普通散点图
library(ggplot2)
data <- data.frame(x = seq(1,20), y = rnorm(20),
group = as.factor(rep(c(0,1), times = 10)))
ggplot(data, aes(x, y, color = group))+
geom_point()+
theme_classic()+
labs(title = "Normal title")
标题里有上下标
expression() 函数:
通常用于创建包含数学表达式或符号的标题、标签等静态文本,不支持使用变量。
ggplot(data, aes(x, y, color = group))+
geom_point()+
theme_classic()+
labs(title = expression("Title with subscript: CO"[2]))
ggplot(data, aes(x, y, color = group))+
geom_point()+
theme_classic()+
labs(title = expression("Title with superscript: y = ax"^'2'))
将换行和上下标直接用\n连接可能会出错,解决方法①使用subtitle,②使用atop(),atop()将两个表达式写成分式的形式但不画分式的线
# subtitle
ggplot(data, aes(x, y, color = group))+
geom_point()+
theme_classic()+
labs(title = "Title with linebreak", subtitle = expression("y=ax"^2))
# atop
ggplot(data, aes(x, y, color = group)) +
geom_point() +
theme_classic()+
labs(
title = expression(paste(atop("Title with linebreak:","y=ax"^2))),
)+
theme(
plot.title = element_text(hjust = 0.5) # 将标题水平居中对齐
)
在图上所有文字的地方都可以使用以上方法,不过除了标题,其他地方不能使用子标题来换行,只能用atop(),以图例标题为例:
ggplot(data, aes(x, y, color = group)) +
geom_point() +
theme_classic()+
labs(
title = expression(paste(atop("Title with linebreak:","y=ax"^2))),
color = expression(paste(atop("SO"[2], (mg/kg))))
)+
theme(
plot.title = element_text(hjust = 0.5) # 将标题水平居中对齐
)
atop()无法调节行距和上下两行的字体各自的大小,是否有更好的方法?可能还得用python。
特殊符号
ggplot(data, aes(x, y, color = group))+
geom_point()+
theme_classic()+
labs(title = expression(paste("Title with special symbols: ", alpha + beta ^ 2)))
bquote() 函数:
通常用于在图形中显示变量值或创建根据数据集属性动态变化的标签,支持使用变量,并且可以在表达式中嵌入变量的值。与expression()类似
例如对数据进行回归后将方程添加到图上:
model <- lm(y ~ x, data = data)
# 提取回归系数
intercept <- coef(model)[1]
slope <- coef(model)[2]
# 绘图
ggplot(data, aes(x, y)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, color = "red") +
labs(title =
bquote(atop("Scatter Plot with Linear Regression:",
y == .(round(intercept, 2)) * "+" * .(round(slope, 2)) * "x")),
x = "X",
y = "Y")+
theme_classic()+
theme(plot.title = element_text(hjust = 0.5)) # 将标题水平居中对齐)