在用RStudio的ggplot2包进行画图时常常记不住对应的美化代码,检索又要花费大量的时间。今天给大家推荐一款非常容易上手,且能够解决大家记不住代码痛点的RStudio扩展R包ggThemeAssist。
ggThemeAssist[1]是一个RStudio的扩展R包,提供了一种用于修改ggplot2主题的图形交互式界面。
在安装ggThemeAssist之前,需要安装稳定或者最新的RStudo(v0.99.878 or later)。此外,ggThemeAssist依赖于shiny和miniUI,如果本地尚未安装,通过BiocManager::install()安装即可。
if (!requireNamespace("devtools", quietly = TRUE))
install.packages("devtools")
devtools::install_github("calligross/ggthemeassist")
install.packages("ggThemeAssist") # 或BiocManager::install("ggThemeAssist")
用法非常的简单,下载安装后先重启RStudio,选中一段ggplot的作图代码,在RStuido的Addins按钮处即可打开该插件。
可以调节的内容有图形的比例(Settings)、调色板和背景(Panel&Background)、坐标轴(Axis)、标题和标签(Title and label)、图例(Legend)、副标题和说明文字(Subtitle and Caption)。
设置好以后,点击右上角的“Done”即可在原作图代码的基础上添加修改代码,重新运行作图代码即可完成修改。
本次我们采用ggplot2的内置数据diamonds,考虑到diamonds的数据太多,我们随机选出部分做演示。
library(ggplot2)
library(dplyr) # 需要使用dplyr提取数据
data("diamonds")
small_dia = sample_n(diamonds,size = 1000) # 随机取出1000个数据
我们以carat为x,price为y,cut映射给color作一个点图。
ggplot(data = small_dia,
aes(x= carat,y=price,color = cut))+
geom_point()
选中作图代码并打开ggThemeAssist,在里面进行修改,为了有较大区分,我特意选择了差异很大的颜色。
ggplot(data = small_dia,
aes(x= carat,y=price,color = cut))+
geom_point() + theme(panel.grid.major = element_line(linetype = "dashed"),
panel.background = element_rect(fill = "cornflowerblue"),
plot.background = element_rect(fill = "antiquewhite"))
调色板和背景(Panel&Background)
ggplot(data = small_dia,
aes(x= carat,y=price,color = cut))+
geom_point() + theme(axis.line = element_line(colour = "bisque1",
size = 3, linetype = "dashed"), axis.ticks = element_line(size = 2),
axis.text = element_text(size = 14, colour = "cornflowerblue"),
axis.text.x = element_text(family = "mono",
size = 14), axis.text.y = element_text(size = 14))
坐标轴(Axis)
ggplot(data = small_dia,
aes(x= carat,y=price,color = cut))+
geom_point() + theme(axis.title = element_text(face = "italic",
colour = "brown3", angle = 45), plot.title = element_text(family = "serif",
size = 20, face = "bold", hjust = 0.5)) +labs(title = "this is the main title", x = "caratttttttt",
y = "priceeeeeeeee")
标题和标签(Title and label)
ggplot(data = small_dia,
aes(x= carat,y=price,color = cut))+
geom_point() + theme(legend.text = element_text(family = "mono"),
legend.title = element_text(size = 20,
face = "bold", family = "mono", colour = "brown4"),
legend.key = element_rect(fill = "hotpink",
linetype = "solid"), legend.background = element_rect(fill = "gray90"),
legend.position = "bottom", legend.direction = "horizontal")
图例(Legend)
ggplot(data = small_dia,
aes(x= carat,y=price,color = cut))+
geom_point() + theme(plot.subtitle = element_text(size = 20,
colour = "gray26"), plot.caption = element_text(family = "serif",
size = 20, face = "italic")) +labs(subtitle = "the subtitle", caption = "This is a very beautiful pic")
副标题和说明文字(Subtitle and Caption)
还不抓紧去试试! 参考资料
[1] ggThemeAssist: https://github.com/calligross/ggthemeassist