R绘图添加公式

普通散点图

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)) # 将标题水平居中对齐)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值