Reputation: 65
I am doing the #duboischallenge and am on challenge 5.
I would like to remove the labels "0%" on the plot.
code (still learning so might not be most efficient code!):
income <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-02-16/income.csv')
data5 <- income %>%
gather(expenses, percentage, 3:7) %>%
mutate(percentage = replace_na(percentage, 0))
data5$expenses <- factor(data5$expenses, levels = c("Other", "Tax", "Clothes", "Food", "Rent"))
data5$Class <-factor(data5$Class, levels = c("Over $1000", "$750-1000", "$500-750", "$400-500", "$300-400", "$200-300", "$100-200"))
plot5 <-ggplot(data5, aes(x = Class, y = percentage, fill = expenses)) +
geom_bar(position = "fill", stat = "identity")+
scale_fill_manual(values = c("black", "blueviolet", "darksalmon", "azure3", "cornsilk3"), breaks = c("Rent", "Food","Clothes", "Tax", "Other"))+
geom_text(aes(x = Class, y = percentage, label = paste0(percentage, "%")), color = if_else(data5$expenses == "Rent", "white", "black"), size = 3.5, position = position_fill(vjust = 0.5)) +
coord_flip()
geom_text(data = data5 %>% filter(percentage > 3),aes(x = Class, y = percentage, label = paste0(percentage, "%")), color = if_else(data5$expenses == "Rent", "white", "black"), size = 3.5, position = position_fill(vjust = 0.5))
I get this error: Error: Aesthetics must be either length 1 or the same as the data (32): colour
How do I remove the "0%" labels?
Upvotes: 1
Views: 1511
Reputation: 1252
You can simply take the same approach like with colouring the labels:
ggplot(data5, aes(x = Class, y = percentage, fill = expenses)) +
geom_bar(position = "fill", stat = "identity")+
scale_fill_manual(values = c("black", "blueviolet", "darksalmon", "azure3", "cornsilk3"), breaks = c("Rent", "Food","Clothes", "Tax", "Other"))+
geom_text(aes(x = Class, y = percentage,
label = ifelse(percentage > 0, paste0(percentage, "%"), "")),
color = if_else(data5$expenses == "Rent", "white", "black"), size = 3.5, position = position_fill(vjust = 0.5)) +
coord_flip()
Upvotes: 1