在ggplot2中为数据和轴标签添加上标和减号

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

我正在尝试使用一些数据制作森林图:

dt <- data.frame(outcome = c("A", "B", "C", "D"), 
                 beta = c(-0.007, -0.008, -0.009, -0.009),
                 LCI = c(-0.005, -0.006, -0.007, -0.008), 
                 UCI = c(-0.008, -0.009, -0.01, -0.01), 
                 P = c(0.000001, 0.00002, 0.000003, 0.00004))

这个脚本:

pt <- ggplot(data = dt, aes(
  y = reorder(outcome, beta),
  x = beta,
  xmin = LCI,
  xmax = UCI
)) +
  geom_point(color = "black",
             shape = 18,
             size = 5) +
  geom_errorbarh(height = 0.1,
                 linewidth = 1,
                 color = "black") +
  geom_text(
    aes(
      label = paste0(beta, " (", LCI, ";", UCI,  "), p = ", P),
      x = beta,
      y = outcome
    ),
    size = 4,
    color = "black",
    position = position_dodge(0),
    vjust = -1.5,
    show.legend = FALSE#, check_overlap = FALSE
  ) +
  labs(title = 'My plot', x = 'Beta', y = 'Outcome') +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.05, size = 10, face = "bold")) +
  theme(
    axis.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10, face = "bold")
  ) 

但是,我需要我的 p 值采用显式符号的形式(例如 7 × 10-3),而不是 E 形式(例如 7e-3),并且使用减号而不是连字符。

我尝试用减号替换连字符:

t %>% mutate(beta = as.character(beta)) %>%
  mutate(beta = gsub(("-", "\u2013", beta)))

对于 LCI 和 UCI 来说,相应地,但这没有任何区别。

还尝试添加以下行来修复轴标签中的减号:

scale_x_continuous(breaks = seq(-0.01, -0.009, -0.008, -0.007, -0.006, -0.005), 
                   labels = \~sub("-", "\\u2212", .x)) 

但这也没有帮助。有人可以提出任何解决方案吗?

r ggplot2 geom-text plotmath
1个回答
0
投票
library(ggplot2)
library(dplyr)

dt <- data.frame(outcome = c("A", "B", "C", "D"), 
                 beta = c(-0.007, -0.008, -0.009, -0.009),
                 LCI = c(-0.005, -0.006, -0.007, -0.008), 
                 UCI = c(-0.008, -0.009, -0.01, -0.01), 
                 P = c(0.000001, 0.00002, 0.000003, 0.00004))

dt %>% 
   mutate(P_labs = paste0(beta, "~(", LCI, "*';'", UCI, ")*','~p == ", 
                          gsub("(.*)e(.*)", "\\1~'x'~10^\\2", P))) %>% 
 ggplot(data = ., aes( x = beta, y = reorder(outcome, beta),  
                       xmin = LCI, xmax = UCI )) +
  geom_point(color = "black", shape = 18, size = 5) +
  geom_errorbarh(height = 0.1, linewidth = 1, color = "black") +
  geom_text(aes(label = P_labs,
                x = beta, y = outcome),
            size = 4, color = "black",
            position = position_dodge(0), 
            vjust = -1.5, parse = TRUE, show.legend = FALSE) +
  labs(title = 'My plot', x = 'Beta', y = 'Outcome') +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.05, size = 10, face = "bold")) +
  theme(axis.text = element_text(size = 10, face = "bold"),
        axis.title = element_text(size = 10, face = "bold")) 

创建于 2024-04-12,使用 reprex v2.0.2

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