缺少ggplot2和geom_line的传说 [英] Missing legend with ggplot2 and geom_line

查看:171
本文介绍了缺少ggplot2和geom_line的传说的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ggplot中绘制线条时,如何显示图例?

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

print(p)

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

 'data.frame':2101 obs。 4个变量:
$ 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 ...


$ $
$ b

解决方案

(x = 1:5,y1 = 1:5,y2 = 2:6)

ggplot(d,aes(x ))+
geom_line(aes(y = y1,color =1))+
geom_line(aes(y = y2,color =2))+
scale_colour_manual = c(red,blue))

但我推荐这样:

  d2 < -  melt(d,id =x)
ggplot(d2,aes(x,value,color =变量))+
geom_line()+
scale_colour_manual(values = c(red,blue))


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

解决方案

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

这篇关于缺少ggplot2和geom_line的传说的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆