简体   繁体   English

R:ggplot2删除一些图例条目

[英]R: ggplot2 removing some legend entries

require(reshape2);require(ggplot2)
df <- data.frame(time = 1:10,
                 x1 = rnorm(10),
                 x2 = rnorm(10),
                 x3 = rnorm(10),
                 y1 = rnorm(10),
                 y2 = rnorm(10))
df <- melt(df, id = "time")


ggplot(df, aes(x = time, y = value, color = variable, group = variable, 
               size = variable, linetype = variable)) +
  geom_line() +
  scale_linetype_manual(values = c(rep(1, 3), 2, 2)) +
  scale_size_manual(values = c(rep(.3, 3), 2, 2)) +
  scale_color_manual(values = c(rep("grey", 3), "red", "green")) +
  theme_minimal()

ggplot2 img

This example might not be very representative, but, for example, imagine running bunch of regression models that individually are not important but just contribute to the picture. 这个例子可能不是很具有代表性,但是,例如,假设运行一堆回归模型,这些回归模型分别并不重要,而只是有助于整体发展。 While I want to emphasize only actual and averaged fit series. 虽然我只想强调实际和平均拟合系列。 So basically variables x are not important and should not appear on legend. 因此,基本上变量x不重要,因此不应出现在图例上。

I've tried to set scale_color_discrete(breaks = c("y1", "y2")) as suggested in some other posts. 我试图按照其他一些帖子中的建议设置scale_color_discrete(breaks = c("y1", "y2")) But the problem is that all of aesthetics are already in use via manual and trying to set another discrete version will override properties that are already set for graph (and mess up whole thing). 但是问题在于,所有美学已经通过手册使用,并且尝试设置另一个离散版本将覆盖已经为图形设置的属性(并弄乱了整个事物)。 So ideally - I'd want to see the exact same graph, but only y1 and y2 displayed in the legend. 因此,理想情况下-我希望看到完全相同的图形,但图例中仅显示y1和y2。

You can try subsetting the data set by the variable name and plotting them separately. 您可以尝试通过变量名称对数据集进行子集设置,然后分别进行绘制。

p <- ggplot(df, aes(x = time, y = value, color = variable, 
                    group = variable, size = variable, linetype = variable)) +  
  geom_line(data=df[which(substr(df$variable,1,1)=='y'),])+   
  scale_linetype_manual(values = c(2, 2)) + scale_size_manual(values = c(2, 2)) + 
  scale_color_manual(values = c("red", "green")) + 
  theme_minimal() + 
  geom_line(data=df[which(substr(df$variable,1,1)=='x'),],
            aes(x = time, y = value, group = variable),
            color="grey",size=0.3,linetype=1)
# Plot elements that have attributes set outside of aes() will
# not appear on legend!

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM