Search code examples
rggplot2positionlabel

How to add data labels at the top of crossbars using ggplot2


I have a code that does a nice job of plotting a crossbar plot from a dataframe, where the bottom and top of the bar represent respectively min and max of observed values, and the the cross line represents the average.

Now I have been asked to add data labels for the average value at the top of the bars, and that is more difficult than I imagined. I tried to adjust the label position using hjust, vjust, position_dodge and position_stack - but nothing works as I need

Anybody here can give suggestions?

Edit - Example of data and code for the crossbar plot can be found at this link: geom_crossbar produces a plot with inappropriate y scale

What am I unhappy with? The labels are all over the place, I am unable to put them in any specified position. While I (well, the manager to whom I report) want them at the top of the bars.


Solution

  • Here is a solution, using the data from the prior SO question, that puts the means at the top of the boxes, but the lower two are not aligned.

    my.data <- structure(list(factor1 = structure(c(1L, 1L, 2L, 2L), .Label = c("oil1", "oil2"),
              class = "factor"), factor2 = structure(c(1L, 2L, 1L, 2L), .Label = c("prod1", "prod2"),
              class = "factor"), value = c(1.7, 1, 29.8, 31.3), err = c(1.5, 1, 2, 2),
              min = c(0.2, 0, 27.8, 29.3), max = c(3.2, 2, 31.8, 33.3)), .Names = c("factor1", "factor2",
              "value", "err", "min", "max"), class = "data.frame", row.names = c("1", "2", "3", "4"))
    
    ggplot(data=my.data, aes(x=factor2, fill=factor1)) + 
      geom_crossbar(aes(y=value, ymin=min, ymax=max), position = position_dodge(width = 0.66), width=0.6) +
      geom_text(aes(y = max, label = value, hjust = -0.6, vjust = -0.4))
    

    enter image description here