ggplot中公式的系数如何保持小数点位数一致?

问题描述 投票:0回答:1

我尝试在 ggplot 绘制的图形上标记两个公式。但是,一个公式中的小数位数与另一公式中的小数位数不匹配。

原始数据如下:

df<-structure(list(Treatment = c("Irrigated", "Irrigated", "Irrigated", 
"Irrigated", "Irrigated", "Irrigated", "Irrigated", "Irrigated", 
"Irrigated", "Irrigated", "Irrigated", "Irrigated"), Year = c(2017, 
2017, 2017, 2017, 2017, 2017, 2021, 2021, 2021, 2021, 2021, 2021
), Variety = c("Sultana - MG 000", "ES Pallador - MG I", "Isidor - MG I", 
"Santana - MG I/II", "Blancas - MG II", "Ecudor - MG II", "Sultana - MG 000", 
"ES Pallador - MG I", "Isidor - MG I", "Santana - MG I/II", "Blancas - MG II", 
"Ecudor - MG II"), FTSWt = c(0.91, 0.79, 0.92, 0.48, 0.51, 0.46, 
0.93, 0.59, 0.58, 0.44, 0.48, 0.52), SLA = c(85.38, 111.94, 108.56, 
120.54, 130.14, 123.25, 109.05, 149.97, 168.64, 162.96, 140.18, 
175.1)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", 
"data.frame"))

这是我使用的代码:

library(ggplot2)
library(readxl)
library(stats)
library(ggpmisc)
ggplot(df, aes(x = FTSWt, y = SLA, group = Year)) +
  geom_point(aes(color = as.factor(Year), shape = as.factor(Year)), size =3) +
  geom_smooth(
    method = "lm",
    formula = y ~ x,
    se = FALSE,
    aes(color = as.factor(Year))
  ) +
  stat_poly_eq(
    aes(label = paste(
      gsub('\\.', "*paste('.')*",
           after_stat(eq.label)),
      gsub('\\.', ".", after_stat(rr.label)),
      sep = "*plain(\";\")~~"
    )),
    coef.digits = 4,
    label.x.npc = 0.85,
    label.y.npc = c(0.9, 0.85),
    formula = y ~ x,
    parse = TRUE,
    size = 4.5,
    color = c("black", "red")
  ) +
  geom_text_repel(aes(label = Variety, color = as.factor(Year)), size = 4.5) +
  scale_color_manual(values = c("black", "red", "black", "red")) +
  labs(y = expression(paste('SLA (cm' ^ 2, '·', 'g' ^ -1, ')')),
       x = "FTSWt") +
  theme_bw()

这是我得到的图

enter image description here

如何在不更改其他值的情况下将蓝色圆圈中的数字 59.23 更改为小数点后一位 59.2?

r ggplot2 label decimal
1个回答
0
投票

我们可以像任何操作一样操作公式标签 其他字符串。在下面的示例中,我使用

stringr::str_replace_all()
查找所有 2 位小数并将其替换为第一位数字。我 删除了对论坛标签不重要的部分情节。

library(ggplot2)
library(ggpmisc)
library(ggrepel)
library(stringr)

ggplot(df, aes(x = FTSWt, y = SLA, group = Year)) +
  stat_poly_eq(
    aes(label = paste(
      gsub('\\.', "*paste('.')*",
           after_stat(eq.label) |> str_replace_all("\\.([0-9])[0-9]", "\\.\\1")),
      gsub('\\.', ".", after_stat(rr.label)),
      sep = "*plain(\";\")~~"
    )),
    coef.digits = 4,
    coef.keep.zeros = FALSE,
    label.x.npc = 0.85,
    label.y.npc = c(0.9, 0.85),
    formula = y ~ x,
    parse = TRUE,
    size = 4.5,
    color = c("black", "red")
  ) +
  geom_text_repel(aes(label = "", color = as.factor(Year)), size = 4.5)

© www.soinside.com 2019 - 2024. All rights reserved.