R语言ggplot2分组箱线图添加误差线的简单小例子
2021-10-05 本文已影响0人
小明的数据分析笔记本
ggplot2 更改图例的顺序
箱线图添加误差线这个自己老是记不住,每次作图都得现查,今天的推文记录一下实现代码,方便自己以后查看。
首先是示例数据集
示例数据集还是使用鸢尾花数据集
部分如下

收下是读取数据
df<-read.csv("iris.csv")
head(df)
宽格式转换为长格式
reshape2::melt(df,id.vars="Species") -> dfa
基本箱线图
ggplot(data = dfa,
aes(x=Species,y=value,fill=Species))+
geom_boxplot()

添加误差线
这里使用到的是stat_boxplot()
函数
ggplot(data = dfa,
aes(x=Species,y=value,fill=Species))+
geom_boxplot()+
stat_boxplot(geom = "errorbar",
width=0.3)

这样多了一个垂直线,不好看,我们把误差线的图层放到最下层,就是把代码写到boxplot的前面,然后加一些基本的美化
ggplot(data = dfa,
aes(x=Species,y=value,fill=Species))+
stat_boxplot(geom = "errorbar",
width=0.3)+
geom_boxplot(width=0.5)+
scale_fill_material_d()+
theme_bw()

这里还有一个小知识点是更改图例的顺序,现在图例从上到下依次是 setosa versicolor virginica,如果要反过来可以加一行代码guides(fill=guide_legend(reverse = T))
ggplot(data = dfa,
aes(x=Species,y=value,fill=Species))+
stat_boxplot(geom = "errorbar",
width=0.3)+
geom_boxplot(width=0.5)+
scale_fill_material_d()+
theme_bw()+
guides(fill=guide_legend(reverse = T))

分组箱线图
ggplot(data = dfa,
aes(x=Species,y=value,fill=variable))+
stat_boxplot(geom = "errorbar",
width=0.3,
position = position_dodge(0.5))+
geom_boxplot(width=0.5,
position = position_dodge(0.5))+
scale_fill_material_d()+
theme_bw()+
guides(fill=guide_legend(reverse = T))

分组箱线图需要我们在stat_boxplot()
函数和geom_boxplot()
函数里分别加上position = position_dodge(0.5)
参数,目的是使误差线和箱子的位置对应上
如果不加这两个参数,效果如下

这里还有一个疑问是 箱线图中间的线好像是中位数,如何把这个线更改为平均值呢?暂时没有想明白
今天推文的示例数据和代码可以直接留言20210929获取
欢迎大家关注我的公众号
小明的数据分析笔记本
小明的数据分析笔记本 公众号 主要分享:1、R语言和python做数据分析和数据可视化的简单小例子;2、园艺植物相关转录组学、基因组学、群体遗传学文献阅读笔记;3、生物信息学入门学习资料及自己的学习笔记!