箱线图展示的就是分位数,中间的线表示的是中位数,也就是50%分位数,如果非要在箱线图上画上表示平均值的线段也是可以实现的,今天介绍一下实现代码
示例数据集我们用R语言的内置数据集PlantGrowth
image.png
df<-read.csv("PlantGrowth.csv")
library(ggplot2)
library(tidyverse)
p1<-ggplot(data=df,
aes(x=group,y=weight))+
geom_boxplot(aes(fill=group))
p1
image.png
ggplot_build(p1)$data[[1]]
image.png
df %>%
group_by(group) %>%
summarise(mean_value=mean(weight)) %>%
rename("group_1"="group") %>%
cbind(ggplot_build(p1)$data[[1]]) -> df1
p1+
geom_segment(data=df1,
aes(x=xmin,xend=xmax,
y=mean_value,
yend=mean_value),
color="red")
image.png
找到一种办法是重新画一条线把原来的中位数的线给盖住
p1+
geom_segment(data=df1,
aes(x=xmin,xend=xmax,
y=mean_value,
yend=mean_value),
color="black",
size=4)+
geom_segment(data=df1,
aes(x=xmin+0.005,xend=xmax,
y=middle,
yend=middle,
color=group_1),
show.legend = F,
size=5)
image.png
ggplot(data=df,
aes(x=group,y=weight))+
stat_boxplot(geom="errorbar",
width=0.2)+
geom_boxplot(aes(fill=group))+
geom_segment(data=df1,
aes(x=xmin,xend=xmax,
y=mean_value,
yend=mean_value),
color="black",
size=4)+
geom_segment(data=df1,
aes(x=xmin+0.005,xend=xmax,
y=middle,
yend=middle,
color=group_1),
show.legend = F,
size=5)+
theme_bw()+
theme(legend.position = "top")
image.png
这个方法还是比较繁琐的,不知道有没有比较好的办法
(猜测geom_boxplot函数里应该是有一个步骤计算中位数的,试着看看源代码,看能不能把中位数的代码改为平均值)
还有一个问题是如果是分组的箱线图那么应该如何来实现呢?
欢迎大家关注我的公众号
小明的数据分析笔记本
小明的数据分析笔记本 公众号 主要分享:1、R语言和python做数据分析和数据可视化的简单小例子;2、园艺植物相关转录组学、基因组学、群体遗传学文献阅读笔记;3、生物信息学入门学习资料及自己的学习笔记!