2

I am trying to add labels (letters) above a barplot using ggplot2 function geom_text. My bars are separated using position=position_dodge() and so I need to apply the same for the new labels. However I would like to use also nudge_y to separate the labels from the bar. If I try to use both together R complains that I can use only one of either options. I'd like to do something like this:

Tukey.labels <- geom_text(data=stats,
                    aes(x=factor(Treatment2), y=x.mean, 
                        label=Tukey.dif),
                    size=4, nudge_y=3,            # move letters in Y
                    position=position_dodge(0.5)) # move letters in X

To create something like this image Does anybody knows a possibility to shift all my labels the same distance in Y while doing position_dodge at the same time? I could not find answer for this in other posts

teoten
  • 31
  • 1
  • 6

2 Answers2

7

Hard to troubleshoot without a reproducible example. Hopefully this helps:

library(dplyr); library(ggplot2)
ggplot(mtcars %>% rownames_to_column("car") , 
       aes(as.factor(cyl), mpg, group = car)) + 
  geom_col(position = position_dodge(0.9)) +
  geom_errorbar(aes(ymin = mpg - wt,
                    ymax = mpg + wt),
                position = position_dodge(0.9)) +
  geom_text(aes(label = gear, y = mpg + wt), vjust = -0.5,
            position = position_dodge(0.9))

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Thanks a lot it's perfect. It didn't work before because I was giving vjust positive value. – teoten Jun 30 '19 at 06:14
3

In the spirit of the original question, one can easily combine ggplot's position_nudge and position_dodge like this:

position_nudgedodge <- function(x = 0, y = 0, width = 0.75) {
    ggproto(NULL, PositionNudgedodge,
        x = x,
        y = y,
        width = width
    )
}

PositionNudgedodge <- ggproto("PositionNudgedodge", PositionDodge,
    x = 0,
    y = 0,
    width = 0.3,

    setup_params = function(self, data) {
        l <- ggproto_parent(PositionDodge,self)$setup_params(data)
        append(l, list(x = self$x, y = self$y))
    },

    compute_layer = function(self, data, params, layout) {
        d <- ggproto_parent(PositionNudge,self)$compute_layer(data,params,layout)
        d <- ggproto_parent(PositionDodge,self)$compute_layer(d,params,layout)
        d
    }
)

Then you can use it like this:

Tukey.labels <- geom_text(data=stats,
    aes(x=factor(Treatment2), y=x.mean, label=Tukey.dif),
    size=4,
    position=position_nudgedodge(y=3,width=0.5)
)
Jeremy
  • 51
  • 2