Missing legend with ggplot2 and geom_line

瘦欲@ 提交于 2019-11-26 05:36:12

问题


How does one get a legend to display when plotting lines in ggplot? I\'ve been trying all evening but have been unsuccessful.

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)

Where output is a dataframe with the following structure:

\'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 ...

回答1:


put colour inside the aes like this:

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"))

but I recommend this way:

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


来源:https://stackoverflow.com/questions/5027016/missing-legend-with-ggplot2-and-geom-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!