【ggplot2绘图四:条形图】

2021.4.26
持续更新中。。。

参考:《R数据可视化手册》、学术数据分析及可视化

1. 简单条形图

BOD
str(BOD)

ggplot(BOD, aes(x=Time, y=demand)) + 
  #设置条形图的形式、填充色、变宽色和宽带
  geom_bar(stat="identity", fill="lightblue",
          colour="black", width=0.5)+
  #设置标签、垂直距离
  geom_text(aes(label=demand), vjust=-0.2)
  ##x轴为离散型变量,X轴的变化
  ##ggplot(BOD, aes(x=factor(Time), y=demand)) + geom_bar(stat = "identity")

判断x轴变量是连续性还是因子型很重要
条形图中stat = 'identity'不能少!

2. 单个条形图添加误差线

ce <- subset(cabbage_exp, Cultivar == "c39")
ggplot(ce, aes(x = Date, y = Weight))+
  geom_bar(stat = "identity", fill = "white", color = "black")+
  #添加误差线,设置误差线大小
  geom_errorbar(aes(ymin=Weight-se, ymax=Weight+se),width=0.2)

3. 簇状条形图添加误差线

ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar))+
  #设置条形图堆叠方式
  geom_bar(stat="identity", position="dodge")+
  geom_errorbar(aes(ymin=Weight-se,ymax=Weight+se), 
            position=position_dodge(0.9),width=0.2)

绘制簇状条形图时,需要用position = "dodge"来避免条形图堆积

4. 堆积条形图

#设置条形图基本信息
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar), 
       order=desc(Cultivar))+
  geom_bar(stat="identity")
##调整图例的顺序
##guides(fill=guide_legend(revers=TRUE))

order = desc()可以调整条形图的堆叠顺序

5. 绘制百分比堆积条形图

library(plyr)
cabbage_exp
##将每组条形对应的数据标准化为100%格式
ce <- ddply(cabbage_exp, "Date", transform,
            percent_weight=Weight/sum(Weight)*100)
ggplot(ce, aes(x=Date, y=percent_weight, fill=Cultivar))+
  geom_bar(stat="identity")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容