【问题标题】:R: ggplot2 removing some legend entriesR:ggplot2 删除一些图例条目
【发布时间】:2016-02-20 19:48:24
【问题描述】:
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()

这个例子可能不是很有代表性,但是,例如,想象一下运行一堆单独不重要但只是有助于图片的回归模型。虽然我只想强调实际和平均拟合系列。所以基本上变量 x 并不重要,不应该出现在图例中。

我尝试按照其他一些帖子中的建议设置scale_color_discrete(breaks = c("y1", "y2"))。但问题是所有美学都已经通过手动使用,并且尝试设置另一个离散版本将覆盖已经为图形设置的属性(并搞砸整个事情)。所以理想情况下 - 我希望看到完全相同的图表,但图例中只显示 y1 和 y2。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以尝试按变量名称对数据集进行子集化并分别绘制。

    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!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-28
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多