ggplot2使用技巧

R Graphics Cookbook, 2nd edition

https://r-graphics.org/

ggplot2高效实用指南 - 生信宝典

https://mp.weixin.qq.com/s/v3qtAgIMpo6vxxHUjlFagQ

ggplot2实用教程精选 - YuLabSMU

https://mp.weixin.qq.com/s/8dZA2HkrBytuvlSepQ1Ucw

Use R package export to export Rplots to PPT

export is an R package to easily export active R graphs and statistical output in publication quality to Microsoft Office, HTML, and Latex. More information on GitHub.

Get the latest development version from GitHub

Getting Started

An example Rscript

by liuyujie0136

对数据框的不同列循环作图

使用aes_string

Use coord_cartesian instead of scale_y_continuous

Example:

From the coord_cartesian documentation:

Setting limits on the coordinate system will zoom the plot (like you're looking at it with a magnifying glass), and will not change the underlying data like setting limits on a scale (e.g. scale_y_continuous) will.

You can also use scale_y_continuous alongside coord_cartesian to modify breaks, minor_breaks and expand etc. Just don't supply it with the ylim argument!

在散点图上添加线性拟合方程和R值

借用ggpubr

ggplot2多子图对齐坐标轴

https://zhuanlan.zhihu.com/p/161401082

使用cowplot::plot_grid(align = "vh"),(align = "v":垂直方向上对齐,align = "h":水平方向上对齐)

例:plot_grid(p1, p2, p3, p4, ncol = 2, align = "vh")

另,可用于 ggplot2 子图排版的 package 有:

  • gridExtra

  • patchwork

  • cowplot

ggplot2多子图合并图例

https://wilkelab.org/cowplot/articles/shared_legends.html

使用cowplot::get_legend()cowplot::plot_grid(),示例如下:

ggplot2绘制双y轴

https://www.zhihu.com/tardis/zm/art/451580927

使用scale_y_continuous(sec.axis = sec_axis(~./N, name=XXX, breaks=XXX))即可。其中N为两个y轴数据的换算倍数,~./N表示次级y轴的范围是用一级y轴除以N

注意,次级y轴对应数据在绘制时需要乘以N

若仅希望重复一遍y轴(即左右均有相同的y轴),则使用sec.axis = dup_axis(name=XXX, breaks=XXX ).

ggplot2设置坐标轴次级刻度(minor breaks)

https://www.jianshu.com/p/80835c4cc37f

scale_(x|y)_continuous里设置minor_breaks:

  • minor_breaks=NULL:删除次要刻度标签

  • minor_breaks=默认:两个主要刻度之间有一个次要刻度

  • minor_breaks=手动设置的向量

  • minor_breaks=函数:例如:scales::minor_breaks_n(n)注意:此处n应该设置为所需次级刻度数目+2,因此n包含了其两端的两个主要刻度

Last updated