传统的barplot由于展示信息量少现在已经满足不了时代的需求,是时候赶上潮流使用云雨图了,本节介绍如何快速的从barplot转化成云雨图
在揭开{ggplot2}中stat_图层的神秘面纱这篇文档中介绍了快速绘制barplot的方法,在此再进行一次阐述,详细内容请参考:揭开ggplot2中stat图层的神秘面纱,还是使用我们熟悉的iris数据集合
library(tidyverse)
library(reshape2)
library(gghalves)
library(patchwork)
自定义主题
theme_niwot <- function(){
theme_minimal()+
theme(axis.line = element_line(color = "#3D4852"),
legend.position="non",
axis.ticks = element_line(color = "#3D4852"),
panel.grid.major.y = element_line(color = "#DAE1E7"),
panel.grid.major.x = element_blank(),
plot.margin = unit(rep(1, 4), "cm"),
axis.text = element_text(size = 13, color = "#22292F"),
axis.text.y = element_text(margin = margin(r = 5)),
axis.text.x = element_text(margin = margin(t = 5)))
}
可以看出使用stat_summary函数很方便快速的给barplot添加上了误差线,大大简化了代码
bar <- iris %>%
ggplot(aes(Species,Sepal.Length,fill=Species))+
stat_summary(fun= mean,geom = "bar",width=0.5) +
stat_summary(fun.data = mean_se,geom = "errorbar",width=0.2)+
scale_y_continuous(expand = c(0, 0))+
labs(x=NULL,y=NULL)+theme_niwot()
通过gghalves绘制一半的小提琴图
vio <- iris %>% ggplot(aes(Species,Sepal.Length,fill=Species))+
geom_half_violin(position = position_nudge(x = 0.2),side=2,alpha = 0.8)+
geom_point(aes(y=Sepal.Length, color= Species),
position = position_jitter(width = 0.15),
size = 1,alpha = 0.8)+labs(x=NULL,y=NULL)+
geom_boxplot(width = 0.1, outlier.shape = NA,alpha = 0.8)+
theme_niwot()
bar/vio
喜欢的小伙伴可以关注我的个人公众号R语言数据分析指南,持续分享更多优质资源
网友评论