尝试将 pvalue 手动添加到 ggplot R 中的箱线图后出现错误

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

我正在尝试将在其他地方计算的 p 值添加到我的箱线图中。在尝试使用 stat_pvalue_manual 函数添加 pvalue 之前,箱线图工作得很好。我的代码如下:

df <- data.frame(
  method = c(rep('JXD', 100), rep('ILL', 100),rep('NP', 100) ),
  value = c((runif(100, min=400, max=800)), runif(100, min=500, max=850), runif(100, min=900, max=1500))
)

ggplot(df, aes(method, value, fill = method)) +  # This is the plot function
    geom_violin() +
    geom_boxplot(width=0.2, fill="white", alpha = 0.1) +
    labs(x = "Method", fill="Method")

在此之后,我尝试添加来自其他程序的 p 值:

stat.test <- tibble::tribble(
    ~group1, ~group2,   ~p.adj, ~p.signif,
    "ILL",     "JXD", 6.466374e-01, 'n.s',
    "ILL",     "NP", 5.301167e-50, '****'
 )

ggplot(df, aes(method, value, fill = method)) +  # This is the plot function
  geom_violin() +
  geom_boxplot(width=0.2, fill="white", alpha = 0.1) +
  labs(x = "Method", fill="Method") +
  stat_pvalue_manual(
    stat.test,
    y.position = 900, step.increase = 1,
    label = "p.adj"
  )

但出现以下错误:

Error in FUN(X[[i]], ...) : object 'method' not found

我尝试使用函数 ggboxplot 代替,并且通过在引号“method”之间放置它可以正常工作,该函数不适用于函数 ggplot。然而使用前者我无法得到我想要的数字。

g <- ggboxplot(df, x = "method", y = "value", width = 0.8)
g+ stat_pvalue_manual(
 stat.test, 
 y.position = 900, step.increase = 0.7,
 label = "p.signif"
 

我不明白出了什么问题。

非常感谢!

r ggplot2 p-value
2个回答
3
投票

问题是您将

fill=method
指定为全球审美。因此,在
stat_pvalue_manual
中也在数据框中寻找列名称
method
stat.test

为了解决这个问题,让

fill=method
成为
geom_violin
的当地审美:

library(ggplot2)
library(ggpubr)

df <- data.frame(
  method = c(rep("JXD", 100), rep("ILL", 100)),
  value = c((runif(100, min = 400, max = 800)), runif(100, min = 500, max = 850))
)

stat.test <- tibble::tribble(
  ~group1, ~group2, ~p.adj, ~p.signif,
  "ILL", "JXD", 6.466374e-01, "n.s",
  "ILL", "NP", 5.301167e-50, "****"
)

ggplot(df, aes(method, value)) + # This is the plot function
  geom_violin(aes(fill = method)) +
  geom_boxplot(width = 0.2, fill = "white", alpha = 0.1) +
  labs(x = "Method", fill = "Method") +
  stat_pvalue_manual(
    stat.test,
    y.position = 900, step.increase = 1,
    label = "p.adj"
  )


0
投票

就像Stefan提到的,这是因为全球审美。您还可以通过以下方式禁用它:

  stat_pvalue_manual(
  stat.test,
  y.position = 900, step.increase = 1,
  label = "p.adj",
  inherit.aes = F

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