library (showtext)
showtext_auto()
# 查看字体
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
# 添加标题
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
# 下面示例添加上标 ^,如果想添加下标使用 []
labs(x = expression('Leaf_area_obs'~(cm^2)), y = expression('Leaf_area_pred'~(cm^2))) +
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() # 每个标注文本带文本框
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)
一些暂未解决的问题
使用atop应该可以换行公式
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
#加载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")+
# 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_continuous(limits = c(-5,15), # 设置最大和最小值
breaks = seq(0, 50, 1)) # 0-50每个1设置一个刻度
xlim(0,6000) # 直接使用xlim也可
画横线: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
数值型
类别型
其中,colour表示轮廓色度量,fill表示填充色度量
调色板介绍
参考链接:https://blog.csdn.net/weshengxin/article/details/126006349
3 类调色板各有特色:
# 显示所有面板
display.brewer.all(n=NULL, type="all", select=NULL, exact.n=TRUE, colorblindFriendly=FALSE)
变量的类型
参考链接:https://blog.csdn.net/Allenmumu/article/details/119532449
(1)调整单一颜色
(2)分类变量颜色调整
(3)数值变量颜色调整
定量变量表示可测量的数量,因此是数字变量。定量数据可以进一步分类为连续(可能是浮点数)或离散(仅限整数)。
函数 scale_color_gradient() 是一个顺序梯度,
而 cale_color_gradient2() 是发散的。
连续变量默认配色方案,单色渐变,
scale_color_continuous()
手动设置顺序配色方案,
scale_color_gradient(low = “white”, high = “black”)
发散的配色方案,
scale_color_gradient2(low = “red”, mid = “white”, high = “blue”)
使用R预设调色板,
scale_color_gradientn(colours =rainbow(10))
将ColorBrewer的颜色应用到连续变量上。
scale_color_distiller(palette = “Spectral”)
ggplot2中的 Viridis 调色板(好看,比较实用)
scale_color_viridis_c()
scale_color_viridis_c(option = “inferno”)
scale_color_viridis_c(option = “plasma”)
scale_color_viridis_c(option = “cividis”)
使用扩展包中的调色板
racrtocolors包
scale_color_carto_c(palette = “BurgYl”)
scale_color_carto_c(palette = “Earth”)
path_s = "D:/Figure/"
ggsave(paste0(path_s, 'box', '.tiff'), Figure, width = 10, height = 7, units = c("cm"), dpi = 600)
参考博文:
# 使用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()。
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")
df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
ggplot(df, aes(trt, outcome)) +
geom_col()
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)
参考博文:
- 构建了新函数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
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)
# 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)
参考链接:
参考链接:
R语言绘制相关性热图(相关性图)多种方法盘点,包你一学就会!( https://zhuanlan.zhihu.com/p/458889477 )
library(ggcorrplot)
library(ggplot2)
# 使用默认的方案绘图
ggcorrplot(cormtcars)
# 使用自定义方案绘图
cor <- round(cor(mtcars), 2) # R自带的cor()函数计算相关性矩阵,round()保留两位小数
pmtcars <- 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)
还可以使用以下包: