Home > Software engineering >  How to resolve problem with ggplot and ggsignif
How to resolve problem with ggplot and ggsignif

Time:11-21

I am trying to plot the differences in pairs. I found an example on this forum, but to this graph I would like to add the significance level information using the geom_signif function. Unfortunately, I get the message back: "Error in f (...): Can only handle data with groups that are plotted on the x-axis " Can someone help me fix this problem?

d <- data.frame(y = rnorm(20, 9, 2),
                group = as.factor(rep(c('Post-FAP', 'Post-DEP'), each = 10)),
                id = rep(1:10, 2))

ggplot(d, aes(y = y))  
  geom_boxplot(aes(x = rep(c(-2.5, 2.5), each = 10), group = group), fill = '#47E3FF')  
  geom_point(aes(x = rep(c(-1, 1), each = 10)), shape = 21, size = 1.5, col = "black", fill = "grey")  
  geom_line(aes(x = rep(c(-1, 1), each = 10), group = id))  
  #geom_signif(annotation = "p=0.05", y_position = 13, xmin = -2.5, xmax = 2.5, tip_length = .02)  
  scale_x_continuous(breaks = c(-2.5, 2.5), labels = c("Post-FAP", "Post-DEP"))  
  scale_y_continuous(minor_breaks = seq(5, 14, by =1),
                     breaks = seq(6, 14, by = 2), limits = c(5, 14),
                     guide = "axis_minor")   
  theme_bw()  
  theme(legend.position = "none", panel.grid = element_blank())

CodePudding user response:

I think what you need to do is install ggh4x. It is an addon to ggplot2 that has some helpful tools, like properly adding ticks and minor ticks in your case. Once you load the R package then you should be good to go.

library(ggh4x)
library(ggplot2)

ggplot(d, aes(y = y))  
  geom_boxplot(aes(x = rep(c(-2.5, 2.5), each = 10), group = group), fill = '#47E3FF')  
  geom_point(aes(x = rep(c(-1, 1), each = 10)), shape = 21, size = 1.5, col = "black", fill = "grey")  
  geom_line(aes(x = rep(c(-1, 1), each = 10), group = id))  
  #geom_signif(annotation = "p=0.05", y_position = 13, xmin = -2.5, xmax = 2.5, tip_length = .02)  
  scale_x_continuous(breaks = c(-2.5, 2.5), labels = c("Post-FAP", "Post-DEP"))  
  scale_y_continuous(minor_breaks = seq(5, 14, by =1),
                     breaks = seq(5, 14, by = 2), limits = c(5, 14),
                     guide = "axis_minor")   
  theme_bw()  
  theme(legend.position = "none", panel.grid = element_blank())

example data

CodePudding user response:

There is a thread here on the error message you posted, saying that all the information on aes (x and y) need to be accessible by the subfunction, i.e. geom_signif.

Using ggplot(d, x=aes(as.numeric(group), y=y, group = group)) worked for me.

Interestingly, ggplot(d, x=aes(rep(c(-2.5, 2.5), each = 10), y=y, group = group)) , did not return an error, but also did not show the geom_signif annotation.

  •  Tags:  
  • r
  • Related