首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >缺少带有ggplot2和geom_line的图例

缺少带有ggplot2和geom_line的图例
EN

Stack Overflow用户
提问于 2011-02-17 17:18:38
回答 1查看 29.7K关注 0票数 28

如何在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)

其中,output是具有以下结构的数据帧:

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-17 17:35:52

像这样将颜色放入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"))
票数 48
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5027016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档