基本使用:
- 單序列柱形圖:
ggplot(mpg,aes(class,displ))+geom_bar(stat="identity",fill="steelblue")
- 多系列簇狀柱形圖:
ggplot(data=mpg,aes(x=class,fill=factor(year)))+geom_bar(position='stack')
- 並列柱狀圖:
ggplot(data=mpg,aes(x=class,fill=factor(year)))+geom_bar(position='dodge')
- 橫狀條形圖 ( + coord_flip()):
ggplot(data=mpg,aes(x=class,fill=factor(year)))+geom_bar(position='dodge')+coord_flip()
加入 主題 (注意需要載入 ggthemes 包)
ggplot(mydata,aes(Conpany,Sale,fill=Year))+geom_bar(stat="identity",position="dodge")+ggtitle("The Financial Performance of Five Giant")+theme_wsj()+scale_fill_wsj()
ggplot(mydata,aes(Conpany,Sale,fill=Year))+geom_bar(stat="identity",position="dodge")+ggtitle("The Financial Performance of Five Giant")+theme_wsj()+scale_fill_wsj("rgby", "")
ggplot(mydata,aes(Conpany,Sale,fill=Year))+geom_bar(stat="identity",position="dodge")+ggtitle("The Financial Performance of Five Giant")+theme_economist(base_size=14)+scale_fill_economist()+theme(axis.ticks.length=unit(0.5,'cm'))+guides(fill=guide_legend(title=NULL))
- 若需在柱狀上加入數據標籤
- 其中 label 和 最後的geo_text 是負責這個標籤的
ggplot(mydata,aes(Conpany,Sale,fill=Year,label =Sale))+geom_bar(stat="identity",position="dodge")+theme_wsj()+scale_fill_wsj("rgby", "")+theme(axis.ticks.length=unit(0.5,'cm'))+guides(fill=guide_legend(title=NULL))+ggtitle("The Financial Performance of Five Giant")+theme(axis.title = element_blank())+geom_text(aes(y = Sale + 0.05), position = position_dodge(0.9), vjust = -0.5)
Reference:
https://mp.weixin.qq.com/s?__biz=MzA3Njc0NzA0MA==&mid=2653189930&idx=1&sn=bf4bed50468198dd585e40e7b5b36cc4&scene=21#wechat_redirect