数据
本文章共用到三个R内嵌的数据集——iris、mpg、mtcars:
iris
mpg
mtcars
散点图的绘制及其拓展
1、基础散点图绘制
library(ggplot2)
p1<-ggplot(iris,aes(Sepal.Length,Sepal.Width,color=Species))+
geom_point()+
theme_bw()
p1
2、具有相关性的散点添加拟合曲线并添加相关系数——使用到了ggpubr包中的stat_cor函数
library(ggpubr)
p1+facet_wrap(~Species)+
geom_smooth(method = lm) +
stat_cor(method = "pearson", label.x = c(5,5,5))
3、局部放大效果的实现(此前文章讲解过,大家自行参考)
library(ggforce)
p1+facet_zoom(x = Species == "versicolor")
4、圈出图中某些数据点
library(ggalt)
library(dplyr)
circle.df <- iris %>% filter(Species == "setosa")
p1+geom_encircle(data = circle.df, linetype = 1)
5、避免散点图中的数据点重叠——使用抖动点或计数点图
# 基础散点图
ggplot(mpg, aes(cty, hwy)) +
geom_point(size = 2)+
theme_bw()
# 抖动点图
ggplot(mpg, aes(cty, hwy)) +
geom_jitter(size = 2, width = 0.5)+
theme_bw()
#计数点图,重叠的点越多,圆的尺寸就越大
ggplot(mpg, aes(cty, hwy)) +
geom_count()+
theme_bw()
6、展示多个变量——气泡图
ggplot(mtcars, aes(mpg, wt, color=cyl)) +
geom_point(aes(size = qsec), alpha = 0.5) +
scale_size(range = c(0.5, 12))+
theme_bw()
7、散点图添加边缘密度图
library(ggpubr)
ggscatterhist(iris, x = "Sepal.Length", y = "Sepal.Width",
color = "Species", size = 3, alpha = 0.6,
palette = c("#00AFBB", "#E7B800", "#FC4E07"),
margin.params = list(fill = "Species", color = "black", size = 0.2))
8、散点图添加边缘箱线图(当然也可通过拼图实现,具体参考此前文章)
library(ggpubr)
ggscatterhist(iris, x = "Sepal.Length", y = "Sepal.Width",
color = "Species", size = 3, alpha = 0.6,
palette = c("#00AFBB", "#E7B800", "#FC4E07"),
margin.plot = "boxplot",
ggtheme = theme_bw())