散点图作为一种展示2组连续变量关系的常用可视化方式之一,添加点,线,箭头,线段,注释,甚至函数,公式,方差表都没有问题。
本文简单的介绍2种散点图添加边际图的方法。
一 载入数据,R包
使用经典数据集iris
library(ggplot2) #加载ggplot2包
library(ggExtra)
library(ggstatsplot)
data(iris)
head(iris)
二 ggplot2 + ggExtra绘制边际散点图
使用ggplot2
绘制散点图,然后利用ggExtra
包的函数添加边际柱形图
p1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point(color = "#00AFBB")
p1
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绘制的,那更多细节还不是按照需求直接加就行嘛
使用ggMarginal
添加, Type 可选参数 histogram, density 和 boxplot.
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/
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有