打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
R|散点图+边际图(柱形图,小提琴图),颜值区UP

散点图作为一种展示2组连续变量关系的常用可视化方式之一,添加点,线,箭头,线段,注释,甚至函数,公式,方差表都没有问题。

ggplot2-annotation|画图点“精”,让图自己“解释”

R-ggpmisc|回归曲线添加回归方程,R2,方差表,香不香?

本文简单的介绍2种散点图添加边际图的方法。

一 载入数据,R包

使用经典数据集iris

library(ggplot2) #加载ggplot2包
library(ggExtra)
library(ggstatsplot)
data(iris)
head(iris)

二 ggplot2 + ggExtra绘制边际散点图

使用ggplot2绘制散点图,然后利用ggExtra包的函数添加边际柱形图

2.1 绘制基础散点图
p1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
 geom_point(color = "#00AFBB")
p1

2.2 添加一点点细节

1)添加横轴,数轴线;

2)添加R2 和 P值

3)添加回归曲线

p2 <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
 geom_point(color = "#00AFBB") +
 geom_smooth(method="lm", se=T) +
 geom_hline(yintercept = 3, linetype = "dashed", color = "blue") +
 geom_vline(xintercept = 6, linetype = "dashed", color = "red") +
 annotate("text", x=4.5, y=4.25, parse=TRUE,

          label="r^2 == 0.0138 * ' p-value = 0.1529' ")

p2

既然是ggplot2绘制的,那更多细节还不是按照需求直接加就行嘛

2.3 添加边际条形图

使用ggMarginal添加, Type 可选参数 histogram, densityboxplot.

ggMarginal(p2, type = "histogram", fill = "#00AFBB")

三 ggstatsplot绘制边际散点图

直接使用ggstatsplot包的ggscatterstats函数绘制

library(ggstatsplot)

ggscatterstats(

 data = iris,                                          
 x = Sepal.Length,                                                  
 y = Sepal.Width,
 xlab = "Sepal Length",
 ylab = "Sepal Width",
 marginal = TRUE,
 marginal.type = "densigram",
 margins = "both",
 xfill = "blue", # 分别设置颜色
 yfill = "#009E73",
 title = "Relationship between Sepal Length and Sepal Width",
 messages = FALSE
)

其中marginal.type可选 histograms,boxplots,density,violin,densigram (density + histogram);可自行尝试效果。

OK,文献中常见的带边际图的散点图就绘制好了!更多参数设置详见参考资料。

参考资料:

https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2

https://indrajeetpatil.github.io/ggstatsplot/

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
一条指令把统计 画图都给做了?似乎太美好!
一文解决基本科研绘图需求(可视化神器ggstatsplot)(1)(概述)
Legends
R统计绘图(1): ggplot2入门指南
ggplot2中facet_grid的分面字体、颜色和背景的修改
生信技能树R语言学习直播配套笔记
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服