dev
dev

Reputation: 37

Displaying select barplot data labels in ggplot

I have a stacked barplot in ggplot. It has count data labels. However, the labels overlap in small bars resulting in it not being possible to read. To clean up the figure and resolve this, I think the best approach is to omit data labels (but keep the bars) for counts less than 5. I am unsure how to do this but I suspect I will need to apply some form of filter function to the code: "geom_text(stat = 'count', aes(label = ..count..), position = position_stack(vjust = 0.5))"

My code is below:

library(tidyverse)
custom_colors <- c("grey", "darkgrey")
df %>%
  ggplot(aes(x = fct_infreq(job), fill=comms, pattern = 'stripe',)) +
  theme(text=element_text(size=10, family="Times New Roman"))+
  geom_bar(position = "stack")+
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
        legend.position='bottom',
        panel.background = element_blank(),
        panel.grid.major = element_blank(),   
        panel.grid.minor = element_blank(),
        )+
  labs(title = "", x="Job Title", y="Number of Participants (n)", fill='')+
  geom_text(stat = 'count', aes(label = ..count..), position = position_stack(vjust = 0.5))+
  scale_fill_manual(values = custom_colors)

The output figure is below: enter image description here

My goal is to remove all of the data labels that are less than 5.

As a side note: any advice on getting the pattern='stripe' to work?

Upvotes: 0

Views: 34

Answers (1)

stefan
stefan

Reputation: 125133

You could use ifelse to conditionally set the label to an empty string or NA for cases with a count < 5. Additionally I switched to after_stat as the .. notation was deprecated in ggplot2 3.4.0.

Using some random example data:

library(tidyverse)

set.seed(123)

df <- list(
  data.frame(
    job = sample(LETTERS, 500, replace = TRUE),
    comms = "a"
  ),
  data.frame(
    job = sample(LETTERS, 80, replace = TRUE),
    comms = "b"
  )
) |>
  bind_rows()

custom_colors <- c("grey", "darkgrey")

df %>%
  ggplot(aes(x = fct_infreq(job), fill = comms, pattern = "stripe", )) +
  theme(text = element_text(size = 10, family = "Times New Roman")) +
  geom_bar(position = "stack") +
  theme(
    axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
    legend.position = "bottom",
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
  ) +
  labs(title = "", x = "Job Title", y = "Number of Participants (n)", fill = "") +
  geom_text(
    stat = "count",
    aes(label = after_stat(
      ifelse(count < 5, "", count)
    )),
    position = position_stack(vjust = 0.5)
  ) +
  scale_fill_manual(values = custom_colors)

Upvotes: 1

Related Questions