Label only one bar in ggplot2
First you have to add position_dodge(width = .9
to dodge the text labels by the same amount as the bars, where .9 is the default width of geom_col
.
However, to make the dodging work all groups have to present in your data so you have to use the whole dataframe for geom_text
too. To label only one group use e.g. an ifelse
to set the labels for the other categories to an empty string.
library(ggplot2)
library(dplyr)
library(tidyr)
df <- iris |>
pivot_longer(-Species) |>
count(Species, name, wt = value, name = "value")
df |>
ggplot(aes(x = name, y = value, fill = Species)) +
geom_col(position = position_dodge()) +
geom_text(aes(label = ifelse(Species == "setosa", value, "")),
position = position_dodge(width = .9), vjust = 0)