itle: "手把手教你R语言科研绘图实战 | 地表最强ggplot2高级进阶绘图教程(含代码和案例)"
Author: "米地右"
Date: "2023-10-12"
本教程是前篇ggplot2基础绘图教程的进阶版。为了更好的帮助各位小伙伴快速掌握和熟练运用R语言ggplot2进行科研绘图,本人整理了此地表最强最全ggplot2进阶绘图教程,并附带了代码和示例,希望能够为大家提供一点儿帮助,便于大家参考及学习相关图形代码。
整理不易,如果喜欢的话,请多多点赞、收藏、转发和分享,让更多的人热爱科研。
后续会继续推出R语言科研绘图的系列教程,包括各种图形的高级绘图,TOP期刊如Nature、Science、Cell等具体使用案例及代码,欢迎大家关注本公众号Med2You,也欢迎大家一起交流学习。
本进阶绘图教程涵盖了ggplot2基本绘图,包括散点图、柱状图、抖动图、箱线图、气泡图、气球图、棒棒糖图、哑铃图、华夫饼图、饼图、矩形树图、时序图、坡度图、聚类、脊线图、相关性分析图、QQ图、密度图、直方图、线图、误差条、小提琴图等。
ggplot2进阶绘图汇总
1 相关性(Correlation)
相关性图主要用于分析两个变量之间的相关程度。主要内容有:
-
散点图(Scatterplot)
-
带边界的散点图(Scatterplot With Encircling)
-
抖动图(Jitter Plot)
-
计数图(Counts Chart)
-
气泡图(Bubble Plot)
-
边际直方图/箱线图(Marginal Histogram / Boxplot)
-
相关图(Correlogram)
1.1 散点图(Scatterplot)
数据分析中最常用的图无疑是散点图,主要是用于分析两个变量之间关系的本质。
它可以使用geom_point()绘制。此外,geom_smooth默认情况下会绘制一条平滑线(基于损失),可以通过设置method='lm'来调整以绘制最佳拟合线。
1# install.packages("ggplot2")
2# load package and data
3options(scipen=999) # turn-off scientific notation like 1e+48(关闭科学计数法)
4library(ggplot2)
5theme_set(theme_bw()) # pre-set the bw theme(设置主题)
6
7data("midwest", package = "ggplot2") # 加载数据
8# midwest <- read.csv("http://goo.gl/G1K41K") # bkup data source
9head(midwest)
10
11# Scatterplot 散点图绘制
12gg <- ggplot(midwest, aes(x=area, y=poptotal)) +
13 geom_point(aes(col=state, size=popdensity)) +
14 geom_smooth(method="loess", se=F) +
15 xlim(c(0, 0.1)) +
16 ylim(c(0, 500000)) +
17 labs(subtitle="Area Vs Population",
18 y="Population",
19 x="Area",
20 title="Scatterplot",
21 caption = "Source: midwest")
22
23plot(gg)
Scatterplot 散点图绘制
1.2 带边界的散点图(Scatterplot With Encircling)
在展示结果时,有时需要在图表中加上某些特殊的点或区域组,以便引起人们对某些特殊情况的注意。使用ggalt包中的geom_encircle()可以方便地完成此操作。
1# install 'ggalt' pkg
2# devtools::install_github("hrbrmstr/ggalt")
3options(scipen = 999)
4library(ggplot2)
5library(ggalt)
6midwest_select <- midwest[midwest$poptotal > 350000 &
7 midwest$poptotal <= 500000 &
8 midwest$area > 0.01 &
9 midwest$area < 0.1, ]
10head(midwest_select)
11# Plot
12ggplot(midwest, aes(x=area, y=poptotal)) +
13 geom_point(aes(col=state, size=popdensity)) + # draw points
14 geom_smooth(method="loess", se=F) +
15 xlim(c(0, 0.1)) +
16 ylim(c(0, 500000)) + # draw smoothing line
17 geom_encircle(aes(x=area, y=poptotal),
18 data=midwest_select,
19 color="red",
20 size=2,
21 expand=0.08) + # encircle
22 labs(subtitle="Area Vs Population",
23 y="Population",
24 x="Area",
25 title="Scatterplot + Encircle",
26 caption="Source: midwest")
带边界的散点图(Scatterplot With Encircling)
1.3 抖动图(Jitter Plot)
使用mpg数据集来绘制城市里程(cty)与公路里程(hwy)的散点图
1# load package and data
2library(ggplot2)
3data(mpg, package="ggplot2") # alternate source: "http://goo.gl/uEeRGu")
4theme_set(theme_bw()) # pre-set the bw theme.
5
6g <- ggplot(mpg, aes(cty, hwy))
7
8# Scatterplot
9g + geom_point() +
10 geom_smooth(method="lm", se=F) +
11 labs(subtitle="mpg: city vs highway mileage",
12 y="hwy",
13 x="cty",
14 title="Scatterplot with overlapping points",
15 caption="Source: midwest")
此图非常类似散点图,此图看起来很整洁,清楚地说明了城市里程(cty)和公路里程(hwy)之间的关系。但是,这个图像隐藏了一些东西。你能查出来吗?
1dim(mpg)
2# 234
3# 11
原始数据有234个数据点,但此图显示的数据点似乎较少,发生了什么事呢?
这是因为有许多重叠点显示为一个点。cty和hwy都是源数据集中的整数,这使得隐藏此细节更加容易。所以下次用整数绘制散点图时要格外小心。那怎么处理呢?可以用jitter_geom()绘制抖动图。顾名思义,重叠点是基于由width参数控制的阈值围绕其原始位置随机抖动的。宽度越大,点从其原始位置抖动的位置就越多。
1# load package and data
2library(ggplot2)
3data(mpg, package="ggplot2")
4# mpg <- read.csv("http://goo.gl/uEeRGu")
5
6# Scatterplot
7theme_set(theme_bw()) # pre-set the bw theme.
8g <- ggplot(mpg, aes(cty, hwy))
9g + geom_jitter(width = .5, size=1) +
10 labs(subtitle="mpg: city vs highway mileage",
11 y="hwy",
12 x="cty",
13 title="Jittered Points")
抖动图(Jitter Plot)
1.4 计数图(Counts Chart)
克服数据点重叠问题的第二种方法是使用计数图。如果重叠的点越多,圆的大小就越大。
1# load package and data
2library(ggplot2)
3data(mpg, package="ggplot2")
4# mpg <- read.csv("http://goo.gl/uEeRGu")
5
6# Scatterplot
7theme_set(theme_bw()) # pre-set the bw theme.
8g <- ggplot(mpg, aes(cty, hwy))
9g + geom_count(col="tomato3", show.legend=F) +
10 labs(subtitle="mpg: city vs highway mileage",
11 y="hwy",
12 x="cty",
13 title="Counts Plot")
计数图(Counts Chart)
1.5 气泡图(Bubble Plot)
尽管散点图可比较2个连续变量之间的关系,但如果基于以下内容理解基础组内的关系,则气泡图非常有用
-
分类变量(通过更改颜色)
-
另一个连续变量(通过更改点的大小)
简单来说,如果有4维数据,其中两个是数字(X和Y),另一个是分类(颜色),另一个是数字变量(大小),则气泡图更适合。
1# load package and data
2library(ggplot2)
3data(mpg, package="ggplot2")
4# mpg <- read.csv("http://goo.gl/uEeRGu")
5
6mpg_select <- mpg[mpg$manufacturer %in% c("audi", "ford", "honda", "hyundai"), ]
7
8# Scatterplot
9theme_set(theme_bw()) # pre-set the bw theme.
10g <- ggplot(mpg_select, aes(displ, cty)) +
11 labs(subtitle="mpg: Displacement vs City Mileage",
12 title="Bubble chart")
13
14g + geom_jitter(aes(col=manufacturer, size=hwy)) +
15 geom_smooth(aes(col=manufacturer), method="lm", se=F)
气泡图(Bubble Plot)
-
动画气泡图(Animated Bubble chart)
使用gganimate包可实现动画气泡图。
1# Source: https://github.com/dgrtwo/gganimate
2# install.packages("cowplot") # a gganimate dependency
3# devtools::install_github("dgrtwo/gganimate")
4library(ggplot2)
5library(gganimate)
6library(gapminder)
7theme_set(theme_bw()) # pre-set the bw theme.
8
9ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, frame = year)) +
10 geom_point() +
11 geom_smooth(aes(group = year),
12 method = "lm",
13 show.legend = FALSE) +
14 facet_wrap(~continent, scales = "free") +
15 scale_x_log10() # convert to log scale
1.6 边际直方图/箱线图(Marginal Histogram/Boxplot)
如果要在同一图表中显示关系和分布,请使用边际直方图。它在散点图的边缘处具有X和Y变量的直方图。可以使用ggExtra包ggMarginal()函数实现。除了histogram之外,还可以通过设置相应的选项type来选择绘制箱线图boxplot或density绘图。
1# load package and data
2library(ggplot2)
3library(ggExtra)
4data(mpg, package="ggplot2")
5# mpg <- read.csv("http://goo.gl/uEeRGu")
6
7# Scatterplot
8theme_set(theme_bw()) # pre-set the bw theme.
9mpg_select <- mpg[mpg$hwy >= 35 & mpg$cty > 27, ]
10g <- ggplot(mpg, aes(cty, hwy)) +
11 geom_count() +
12 geom_smooth(method="lm", se=F)
-
绘制边际直方图
1# 绘制边际直方图
2ggMarginal(g, type = "histogram", fill="transparent")
边际直方图
-
绘制边际箱线图
1# 绘制边际箱线图
2ggMarginal(g, type = "boxplot", fill="transparent")
边际箱线图
-
绘制边际密度图
1# 绘制边际核密度图
2ggMarginal(g, type = "density", fill="transparent")
边际密度图
1.7 相关图(Correlogram)
相关图让您检查同一数据帧中存在的多个连续变量的相关性。使用ggcorrplot包可以方便地实现。
1# devtools::install_github("kassambara/ggcorrplot")
2library(ggplot2)
3library(ggcorrplot)
4
5# Correlation matrix
6data(mtcars)
7corr <- round(cor(mtcars), 1)
8head(corr)
9# Plot
10ggcorrplot(corr, hc.order = TRUE, # hc.order是否对相关性矩阵排序
11 type = "lower", # 下三角形显示
12 lab = TRUE, # 是否显示图中数字
13 lab_size = 3, # 图中点的大小
14 method="circle", # 点的形状square or circle
15 colors = c("tomato2", "white", "springgreen3"), # 颜色
16 title="Correlogram of mtcars",
17 ggtheme=theme_bw)
相关图(Correlogram)
2 偏差(Deviation)
比较少量项目(或类别)与固定引用值之间的变化用偏差图最好。本节主要内容有:
-
发散条形图(Diverging bars)
-
发散棒棒糖图(Diverging Lollipop Chart)
-
发散点图(Diverging Dot Plot)
-
面积图(Area Chart)
2.1 发散条形图(Diverging bars)
1library(ggplot2)
2theme_set(theme_bw())
3
4# Data Prep
5data("mtcars") # load data加载数据
6mtcars$`car name` <- rownames(mtcars) # create new column for car names
7mtcars$mpg_z <- round((mtcars$mpg - mean(mtcars$mpg))/sd(mtcars$mpg), 2) # compute normalized mpg
8mtcars$mpg_type <- ifelse(mtcars$mpg_z < 0, "below", "above") # above / below avg flag
9mtcars <- mtcars[order(mtcars$mpg_z), ] # sort
10mtcars$`car name` <- factor(mtcars$`car name`, levels = mtcars$`car name`) # convert to factor to retain sorted order in plot.
11
12# Diverging Barcharts
13ggplot(mtcars, aes(x=`car name`, y=mpg_z, label=mpg_z)) +
14 geom_bar(stat='identity', aes(fill=mpg_type), width=.5) +
15 scale_fill_manual(name="Mileage",
16 labels = c("Above Average", "Below Average"),
17 values = c("above"="#00ba38", "below"="#f8766d")) +
18 labs(subtitle="Normalised mileage from 'mtcars'",
19 title= "Diverging Bars") +
20 coord_flip()
发散条形图(Diverging bars)
2.2 发散棒棒糖图(Diverging Lollipop Chart)
棒棒糖图表传达的信息与条形图和