给定以下数据:
data <- data.frame(Train = rep(c(20,30,40,50),2), xi = runif(8,0,1), category = c(rep("0.3_val",4),rep("0.3_test",4)))
data <- rbind(data, data.frame(Train = rep(c(20,30,40,50),2), xi = runif(8,0,1), category = c(rep("0.6_val",4),rep("0.6_test",4))))
如果考虑上面代码中的数据,线型和颜色的图例将合并为一个图例:
p <- ggplot(data = data, aes(x = Train, y = xi, group = category, color = category)) +
geom_line(aes(color = category,linetype=category)) +
geom_hline(yintercept = 1) +
theme_bw() +
xlab(expression(italic("n"))) +
ylab(expression(xi)) +
theme(panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"), legend.title=element_text(size=4)) +
theme(legend.key.size = unit(0.2, 'cm')) + guides(fill=guide_legend(title=ylab)) +
theme(strip.background =element_rect(color = "black",fill="white")) +
scale_colour_manual(name="Legend", values=c("black","black","grey","grey"))+
scale_linetype_manual(name="Legend", values=c("dashed", "twodash","dashed", "twodash","dashed", "twodash"))
print(p)
如果现在图例标签更改为希腊符号(表达式),则图例将一分为二,尽管scale_x_manual()中的名称和标签相同:
p <- ggplot(data = data, aes(x = Train, y = xi, group = category, color = category)) +
geom_line(aes(color = category,linetype=category)) +
geom_hline(yintercept = 1) +
theme_bw() +
xlab(expression(italic("n"))) +
ylab(expression(xi)) +
theme(panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"), legend.title=element_text(size=4)) +
theme(legend.key.size = unit(0.2, 'cm')) + guides(fill=guide_legend(title=ylab)) +
theme(strip.background =element_rect(color = "black",fill="white")) +
scale_colour_manual(name="Legend", values=c("black","black","grey","grey"),
labels=c("0.3_val"=expression(xi[0.3]^{val}),
"0.3_test"=expression(xi[0.3]^{test}),
"0.6_val"=expression(xi[0.6]^{val}),
"0.6_test"=expression(xi[0.6]^{test})))+
scale_linetype_manual(name="Legend", values=c("dashed", "twodash","dashed", "twodash"),
labels=c("0.3_val"=expression(xi[0.3]^{val}),
"0.3_test"=expression(xi[0.3]^{test}),
"0.6_val"=expression(xi[0.6]^{val}),
"0.6_test"=expression(xi[0.6]^{test})))
print(p)
在scale_x_manual()中使用表达式时,如何避免这个问题,使图例从两个变为一个?
1条答案
按热度按时间dsekswqp1#
可以关闭线型向导并替代颜色向导的美观性:
出于某种原因,预先将标签存储为表达式对象也可以,并且需要的输入少一些: