Closed ixxmu closed 1 year ago
#相关R包安装与载入:
install.packages('ggside') #稳定版
devtools::install_github('jtlandis/ggside') #开发版
library(ggplot2)
library(ggside)
library(cols4all)
#使用内置鸢尾数据集测试:
df <- iris
head(df)
1.主图绘制
#散点图绘制:
p <- ggplot(data = df,
mapping = aes(x = Petal.Length, y = Petal.Width,
color = Species, fill = Species)) +
geom_point(size = 2) + #添加散点图
geom_smooth(method = 'lm', formula = y ~ x, se = T) #添加拟合曲线
p
#自定义主题和配色:
c4a_gui()
mycol <- c4a('light',3)
mytheme <- theme_bw() +
theme(legend.title = element_blank(),
legend.position = 'right',
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank())
p1 <- p +
scale_fill_manual(values = mycol) +
scale_color_manual(values = mycol) +
mytheme
p1
2.子图绘制
2.1 密度曲线图绘制
#在散点图上方添加密度分布曲线:
p2 <- p1 +
geom_xsidedensity(aes(y = after_stat(density)),
alpha = 0.3,
position = "stack")
p2 #子图和主图共享x轴,独立y轴
#继续在右侧添加密度分布曲线:
p3 <- p2 +
geom_ysidedensity(aes(x = after_stat(density)),
alpha = 0.3,
position = "stack") +
theme_ggside_classic() + #子图独立主题自定义
theme(ggside.panel.scale = 0.3) #子图宽/高度调整
p3
2.2 箱线图绘制
#在散点图上方和右方添加箱线图:
p4 <- p1 +
geom_xsideboxplot(aes(y = Species),
orientation = "y", alpha = 0.3, notch = T) + #在上方添加子箱线图,notch为T则绘制缺口型箱线图
scale_xsidey_discrete() + #将子图y轴原本的连续轴转换为离散轴
geom_ysideboxplot(aes(x = Species),
orientation = "x", alpha = 0.3) + #在右方添加子箱线图
scale_ysidex_discrete() + #将子图x轴原本的连续轴转换为离散轴
theme_ggside_classic() +
theme(ggside.panel.scale = 0.3)
p4 #此时右侧子图x轴标签重叠
#优化一下子图标签角度:
p5 <- p4 + theme(ggside.axis.text.x = element_text(angle = 45,hjust = 1))
p5
2.3 小提琴图绘制
#绘图逻辑和箱线图完全一致
p6 <- p1 +
geom_xsideviolin(aes(y = Species),
orientation = "y", alpha = 0.3, scale = 'width') +
scale_xsidey_discrete() +
geom_ysideviolin(aes(x = Species),
orientation = "x", alpha = 0.3, scale = 'width') +
scale_ysidex_discrete() +
theme_ggside_classic() +
theme(ggside.panel.scale = 0.3,
ggside.axis.text.x = element_text(angle = 45,hjust = 1))
p6
2.4 子图混搭
#密度曲线+箱线图:
p7 <- p1 +
geom_xsidedensity(aes(y = after_stat(density)),
alpha = 0.3,
position = "stack") +
geom_ysideboxplot(aes(x = Species),
orientation = "x", alpha = 0.3) +
scale_ysidex_discrete() +
theme_ggside_classic() +
theme(ggside.panel.scale = 0.3,
ggside.axis.text.x = element_text(angle = 45,hjust = 1))
p7
#如果分组较多也可尝试分面:
p7 + facet_wrap(vars(Species))
参考资料
*未经许可,不得以任何方式复制或抄袭本篇文章之部分或全部内容。版权所有,侵权必究。
基迪奥旗下绘图公众号
分享科研绘图技能与工具
欢迎关注与转发~
你的好友拍了拍你
并请你帮她点一下“分享”~
https://mp.weixin.qq.com/s/BzBnqAFtX5F10H3tZBZ6Bg