首页 > 解决方案 > 使用 ggplot stat_summary 绘制 p 值

问题描述

我想用系数和误差线绘制一个数据框(统计数据),并自动在每个点上方写入 p 值。

stats <- data.frame(Coefficient = c(-0.07,-0.04,-0.15173266),
                    p_value = c(.0765210755,0.5176050652,0.0001309025),
                    conf_low = c(-.1544418,-0.1686583,-0.2294873),
                    conf_high = c(0.007812205,0.084939487,-0.073978033),
                    Test = c("TestA","TestB","TestC"))

我正在尝试制作一个函数来绘制每个系数点上方的 p 值。(下图中的 coord_flip 也可能让我失望。

give.pval <- function(y){
  return(c(x = Coefficient, label = stats$p_value))
}

以下 ggplot 正是我需要的,除了我做错的 stat_summary 行

ggplot(stats, aes(x = Test, y = Coefficient)) +
  geom_point(aes(size = 6)) +
  geom_errorbar(aes(ymax = conf_high, ymin = conf_low)) +
  geom_hline(yintercept=0, linetype="dashed") +
  #stat_summary(fun.data = give.pval, geom = "text") + 
  theme_calc() +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        axis.text.x = element_text(size = 12, vjust = 0.5), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 12), axis.title.y = element_blank(),
        legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 24)) +
  coord_flip() + 
  ylab("Coefficient")

我希望有这个图,但在三个系数点的每一个上方都有适当的 p 值。

感谢您的任何建议。

标签: rggplot2

解决方案


这可以通过在aesgeom_text上映射的图层和一些额外的轻推来实现p_valuelabel

library(ggplot2)

stats <- data.frame(Coefficient = c(-0.07,-0.04,-0.15173266),
                    p_value = c(.0765210755,0.5176050652,0.0001309025),
                    conf_low = c(-.1544418,-0.1686583,-0.2294873),
                    conf_high = c(0.007812205,0.084939487,-0.073978033),
                    Test = c("TestA","TestB","TestC"))

ggplot(stats, aes(x = Test, y = Coefficient)) +
  geom_point(aes(size = 6)) +
  geom_errorbar(aes(ymax = conf_high, ymin = conf_low)) +
  geom_hline(yintercept=0, linetype="dashed") +
  geom_text(aes(label = p_value), nudge_x = .2) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        axis.text.x = element_text(size = 12, vjust = 0.5), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 12), axis.title.y = element_blank(),
        legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 24)) +
  coord_flip() + 
  ylab("Coefficient")


推荐阅读