zl程序教程

您现在的位置是:首页 >  其他

当前栏目

R包|用SCI文章的配色画图

2023-03-07 09:16:30 时间

我们在进行R进行画图时,常常会感叹默认配色难看,又不愿去找配色。因此,本期给大家推荐R包ggsci[1]解决以上问题。

ggsci提供了一个ggplot2调色板集合,其灵感来自科学期刊、数据可视化图书馆、科幻电影和电视节目,并不是期刊官方提供的配色

通过vignette("ggsci") 在其帮助文档里我们可以发现共有16种主题。

比如NPG,由Nature的配色汇总而来;再比如AAAS,由Science的配色汇总而来。

NPG

安装

使用ggsci之前,首先要安装好ggplot2。

Install from CRAN

install.packages("ggsci")

Install from GitHub

remotes[2]:Download and install R packages stored in GitHub, GitLab, Bitbucket, Bioconductor, or plain subversion or git repositories. This package is a lightweight replacement of the install_* functions in devtools. Indeed most of the code was copied over from devtools.

remotes::install_github("nanxstats/ggsci")

事实上,现在BiocManager::install()已经可以自动识别包的来源,直接使用BiocManager::install("ggsci") 即可。

使用

ggsci使用起来非常简单,只需要在画图命令中加入scale_color_xxx(xxx为你需要的配色主题)。

示例数据

我们采用ggplot2的内置数据diamonds中的部分数据来演示。

library(ggplot2)
library(dplyr) 
data("diamonds")
small_dia = sample_n(diamonds,size = 1000) # 从diamonds中随机抽取1000个数据

small_dia示例

绘图演示

将carat映射给x,price映射给y,以cut作为颜色的分组信息绘图。

ggplot(data = small_dia,
       aes(x= carat,y=price,color = cut))+
  geom_jitter()+
  theme_classic()

default

Nature配色

我们再加上scale_color_npg()采用Nature配色

ggplot(data = small_dia,
       aes(x= carat,y=price,color = cut))+
  geom_jitter()+
  scale_color_npg()+
  theme_classic()

scale_color_npg

Science配色

ggplot(data = small_dia,
       aes(x= carat,y=price,color = cut))+
  geom_jitter()+
  scale_color_aaas()+
  theme_classic()

scale_color_aaas

Rick and Morty配色

ggplot(data = small_dia,
       aes(x= carat,y=price,color = cut))+
  geom_jitter()+
  scale_color_rickandmorty()+
  theme_classic()

scale_color_rickandmorty

还不抓紧去试试!

参考资料

[1] ggsci: https://nanx.me/ggsci/

[2] remotes: https://remotes.r-lib.org/