Rachael
Rachael

Reputation: 315

got an error after trying to add pvalues manually to a boxplot in ggplot R

I am trying to add pvalues, calculated somewhere else, to my boxplots. The boxplot work just fine before trying to add the pvalues with the function: stat_pvalue_manual. My code is as follows:

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")

After this I am trying to add p values from other program:

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"
  )

But got the following error:

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

I tried using the function ggboxplot instead, and it worked fine by putting between quotation marks 'method', which does not work with the function ggplot. However using the former I cannot get the figure that I want.

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"
 

I do not understand what is wrong.

Thanks a lot!

Upvotes: 1

Views: 4666

Answers (2)

stefan
stefan

Reputation: 124103

The issue is that you specified fill=method as a global aesthetic. Hence, stat_pvalue_manual is looking for a column named method in your dataframe stat.test too.

To solve this issue make fill=method a local aesthetic of 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"
  )

Upvotes: 4

Avish
Avish

Reputation: 66

Like Stefan mentioned, it's because global aesthetic. You can also disable it with:

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

Upvotes: 1

Related Questions