ggplot legend key color and items

末鹿安然 提交于 2019-12-24 01:45:24

问题


Using the following data frame:

sdf<-data.frame(hours=gl(n=3,k=1,length=9,labels=c(0,2,4)),    
                count=c(4500,1500,2600,4000,800,200,1500,50,20),
                machine=gl(n=3,k=3,length=9,labels=c("A","B","C")))

The following graph can be produced using either of these scripts:

ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+
  geom_area(data=sdf[sdf$machine=="A",])+
  geom_area(data=sdf[sdf$machine=="B",])+
  geom_area(data=sdf[sdf$machine=="C",])

ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+
  geom_area(position="dodge")

However, when the fill color is changed, the item in the legend disappears.

ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+
  geom_area(data=sdf[sdf$machine=="A",])+
  geom_area(data=sdf[sdf$machine=="B",],fill="darkorchid")+
  geom_area(data=sdf[sdf$machine=="C",])

Ideally, the legend should show the color change.

Question: What script can create items in a legend as well as offer color controls for those items?


回答1:


You can adjust the values assigned to any aesthetic using scale_X_manual(values=(whatever)). Here you want scale_fill_manual.

ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+
  geom_area(position="dodge") + 
  scale_fill_manual(values=c("red", "darkorchid", "green"))

Note that, as a rule, you want to let ggplot group the data for you, as you have done in your second ggplot call (This is what the group argument does). Supplying each 'slice' of data separately, as you have done in your first example, pretty much defeats the purpose of ggplot2, and should be avoided.



来源:https://stackoverflow.com/questions/18519243/ggplot-legend-key-color-and-items

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