數(shù)據(jù)
本文章共用到三個(gè)R內(nèi)嵌的數(shù)據(jù)集——iris寝优、mpg分尸、mtcars:
iris
mpg
mtcars
散點(diǎn)圖的繪制及其拓展
1、基礎(chǔ)散點(diǎn)圖繪制
library(ggplot2)
p1<-ggplot(iris,aes(Sepal.Length,Sepal.Width,color=Species))+
geom_point()+
theme_bw()
p1
2业踢、具有相關(guān)性的散點(diǎn)添加擬合曲線并添加相關(guān)系數(shù)——使用到了ggpubr包中的stat_cor函數(shù)
library(ggpubr)
p1+facet_wrap(~Species)+
geom_smooth(method = lm) +
stat_cor(method = "pearson", label.x = c(5,5,5))
3玻淑、局部放大效果的實(shí)現(xiàn)(此前文章講解過俗或,大家自行參考)
library(ggforce)
p1+facet_zoom(x = Species == "versicolor")
4、圈出圖中某些數(shù)據(jù)點(diǎn)
library(ggalt)
library(dplyr)
circle.df <- iris %>% filter(Species == "setosa")
p1+geom_encircle(data = circle.df, linetype = 1)
5岁忘、避免散點(diǎn)圖中的數(shù)據(jù)點(diǎn)重疊——使用抖動(dòng)點(diǎn)或計(jì)數(shù)點(diǎn)圖
# 基礎(chǔ)散點(diǎn)圖
ggplot(mpg, aes(cty, hwy)) +
geom_point(size = 2)+
theme_bw()
# 抖動(dòng)點(diǎn)圖
ggplot(mpg, aes(cty, hwy)) +
geom_jitter(size = 2, width = 0.5)+
theme_bw()
#計(jì)數(shù)點(diǎn)圖,重疊的點(diǎn)越多区匠,圓的尺寸就越大
ggplot(mpg, aes(cty, hwy)) +
geom_count()+
theme_bw()
6干像、展示多個(gè)變量——?dú)馀輬D
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、散點(diǎn)圖添加邊緣密度圖
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驰弄、散點(diǎn)圖添加邊緣箱線圖(當(dāng)然也可通過拼圖實(shí)現(xiàn)麻汰,具體參考此前文章)
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())