我有一个具有不同物种和观测年份的数据集(分为3类)。我现在想用每个物种的年度观测值为每个物种做一个图,并为每个年类别(每个条形图)分配不同的颜色,但是在每个图中它应该是相同的颜色。
我厌倦了做lapply
,然后对ggplot
做geom_bar
(请参见下面的代码)。我知道我可以用geom_bar(fill = c("#e31a1c", "#ff7f00", "#33a02c")
来分配颜色,但是问题是,有些物种仅在某些年份才被观察到,所以我得到一个错误,即美学与数据的长度不同。那么还有另一种方法可以为条形分配颜色吗?
Species = c(rep("X", 7), rep("Y", 3), rep("Z", 4), "V", rep("W", 3))
Year = c("A", "A", "A", "B", "B", "C", "C","A", "A", "C","B", "B", "C", "C","A", "A", "B", "C")
df <- data.frame(Species, Year)
mylist = lapply(split(df, as.factor(df$Species)), function(memefin){
ggplot(memefin, aes(x = Year, fill = Year))+
geom_bar(fill = c("#e31a1c", "#ff7f00", "#33a02c"))+
ggtitle(memefin$Species)+
scale_x_discrete(breaks=c("A","B","C"),labels=c("2000-2004", "2005-2009", "2010-2014"), drop = F)
})
答案 0 :(得分:2)
您在正确的轨道上:
mylist = lapply(split(df, as.factor(df$Species)), function(memefin){
ggplot(memefin, aes(x = Year, fill = Year))+
geom_bar()+
ggtitle(memefin$Species)+
scale_x_discrete(breaks=c("A","B","C"),labels=c("2000-2004", "2005-2009", "2010-2014"), drop = F)+
scale_fill_manual(values=c("A"="#e31a1c","B"= "#ff7f00","C" ="#33a02c")) # just apply the colours to specific "Years"
})