【问题标题】:Missing legend with ggplot2 and geom_lineggplot2 和 geom_line 缺少图例
【发布时间】:2011-02-17 09:18:37
【问题描述】:

在 ggplot 中绘制线条时如何显示图例?我整个晚上都在尝试,但没有成功。

p <- ggplot(output, aes(lambda), legend=TRUE) +
  geom_line(aes(y=train.err), colour="red", label="r") +
  geom_line(aes(y=test.err), colour="blue", label="b") +
  geom_line(aes(y=data.err), colour="green", label="g")

print(p)

其中输出是具有以下结构的数据框:

'data.frame':   2101 obs. of  4 variables:
 $ lambda   : num  3.06e-07 3.09e-07 3.12e-07 3.15e-07 3.18e-07 ...
 $ train.err: num  0.415 0.415 0.415 0.415 0.415 ...
 $ test.err : num  0.373 0.373 0.373 0.373 0.373 ...
 $ data.err : num  0.398 0.398 0.398 0.398 0.398 ...

【问题讨论】:

    标签: r ggplot2 legend linechart


    【解决方案1】:

    像这样在 aes 中添加颜色:

    d<-data.frame(x=1:5, y1=1:5, y2=2:6)
    
    ggplot(d, aes(x)) + 
      geom_line(aes(y=y1, colour="1")) + 
      geom_line(aes(y=y2, colour="2")) +
      scale_colour_manual(values=c("red", "blue"))
    

    但我推荐这种方式:

    d2 <- melt(d, id="x")
    ggplot(d2, aes(x, value, colour=variable)) + 
      geom_line() +
      scale_colour_manual(values=c("red", "blue"))
    

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 2018-11-22
      • 1970-01-01
      • 2014-10-11
      • 2015-08-02
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多