Reputation: 355
I have a stacked bar chart in ggplot with geom_text() labels centered on each bar. I want to hide labels on small bars so that the graph does not look overly crowded. I can do this with the code below, but it messes up the positioning of the labels as you can see in the linked picture below (they are no longer centered).
Is there a way to hide bar chart labels that doesn't mess up the positions of the remaining labels?
ggplot(data=outcome,
aes(x = category, y=percent,fill = outcome)) +
geom_bar(stat='identity') +
coord_flip() +
geom_text(data=outcome %>% filter(percent>=0.1),aes(label = percent), size = 3,position = position_stack(vjust = 0.5),
check_overlap=TRUE)
Upvotes: 2
Views: 2104
Reputation: 36076
You can use an ifelse()
statement. Here I put blanks every time I didn't want a label, but NA
also works.
library(ggplot2)
df = data.frame(
x = factor(c(1, 1, 2, 2)),
y = c(1, 3, 2, 1),
grp = c("a", "b", "a", "b")
)
ggplot(data = df, aes(x, y, fill = grp)) +
geom_col() +
coord_flip() +
geom_text(aes(label = ifelse(y > 1, y, "")),
position = position_stack(vjust = 0.5),
size = 3)
Created on 2018-08-07 by the reprex package (v0.2.0).
Upvotes: 7