R语言使用ggplot2包绘图

设置

绘图显示中文 showtext_auto()

library (showtext)
showtext_auto()

查看并设置字体 windowsFonts()

# 查看字体
windowsFonts()

# 定义字体名称
windowsFonts(myFont = windowsFont("微软雅黑"))

# 使用字体
#修改坐标轴和legend、标题的字体
theme(text=element_text(family="Arial"))
#或者
theme_bw(base_family="Arial")
#修改geom_text的字体
geom_text(family="Arial")

参考链接:
R语言学习 - 图形设置中英字体
https://zhuanlan.zhihu.com/p/442648746
R语言中作图字体的设置
https://blog.csdn.net/qq_18055167/article/details/123646961


设置标题 ggtitle()

# 添加标题
labs(x = 'x轴标题', y = 'y轴标题' ,title = '标题' )
xlab('x轴标题')
ylab('y轴标题')
ggtitle("主标题", subtitle = "副标题")

# 调整标题的位置
theme(plot.title = element_text(color = 'red', size = 20, hjust = 0.5))                       # 标题居中
theme(plot.title = element_text(color = 'red', size = 20, hjust=0.5, vjust = -15))      # 通过vjust参数将标题调整到图形内部。
参考链接:
# Tidyverse自学笔记-ggplot2之图形标题
https://zhuanlan.zhihu.com/p/545306833
# 玩转数据可视化之R语言ggplot2:(七)对图形添加注释和标签(包含标题、坐标轴、参考线和高亮等注释方法)
https://blog.csdn.net/weixin_45052363/article/details/124153241
# R语言ggplot如何添加图例?(讲的很多,  绘图的很多基础设置都讲了)
https://www.zhihu.com/question/267400251/answer/2454390967

添加公式 expression()

# 下面示例添加上标 ^,如果想添加下标使用 []
labs(x = expression('Leaf_area_obs'~(cm^2)), y =  expression('Leaf_area_pred'~(cm^2))) +  

绘图添加文本 geom_text(); annotate()

  • 添加多个标注 geom_text(), 可以通过数据框的变量传递位置
p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars))) + geom_point() 
p + geom_text(
check_overlap = TRUE, 
aes(colour = factor(cyl)),
size = 3, 
family = "serif",
hjust = 'left', vjust = 'top',
nudge_x = 0.5, nudge_y = 0
)       
# 为散点图每个点都添加文本标注
# check_overlap 设置是否重叠
# size 设置文本尺寸
# hjust和vjust 设置水平对齐(0:右/上,1:左/下), 或者使用字符("left", "middle", "right", "bottom", "center", "top"). 或者"inward"和"outward"
# nudge_x 和 nudge_x 设置沿着水平和垂直调整以微调标签。用于从点偏移文本。
# family 设置字体
# parse = TRUE 设置是否显示表达式

p + geom_label()      # 每个标注文本带文本框
  • 为指定的位置添加一个文本标注 annotate(), xy位置直接通过数值指定(坐标轴的绝对位置)
    annotate() 功能比较多,还能使用线条和阴影标注
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()

# 指定位置添加文本标注    # 可以使用-Inf或Inf设置xy位置的边缘
p + annotate("text", x = 4, y = 25, label = "Some text")   

# 指定位置标注多行文本, 使用 \n 换行
p + annotate("text", x = 4, y = 25, label = "text1\ntext2")   

# 还能使用geom_text()的一些参数设置标注的颜色, 字体, 大小, 对齐
p + annotate("text", x = 4, y = 25,  
	label = paste0("text1=", "123" ,"\n", "text2=", "45" ) ,
	size = 5,
	colour = "red", 
	family = "serif", 
	hjust = 'left', 
	vjust = 'top')

# 指定位置标注公式, 使用参数 parse = TRUE
p + annotate("text", x = 4, y = 25, label = "italic(R) ^ 2 == 0.75",  parse = TRUE)
  • 使用ggpp包的annotate可以添加根据相对位置添加文本标注
    参考链接:
    https://zhuanlan.zhihu.com/p/392704106
install.packages('ggpp')
library(ggpp)
p + annotate("text_npc", npcx = 0.5, npcy = 0.25, label = "R语言")  # 添加文本标注
p + annotate("table_npc", npcx = 0.5, npcy = 0.3, 
label = data.frame(name =c("R语言","学生"), score =c(100,100)),size=5)   # 添加表格标注
p + annotate("plot_npc", npcx = 0.288, npcy =0.1, label = q)       # 添加图形标注
  • 此外还能使用grid.text() 在面板上标注文本,使用相对位置[0,1]
    library(grid), grid.text()

一些暂未解决的问题

  • 不会使用换行符标注两行公式,
    公式只能标注一行(可能是我不会设置)

使用atop应该可以换行公式

  • 2行公式换行用atop还好, 超过2行就开始出现各种问题, >2行公式换行不建议使用,还是老老实实的一行行的添加吧
plot(c(1,2,3,4,5))
# 使用substitute()函数替换变量, 写公式的atop()函数给公式换行(只能两行).  atop()只能传递两个参数,分别表示一行,没有换行符
exp1 <- substitute(
  atop(italic(y) == a + b %*% italic(x), italic(R) ^ 2 == r2),
  list(a = 1, b = 2, r2 = 0.9) )
text(1, 3, label = exp1, adj = 0, col = "red")

# 标注三行公式只能嵌套使用atop了,  atop(atop(a1, a2),a3)形式的第三行字体大小不一致. 所以使用atop(atop(a1, a2),atop(a3))形式
exp2 <- substitute(
  atop(atop(italic(y) == a + b %*% italic(x), italic(R) ^ 2 == r2), atop(italic(P) == p, phantom(0) ) ),
  list(a = 1, b = 2, r2 = 0.9, p = 0.01) )
text(2, 3, label = exp2, adj = 0, col = "red")

# 此外, 会发现三行公式是居中显示的, 如果想左对齐,只能用phantom(0)占位补成相同长度.
exp3 <- substitute(
  atop(atop(italic(y) == a + b %*% italic(x), italic(R)^2 == r2 ~ phantom(10)), atop(italic(P) == p ~ phantom(10), phantom(0))),
  list(a = 1, b = 2, r2 = 0.9, p = 0.01)
)
text(3, 3, label = exp3, adj = 0, col = "red")


参考链接:
R语言ggplot2添加单个文本或多个文本(包括公式)
https://blog.csdn.net/cfc424/article/details/126759163
R作图之 annotation详解!
https://blog.csdn.net/g_r_c/article/details/19673625
R语言基础绘图——注解
https://shengxin.ren/article/129
R语言绘图中的公式怎么换行?
https://www.zhihu.com/question/469560125


绘图添加回归方程, R2, 显著性P值

  • 可以自行计算按照上面添加标注(公式)的方法添加
  • 还可以使用一些包
  1. R语言笔记——ggplot2画回归曲线,添加方程或P值 (使用ggpmisc包的stat_poly_eq)
    https://wap.sciencenet.cn/home.php?mod=space&do=blog&id=1212579
#加载ggpmisc包
library(ggpmisc) 

# 添加回归曲线,se取消置信空间,linetype设置线型
geom_smooth(method = "lm",linetype=3, se=FALSE, colour="black", span=0.8) + 
#添加回归方程和R2
stat_poly_eq(aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~~')), 
formula = y ~ x, 
parse = T, family = "SH") + 

# 仅添加R2和P值,label.x和label.y设置文字位置
stat_fit_glance(method = 'lm',
method.args = list(formula = y ~ x),
mapping = aes(label = sprintf('R^2~"="~%.3f~~italic(P)~"="~%.2g', stat(r.squared), stat(p.value))),
parse = TRUE, label.x = 0.95, label.y = 0.95, family = "SH")+
  1. 使用的ggpubr包的stat_cor()
# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)

# Scatter plot with correlation coefficient
#:::::::::::::::::::::::::::::::::::::::::::::::::
sp <- ggscatter(df, x = "wt", y = "mpg",
   add = "reg.line",  # Add regressin line
   add.params = list(color = "blue", fill = "lightgray"), # Customize reg. line
   conf.int = TRUE # Add confidence interval
   )
# Add correlation coefficient
sp + stat_cor(method = "pearson", label.x = 3, label.y = 30)

# Specify the number of decimal places of precision for p and r
# Using 3 decimal places for the p-value and
# 2 decimal places for the correlation coefficient (r)
sp + stat_cor(p.accuracy = 0.001, r.accuracy = 0.01)

# Show only the r.label but not the p.label
sp + stat_cor(aes(label = ..r.label..), label.x = 3)

# Use R2 instead of R
ggscatter(df, x = "wt", y = "mpg", add = "reg.line") +
 stat_cor(
   aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")),
  label.x = 3
)


修改横坐标轴刻度 scale_x_continuou()

scale_x_continuous(limits = c(-5,15)# 设置最大和最小值
                   breaks = seq(0, 50, 1))  # 0-50每个1设置一个刻度

xlim(0,6000)   # 直接使用xlim也可

添加竖线、横线、对角线geom_hline(), geom_vline(), geom_abline()

画横线:geom_hline(yintercept = 5 )
画竖线:geom_vline(xintercept = 20)
画斜线:geom_abline(intercept = 0, slope = 1, linetype =“longdash”, size=0.5) # 画对角线


调整图例的颜色

ggplot2包中对配色系统主要通过以下几个函数实现:
参考链接:https://blog.csdn.net/qq_18055167/article/details/123512967

数值型

  • scale_colour/fill_coninuous()
  • scale_fill_distiller()
  • scale_colour/fill_gradient()
  • scale_colour/fill_gradient2()
  • scale_colour/fill_gradientn()

类别型

  • scale_colour/fill_discrete()
  • scale_colour/fill_brewer()
  • scale_colour/fill_manual()

其中,colour表示轮廓色度量,fill表示填充色度量


调色板介绍
参考链接:https://blog.csdn.net/weshengxin/article/details/126006349
3 类调色板各有特色:

  • 连续型(sequential):单渐变色,一种颜色由浅到深。
  • 离散型(divergent):双渐变色,一种颜色到另外一种颜色的渐变。
  • 定性型(qualitative):区分色,几种区分度很高的颜色组合。
# 显示所有面板
display.brewer.all(n=NULL, type="all", select=NULL, exact.n=TRUE, colorblindFriendly=FALSE)

变量的类型
参考链接:https://blog.csdn.net/Allenmumu/article/details/119532449

  1. 分类(分组)变量。变量可以进一步指定为名义、有序和二元(二分)。分类变量使用定性调色板。
  2. 连续变量。连续变量使用连续或发散调色板。

(1)调整单一颜色

  1. 可以指定为单色也可以赋值给变量。通常使用在geom_*(color = “blue”)。注意只有变量才会在aes()中使用。
  2. color(轮廓颜色),fill(填充颜色)。

(2)分类变量颜色调整

  1. 手动选择颜色使用函数
    scale_color_manual()
  2. 使用内置的定性调色板,使用函数
    scale_color_brewer()
  3. 使用扩展包中的调色板,例如:
    library(ggsci)
    scale_color_aaas()
    scale_color_npg()

(3)数值变量颜色调整
定量变量表示可测量的数量,因此是数字变量。定量数据可以进一步分类为连续(可能是浮点数)或离散(仅限整数)。
函数 scale_color_gradient() 是一个顺序梯度,
而 cale_color_gradient2() 是发散的。

  1. 连续变量默认配色方案,单色渐变,
    scale_color_continuous()

  2. 手动设置顺序配色方案,
    scale_color_gradient(low = “white”, high = “black”)
    发散的配色方案,
    scale_color_gradient2(low = “red”, mid = “white”, high = “blue”)
    使用R预设调色板,
    scale_color_gradientn(colours =rainbow(10))

  3. 将ColorBrewer的颜色应用到连续变量上。
    scale_color_distiller(palette = “Spectral”)

  4. ggplot2中的 Viridis 调色板(好看,比较实用)
    scale_color_viridis_c()
    scale_color_viridis_c(option = “inferno”)
    scale_color_viridis_c(option = “plasma”)
    scale_color_viridis_c(option = “cividis”)

  5. 使用扩展包中的调色板
    racrtocolors包
    scale_color_carto_c(palette = “BurgYl”)
    scale_color_carto_c(palette = “Earth”)


设置主题 theme()

输出图片ggsave()

path_s = "D:/Figure/" 
ggsave(paste0(path_s, 'box', '.tiff'), Figure, width = 10, height = 7, units = c("cm"), dpi = 600)

画图

画直方图 geom_histogram()

参考博文:

  • 语言ggplot2统计图形:常见的4种直方图
    (https://zhuanlan.zhihu.com/p/484533343)
# 使用geom_histogram自定义
P <- ggplot(data, aes(var)) 
P + geom_histogram(fill = "darkgrey",
                   color="white") +
    scale_x_continuous(breaks = seq(0, 50, 1)) 
                   
# 让每个bin的两侧都显示标注
P + geom_bar() + scale_x_binned() 

绘制条形(柱状)图 geom_bar(),geom_col()

有两种类型的柱状图:geom_bar()和geom_col()。

  1. geom_bar()
    使柱状图的高度与每组的个数成正比(如果提供了权重美学,则为权重之和)。geom_bar()默认使用stat_count():它计算每个x位置的个数。
  2. geom_col()
    如果你想让条形图的高度代表数据中的数值,请使用geom_col()。geom_col()使用stat_identity():它让数据保持原样。
  • geom_bar() 柱子表示分类的个数
g <- ggplot(mpg, aes(class))

# 绘制柱状图
g + geom_bar()

# 横向绘图 geom_bar(aes(y = class))
ggplot(mpg) + geom_bar(aes(y = class))
# 或者翻转坐标轴 coord_flip() 
g + geom_bar() + coord_flip() 

# 堆叠
g + geom_bar(aes(fill = drv))
# 堆叠后横向
ggplot(mpg, aes(y = class)) +
  geom_bar(aes(fill = drv), position = position_stack(reverse = TRUE)) +
  theme(legend.position = "top")
  • geom_col() 柱子表示数值
df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
ggplot(df, aes(trt, outcome)) +
  geom_col()
  • 柱状图添加误差棒 geom_errorbar()
D.se <- summarySE(D, measurevar = 'seed_setting_rate', groupvars=c('genotype', 'treatment'), na.rm = TRUE) 

P <- ggplot(D.se , aes(x = genotype, y = seed_setting_rate, fill = treatment)) +
  geom_errorbar(aes(ymax = seed_setting_rate + se, ymin = seed_setting_rate - se),
                position = position_dodge(0.9), width = .8, size = .2) +
  geom_bar(stat="identity", position="dodge") +
  mytheme  
P
path = "G:/F/work_RuGao_WYL_2022/Phenotype/Figure/maturity/"
ggsave(paste0(path,'bar_','seed_setting_rate','.tiff'), P, width = 20, height = 10,units = c("cm"), dpi = 600)
  • 对柱子排序,根基y数值大小对x排序 reorder()
    ggplot( mapping = aes(x = reorder(gene, coef), y = coef) )
参考博文:
 - 构建了新函数summarySE,计算平均值和标准差,添加了误差棒
 https://www.zhangshengrong.com/p/ArXGbnrENj/
 
- 添加了文本标注
https://zhuanlan.zhihu.com/p/38412409

- 每天一个R函数之reorder (柱状图的柱子进行排序)
https://zhuanlan.zhihu.com/p/511112576

 - R语言绘制带误差线的条形图
https://www.zhangshengrong.com/p/ArXGbnrENj/

- 语言柱形图(ggplot2)基本操作常用记录(横向排列)
https://blog.csdn.net/weixin_42574470/article/details/125781458


画散点图 geom_point()

library(ggplot2)

P <- ggplot(df_merge,aes(lA_3D_cm, Leaf_area_sum)) + 
  geom_point() +  
  geom_smooth(se = T, method = 'lm', size = 0.5, colour = 'black',fill = 'gray') + # 绘制拟合曲线和阴影
  stat_cor(method = "pearson",label.x.npc = 0, label.y.npc = 1, color='red', r.accuracy=0.01, p.accuracy=0.01) +
  scale_x_continuous( limits = c(0, 550), breaks = seq(0, 550, 100)) + 
  labs(x = expression('Leaf_area_radar'~(cm^2)), y =  expression('Leaf_area_Li3000'~(cm^2))) +  
  theme_bw()
P
path = "D:/"
ggsave(paste0(path,'scat_Leaf_area','.tiff'), P, width = 10, height = 9, units = c("cm"), dpi = 600)

画箱线图以及多重箱线图 geom_boxplot()

  • 参考链接:R语言ggplot2绘制箱线图(Box plot)
  • https://zhuanlan.zhihu.com/p/397799549
# 将dose变量转变为因子变量
ToothGrowth$dose = as.factor(ToothGrowth$dose)
head(ToothGrowth)
library(ggplot2)

# 基本箱线图
p = ggplot(ToothGrowth, aes(x=dose, y=len)) + 
  geom_boxplot()
p

# 自动添加颜色
p = ggplot(ToothGrowth, aes(x=dose, y=len, color = dose)) +
  geom_boxplot()
p

# 根据分组填充不同的颜色
p5 = ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) +
  geom_boxplot()

# Change box plot colors by groups 多重箱线图
ggplot(ToothGrowth, aes(x=dose, y=len, fill=supp)) +
  geom_boxplot()
  
# 手动自动添加颜色
p1 = p + scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9"))
p2 = p + scale_color_brewer(palette = "Dark2")
p3 = p + scale_color_grey() + theme_classic()
library(patchwork)
p1|p2|p3

# 使用单一颜色
p4 = ggplot(ToothGrowth, aes(x = dose, y =len)) + 
  geom_boxplot(fill = '#A4A4A4', color = "black") + 
  theme_classic()
  

  # 修改图例位置("top/bottom/none")
  p + theme(legend.position = "top") 
  # 修改图例顺序
 p + scale_x_discrete(limits = c("2", "0.5", "1"))

# 旋转坐标轴
p + coord_flip()

# 绘制有缺口的箱线图
ggplot(ToothGrowth, aes(x = dose, y=len)) + 
  geom_boxplot(notch=TRUE)
  
# 修改离群值的颜色形状和大小
ggplot(ToothGrowth, aes(x = dose, y=len)) + 
  geom_boxplot(notch=TRUE,
               outlier.colour = "blue", outlier.shape = 6,
               outlier.size = 5)

# 显示均值点
p + stat_summary(fun.y = mean, geom = "point", shape = 23, size=4)
p + scale_x_discrete(limits=c("0.5", "2"))

# Box plot with dot plot 描点
p + geom_dotplot(binaxis = 'y', stackdir = 'center', dotsize = 0.5)
# Box plot with jittered points
# 0.2 : x 方向的抖动程度
p + geom_jitter(shape=16, position = position_jitter(0.2))

为箱型图或者柱状图添加显著性标注 geom_signif() 或者stat_compare_means()

  • 参考链接:
  • 数据可视化——R语言为ggplot图形添加P值和显著性水平
    https://blog.csdn.net/zhouhucheng00/article/details/106391872
  • R可视化——箱线图绘制及显著性标记
    https://zhuanlan.zhihu.com/p/536728011

画散点图并添加相关性标注 ggscatter()

  • 参考链接:
    R语言绘图小技巧篇-添加相关系数
    https://www.jianshu.com/p/baf4ed9563b3
# ggplot2中的绘图设置函数都能配合使用,比如labs(), theme()等
library(ggcorrplot) 
library(ggplot2)
data(mtcars)
df <- mtcars
df$cyl <- as.factor(df$cyl)

F <- ggscatter(df, x = "wt", y = "mpg", add = "reg.line", conf.int = TRUE,  size=1.5,
              add.params = list(fill = "gray"), ggtheme = theme_bw()) + 
     stat_cor(method = "pearson", label.x.npc = 0, label.y.npc = 1,color='red',
              r.accuracy=0.01, p.accuracy=0.01)
F 
path = "D:/"
ggsave(paste0(path,'ggscatter','.tiff'), F, width = 10, height = 9, units = c("cm"), dpi = 600)

画带带误差阴影的折线图geom_line()

参考链接:

  • 【R语言系列02】PLOT GGPLOT作图,标注虚线,标注文本,添加阴影误差带
    (https://www.freesion.com/article/98321370899/)

添加拟合曲线 geom_smooth()

参考链接

  • R语言绘图基础篇-添加拟合曲线(geom_smooth)
    https://zhuanlan.zhihu.com/p/422129556
    -如何在R中使用geom_smooth?(参数介绍的比较详细)
    https://juejin.cn/post/7128265519047639077
  • ggplot2–geom_smooth和曲线拟合画图(有自定义函数)
    https://blog.csdn.net/flyfox73/article/details/116353201

画相关性矩阵 ggcorrplot()

参考链接:
R语言绘制相关性热图(相关性图)多种方法盘点,包你一学就会!( https://zhuanlan.zhihu.com/p/458889477 )

  • 使用ggcorrplot包
library(ggcorrplot)
library(ggplot2)
# 使用默认的方案绘图
ggcorrplot(cormtcars)  

# 使用自定义方案绘图
cor <- round(cor(mtcars), 2)  # R自带的cor()函数计算相关性矩阵,round()保留两位小数
pmat <- cor_pmat(mtcars)   # 使用ggcorrplot包的cor_pmat()函数计算p值
P <- ggcorrplot(cor, 
     method = "circle",   # 使用圆形表示每个相关性,默认是方形
     type = "upper",               # 只显示上三角
     lab = T, lab_size = 3,        # 显示相关性标注,调整字体大小
     p.mat = pmat, insig = "blank",  # pmat表示前面计算的显著性P的矩阵, "blank"表示显著性小于0.05的相关性不显示,默认是打叉号                    
     # hc.order = TRUE    # 分等级聚类重排矩阵,通俗讲就是把相关性按照高低或者正负堆在一块
     ) 
P  
# 保存图片
path_s = "D:/" 
ggsave(paste0(path_s,'cor', '.tiff'), P, width = 20, height = 20, units = c("cm"), dpi = 600)

还可以使用以下包:

  • corrplot包,
  • corrgram包,
  • PerformanceAnalytics包,
    (https://blog.csdn.net/S_S0318/article/details/115959945)
  • ggplot2包以及pheatmap包绘制热力图 (https://blog.csdn.net/weixin_39646107/article/details/111298026)

拼图

  • 【R分享|实战】地表最全R拼图教程,告别AI和PS
    https://mp.weixin.qq.com/s/jbBpaycdGcEoqKNXHhzd2A
  • 大佬新包patchwork:可能是迄今为止最优秀的拼图包
    https://mp.weixin.qq.com/s/p7LLLvzR5LPgHhuRGhYQBQ
  • 7
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值