【发布时间】:2019-12-04 10:02:27
【问题描述】:
试图用 ggplot2 绘制一些图,但无法弄清楚颜色是如何按照 aes 中定义的那样工作的。与审美长度的错误作斗争。
我尝试在主要的 ggplot 调用 aes 中定义颜色以给出图例,但也在 geom_line aes 中。
# Define dataset:
number<-rnorm(8,mean=10,sd=3)
species<-rep(c("rose","daisy","sunflower","iris"),2)
year<-c("1995","1995","1995","1995","1996","1996","1996","1996")
d.flowers<-cbind(number,species,year)
d.flowers<-as.data.frame(d.flowers)
#Plot with no colours:
ggplot(data=d.flowers,aes(x=year,y=number))+
geom_line(group=species) # Works fine
#Adding colour:
#Defining aes in main ggplot call:
ggplot(data=d.flowers,aes(x=year,y=number,colour=factor(species)))+
geom_line(group=species)
# Doesn't work with data size 8, asks for data of size 4
ggplot(data=d.flowers,aes(x=year,y=number,colour=unique(species)))+
geom_line(group=species)
# doesn't work with data size 4, now asking for data size 8
第一个情节给出 错误:美学必须是长度1或与数据相同(4):组
第二个给出 错误:美学必须是长度 1 或与数据 (8) 相同:x、y、颜色
所以我很困惑 - 当给定长度为 4 或 8 的 aes 时,它并不高兴!
我怎样才能更清楚地考虑这一点?
【问题讨论】:
-
你确定第一个情节可以正常工作吗?我认为它分配了错误的组。一般问题是您在
aes之外定义group = species,因此它采用向量species而不是d.flowers的列。尝试例如geom_line(aes(group=species))或将group=species添加到您的ggplot-call -
另一个问题是您使用
cbind将您的数据转换为字符矩阵,然后使用as.data.frame将它们转换为因子。最好使用data.frame(number,species,year)。