暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

R语言绘图|ggplot2绘图过程中主题(theme)使用

3394
点击关注了解更多哦

在绘图过程中利用主题不仅可以简化绘图code,也可以实现快速对图形的调整。本文主要以ggplot2[1]ggthemes[2]egg[3]cowplot[4]ggdark[5]等5种不同R包中内置主题为例展示主题效果。

图形准备

先绘制一个基础图形,这里以R自带的mtcars数据集中为例,绘制mpg变量和hp变量的散点图,并添加一条线性回归拟合曲线,基础图形见下方的“默认主题”图。此外,关于如何利用ggplot2绘制更多形式的散点图及添加回归拟合曲线可参考R语言绘图|散点图与回归拟合曲线

#没有安装相关package需要先进行安装
#install.packages("ggplot2")
#install.packages("gcookbook")
library(ggplot2)
library(gcookbook)
#使用mtcars数据
head(mtcars)
#                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
p <- ggplot(mtcars, aes(x = mpg, y = hp)) + #制定数据,对数据进行映射
  geom_point() + #散点图图层
  geom_smooth(method = lm) # 添加拟合曲线
#查看图形(图形见默认主题格式)

1、ggplot2中的主题

主题的添加方式为图层叠加,如需要添加theme_bw() 主题 ,即用基础图形+主题图层,具体code如下,不同的主题名称见图形上方。

p + theme_bw()
#或者
ggplot(mtcars, aes(x = mpg, y = hp)) + 
  geom_point() + 
  geom_smooth(method = lm) + 
  theme_bw()


2、ggthemes中的主题

#install.packages("ggthemes")
library(ggthemes)

主题名称见图形上方:

3、cowplot中的主题

#install.packages("cowplot")
library(cowplot)

主题名称见图形上方:

4、egg中的主题

主题名称见图形上方:

5、ggdark中的主题

ggdark包以ggplot2包中的主题风格为主,对其进行暗黑式渲染,主题名称见图形上方:

其他

此外,也可以尝试构建自己的主题风格,在后续的绘图过程中可以快速调用主题。


如有帮助请多多点赞哦!

参考资料

[1]

ggplot2: https://cran.r-project.org/web/packages/ggplot2/index.html

[2]

ggthemes: https://cran.r-project.org/web/packages/ggthemes/index.html

[3]

egg: https://cran.r-project.org/web/packages/egg/vignettes/Overview.html

[4]

cowplot: https://cran.r-project.org/web/packages/cowplot/index.html

[5]

ggthemes: https://cran.r-project.org/web/packages/ggdark/index.html


文章转载自日常分享的小懒猫,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论