欢迎来到医科研,这里是白介素2的读书笔记,跟我一起聊临床与科研的故事, 生物医学数据挖掘,R语言,TCGA、GEO数据挖掘。
cowplot包
cowplot包是ggplot2的简单附加组件。它旨在为ggplot2提供一个出版物就绪的主题,一个需要最小量的轴标签尺寸,情节背景等。它的主要目的是方便制作符合要求的图片。除了提供修改的绘图主题外,此包还提供了对ggplot2绘图的自定义注释的功能。 事实证明,提供此功能的最简单方法是在ggplot2之上实现通用绘图画布。因此,使用此软件包可以获得非常不寻常的效果。
举例演示 如果你觉得ggplot2的默认主题并不好看
1library(ggplot2) 2ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 3 geom_point(size = 2.5)
image.pngcowplot调整 可以注意到灰色背景去除了,其实还有些细微尺寸上的细微差别
1library(cowplot) 2ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 3 geom_point(size = 2.5)
image.png更重要的是cowplot的默认主题与 save_plot 函数很好的衔接起来,这样输出的pdf文件不需要再增加其它参数就已经很好了
1library(cowplot) 2plot.mpg <-ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 3 geom_point(size=2.5) 4# use save_plot() instead of ggsave() when using cowplot 5save_plot("mpg.png", plot.mpg, 6 base_aspect_ratio = 1.3 # 给legend留出一定的空间 7) 8plot.mpg 9
image.png增加网格线 cowplot默认状态下为无网格线 background_grid()函数可以增加背景网格线
1plot.mpg+background_grid(major = "xy",minor = "none")
image.png更改主题 theme_set函数能够方便的更改主题
1theme_set(theme_light()) 2plot.mpg
image.pngcowplot组图功能 ggplot2的一个限制是它不容易为标题添加标签和其他注释。ggplot2严格地将绘图面板(轴内的部分)与绘图的其余部分分开,虽然通常可以直接修改其中一个,但我们不能轻易地更改它们。为了以通用方式解决这个问题,cowplot在ggplot2之上实现了一个通用的绘图层。在此绘图层中,您可以在图形顶部添加任意图形元素。 在学术绘图中我们经常可能需要组合多个图的情况
假设我们要组合这两个图 1plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 2 geom_point(size=2.5) 3plot.mpg 4plot.diamonds <- ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() + 5 theme(axis.text.x = element_text(angle=70, vjust=0.5)) 6plot.diamonds 7
image.png
image.png1plot_grid(plot.mpg, plot.diamonds, labels = c("A", "B"))
image.png对齐坐标轴设置 align参数,h表示 horizontally 水平对齐, vertically ("v") 垂直对齐
1plot_grid(plot.mpg, plot.diamonds, labels = c("A", "B"),align = "h")
image.png指定输出的行列 通常plot_grid会自动合理的输出,但也可根据需要自行指定
1plot_grid(plot.mpg, plot.diamonds, labels = c("A", "B"),align="v",nrow = 2)
image.pngsave_plot函数输出文件 plot_grid能够很好的配合save_plot函数输出文件 假设我们要输出一个2*2的文件,注意除在plot_grid文件中指定行列外,save_plot也需要指定
1plot2by2 <- plot_grid(plot.mpg, NULL, NULL, plot.diamonds, 2 labels=c("A", "B", "C", "D"), ncol = 2) 3save_plot("plot2by2.png", plot2by2, 4 ncol = 2, # we're saving a grid plot of 2 columns 5 nrow = 2, # and 2 rows 6 # each individual subplot should have an aspect ratio of 1.3 7 base_aspect_ratio = 1.3 8 ) 9plot2by2
image.png类的图形注释 我们要在之前的图形上添加图注 draw_plot_label参数编号 draw_label参数:增加文字图注
1ggdraw(plot.mpg) + 2 draw_plot_label("A", size = 14) + 3 draw_label("DRAFT!", angle = 45, size = 80, alpha = .2)
image.png给之前的图添加标签
1# plot.mpg and plot.diamonds were defined earlier 2library(viridis) 3ggdraw() + 4 draw_plot(plot.diamonds + theme(legend.justification = "bottom"), 0, 0, 1, 1) + 5 draw_plot(plot.mpg + scale_color_viridis(discrete = TRUE) + 6 theme(legend.justification = "top"), 0.5, 0.52, 0.5, 0.4) + 7 draw_plot_label(c("A", "B"), c(0, 0.5), c(1, 0.92), size = 15)
image.png 除此以外cowplot还有其它更高级的功能,但是可能用的不多,我们不再详细介绍参考源代码链接(https://github.com/wilkelab/cowplot)
|