How to adjust the label for bar chart?

Created a bar chart by following code, the label for bar is not properly aligned with the bar, trying to adjust, but the direction to move the label for each bar group is different, can anyone help to fix the problem? thanks.

cdata<- data.frame(cyl=c("4","6","8","4","6","8"),
                    value=c(26.7,19.7,15.1,13.3,9.87,7.55),
                    grp=rep(c("Treatment","Placebo"), each=3))

graph <- ggplot(cdata, aes(x = cyl, y = value, fill = grp)) +
  geom_bar(stat = "identity",
           width = 0.5, position="dodge") + 
  theme_classic()

graph + geom_text(aes(label=value), color="black", size=3) + 
  theme_classic()
suppressPackageStartupMessages({
  library(ggplot2)
})

cdata<- data.frame(cyl=c("4","6","8","4","6","8"),
                   value=c(26.7,19.7,15.1,13.3,9.87,7.55),
                   grp=rep(c("Treatment","Placebo"), each=3))

ggplot(data = cdata, aes(cyl, value, group = grp)) +
  geom_col(aes(fill = grp), position = "dodge") +
  geom_text(
    aes(label = value, y = value + 0.05),
    position = position_dodge(0.9),
    vjust = 0
  ) + theme_minimal()

Created on 2022-10-29 by the reprex package (v2.0.1)

2 Likes

Im try with geom_bar()

ggplot(cdata) + 
  geom_bar(
    aes(x = cyl, y = value, fill = grp, group = grp), 
    stat='identity', position = 'dodge'
  ) +
  geom_text(
    aes(x = cyl, y = value, group = grp, label=value),
    position = position_dodge(width = 1),
    vjust = -0.5, size = 3
  ) + 
  theme_bw()

2 Likes

Thank you! position_dodge is useful to put label in right position.

geom_bar also works, thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.