Bodhi Bose
Bodhi Bose

Reputation: 33

how to add geom_text labels at the bottom of each group in ggplot2

I am trying to add dates below each grouped bar i.e. between 0 of y-axis and product labels at x-axis. Listed is a reprex.

df1 <- data.frame(product = c("A","A","A","A","A","A","A","B","B","B","B","B","B","B","C","C","C","C","C","C","C","D","D","D","D","D","D","D"), 
                  start_date =as.Date(c('2020-02-01', '2020-02-02', '2020-02-03', '2020-02-04', '2020-02-05', '2020-02-06', '2020-02-07')),
                  value = c(15.71,17.37,19.93,14.28,15.85,10.5,8.58,5.62,5.19,5.44,4.6,7.04,6.29,3.3,20.35,27.92,23.07,12.83,22.28,21.32,31.46,34.82,23.68,29.11,14.48,25.2,16.91,27.79))

graph <- ggplot(df1, aes(y = value, x = product, fill = product, group = factor(start_date))) +
  geom_col(data = df1, stat = "identity",position = position_dodge(width = 0.8), width = 0.7, inherit.aes = TRUE, size = 0) + 
  geom_text(aes(label= format(as.Date(start_date,format="%Y-%m-%d"), format = "%d")), vjust = "bottom", position = position_dodge(width = 0.8), inherit.aes = TRUE) +
  xlab("Product") + ylab("Values") 

Even if I adjust vjust or hjust values I get the below plot enter image description here

I would like the dates similar to the plot below enter image description here

Upvotes: 1

Views: 1608

Answers (1)

chemdork123
chemdork123

Reputation: 13793

You nearly have it, but the key is to realize that all of the text has the same y value: which in this case is a bit below 0. This works:

graph <- ggplot(df1, aes(y = value, x = product, fill = product, group = factor(start_date))) +
    geom_col(position = position_dodge(width = 0.8),
        width = 0.7, inherit.aes = TRUE, size = 0) +
    geom_text(aes(
            label= format(as.Date(start_date,format="%Y-%m-%d"), format = "%d"),
            y=-0.5
        ),
        position = position_dodge(width = 0.8), size=2) +
    xlab("Product") + ylab("Values")

enter image description here

Also note I removed bits here and there that were not needed, since they were inherited: (1) data= call for geom_col, and (2) stat= call for geom_col.

Upvotes: 2

Related Questions