其他
ggplot2优雅的绘制配对箱
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「ggplot2」来绘制配对箱线图,针对原有的图形格式做了一些主题上细微的改动使整个图形看起来有了一番新的感觉,下面就来看看具体如何操作
❞
安装R包并加载
package.list=c("tidyverse","ggsignif","ggsci","ggprism")
for (package in package.list) {
if (!require(package,character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
加载数据
df <- read_tsv("data.xls") %>%
filter(year %in% c(1957,2007),continent !="Oceania") %>%
select(country,year,lifeExp,continent)%>%
mutate(paired = rep(1:(n()/2),each=2),year=factor(year))
数据可视化
df %>%
ggplot(aes(year,lifeExp)) +
stat_boxplot(geom="errorbar",position=position_dodge(width=0.2),width=0.1)+
geom_boxplot(position=position_dodge(width =0.2),width=0.4)+
geom_line(aes(group=paired),position = position_dodge(0.2),color="grey80") +
geom_point(aes(fill=year,group=paired,size=lifeExp,alpha=lifeExp),pch=21,
position = position_dodge(0.2))+
scale_size_continuous(range=c(1,3))+
geom_signif(comparisons = list(c("1957","2007")),
map_signif_level=T,vjust=0.5,color="black",
textsize=5,test=wilcox.test,step_increase=0.1)+
facet_wrap(.~continent,nrow=1)+
scale_fill_npg()+
scale_x_discrete(guide = "prism_bracket")+
scale_y_continuous(limits = c(0,90),minor_breaks = seq(0,90,5),guide = "prism_offset_minor")+
labs(x=NULL,y=NULL)+
theme_prism(base_line_size =0.5)+
theme(plot.margin=unit(c(0.5,0.5,0.5,0.5),units=,"cm"),
axis.line = element_line(color = "black",size = 0.4),
panel.grid.minor = element_blank(),
panel.grid.major = element_line(size = 0.2,color = "#e5e5e5"),
axis.text.y = element_text(color="black",size=10),
axis.text.x = element_text(margin = margin(t = -5),color="black",size=10),
legend.position = "none",
panel.spacing = unit(0,"lines"))+
coord_cartesian()
数据获取
❝可以看到通过修改配色并改用「ggprism」包来设置主题参数使得图形更富有美感,转发此文档附上一句话到朋友圈后台截图给我,即可获取对应的数据及代码
❞
欢迎大家扫描下方二维码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
ggplot2优雅的绘制曲面条形图
ggplot2优雅的绘制哑铃图(增强版)
ggplot2优雅绘制小清新版箱线图
使用ggbump带你绘制更加精美的地图