1

My DF looks like this:

      Date          H2 Value
2018-06-04      H2_Avg  0.08
2018-06-07      H2_Avg  0.11
2018-06-16      H2_Avg  0.12
2018-06-20      H2_Avg  0.13
2018-06-23      H2_Avg  0.24
2018-06-26      H2_Avg  0.16
2018-06-30      H2_Avg  0.24
2018-07-04      H2_Avg  0.38
2018-07-09      H2_Avg  0.44
2018-07-12      H2_Avg  0.34
2018-06-04 H2_disabled  0.07
2018-06-07 H2_disabled  0.09
2018-06-16 H2_disabled  0.10
2018-06-20 H2_disabled  0.14
2018-06-23 H2_disabled  0.23
2018-06-26 H2_disabled  0.18
2018-06-30 H2_disabled  0.22
2018-07-04 H2_disabled  0.33
2018-07-09 H2_disabled  0.27
2018-07-12 H2_disabled  0.24

I want to plot a dodged barplot with the values written within the columns. My code to plot looks like this:

DF %>% ggplot() +
  geom_col(aes(Date, Value, fill = H2), position = "dodge") +
  geom_text(aes(Date, Value, label = Value), 
            position = position_dodge(width = 1), 
            vjust = 1.5)

This outputs the following: enter image description here As you can see, the values specified by geom_text are not legible where the differences between the two columns are small. Is there a way to improve this? Flipping the coordinates and then using the position_dodge argument as proposed here: Position geom_text on dodged barplot does not work for my data due to the small differences between the two groups.

M--
  • 25,431
  • 8
  • 61
  • 93
Roggan
  • 155
  • 1
  • 11
  • Possible duplicate of [Plot text/labels centered on a dodged bar plot](https://stackoverflow.com/questions/44818459/plot-text-labels-centered-on-a-dodged-bar-plot) – M-- Nov 09 '18 at 15:28

2 Answers2

1

Try:

DF %>% ggplot(aes(Date, Value, fill = H2)) +
  geom_col(position = "dodge") +
  geom_text(aes(label = Value), 
            position = position_dodge(width=1),
            vjust=1.5)

Please note that I made the code a bit shorter by including aes() already in ggplot().

enter image description here

alex_555
  • 1,092
  • 1
  • 14
  • 27
  • Nope, I still get the same solution as above. My graphic device does not output me the same spacing of the geom_text values as yours does. Seems like an error on the graphics device imo. restarting R did not help either. – Roggan Nov 09 '18 at 16:30
  • Did you already try to save your plot e.g. to pdf or to png? Maybe it's just R or RStudio. You might also try to update ggplot2, R and / or RStudio – alex_555 Nov 09 '18 at 18:03
1

I finally found the cause of the problem. It had to do with the formatting of the "Date" Column. I had it formatted as a POSIXct date format. For some reason this messed with the position_dodge formatting as described in my original question. Reformatting the date as a plain character solved the question and gave me the same plot as @alex_555's solution.

Roggan
  • 155
  • 1
  • 11