首页 > 解决方案 > position_dodge on geom_text on dodged barplot

问题描述

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.

标签: rggplot2dplyr

解决方案


尝试:

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

请注意,我通过aes()ggplot().

在此处输入图像描述


推荐阅读