const-ae / ggsignif

Easily add significance brackets to your ggplots
https://const-ae.github.io/ggsignif/
GNU General Public License v3.0
593 stars 43 forks source link

feature request - annotate with magnitude of difference in mean #32

Closed chinwobble closed 5 years ago

chinwobble commented 7 years ago

Thanks for the great ggplot2 extension.

Is it possible to easily display the magnitude of the difference between two groups?

I would like to be able to see if two groups are economically significantly different as well as statistical significant. Have an annotation more like "+1.05**".

I know this is possible by passing in a custom data frame with the new values however it requires a fair amount of code. It involves:

const-ae commented 7 years ago

Thanks, I am happy to hear that you like the package.

Right now it is not possible to display the magnitude of an effect without custom labels. And because I have never encountered any examples, where that was done, I would be wary adding it, to not overload the interface with too many options. Or is this a very common visualization in economics?

chinwobble commented 7 years ago

I wouldn't say this is a common visualisation in economics. For my specific visualisation I would like to label the magnitude difference somehow to draw specific attention a trend.

const-ae commented 7 years ago

One option is that you write your own method, which returns a string just the way you want it:

magnitude_test <- function(x,y, ...){
  change <- mean(y)/mean(x)
  p <- t.test(x,y)$p.value
  stars <- if(p < 0.001)
    "***"
  else if(p < 0.01)
    "**"
  else if(p < 0.05)
    "*"
  else
    ""
  list(p.value=paste0(signif(change, digits=2),stars))
}

ggplot(mpg, aes(x=manufacturer, y=displ)) +
  geom_boxplot()  +
  stat_signif(comparisons=list(c("audi", "ford"), c("hyundai", "nissan")),
              test=magnitude_test,
              margin_top=0.02, step_increase=0, tip_length=0.01) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  facet_wrap(~ as.factor(year), scale="free")

image

You can do whatever kind of calculations you want in the function, the only requirement is that the test returns a list with an entry called p.value.

If you want to try this yourself, you will have to install the latest version of ggsignif from github

devtools::install_github("const-ae/ggsignif")

because only that one supports test methods that return text.