I am creating some stacked bar charts in ggplot 2, and wonder how I can conditionally hide certain data labels if they are smaller than a defined percentage of the total, e.g., 10%.
As you can see from the plot generated from the code below, some of the labels become too huge relative to the thickness of the bar. So I would like to hide those than less than the defined threshold. How can I modify the ggplot code below to achieve that? Thanks!
library(ggplot2)
library(dplyr)
#Creating the dataset
my.data <- data.frame(dates = c("1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014"),
fruits=c("apple", "orange", "pear", "berries", "watermelon", "apple", "orange", "pear", "berries", "watermelon"),
count=c(20, 30, 40, 2, 2, 30, 40, 50, 1, 1))
#Creating a positon for the data labels
my.data <-
my.data %>%
group_by(dates) %>%
mutate(pos=cumsum(count)-0.5*count)
#Plotting the data
ggplot(data=my.data, aes(x=dates, y=count, fill=fruits))+
geom_bar(stat="identity")+
geom_text(aes(y=pos, label=count), size=4)
You can subset the data in the geom_text
layer. For example
ggplot(data=my.data, aes(x=dates, y=count, fill=fruits))+
geom_bar(stat="identity")+
geom_text(data=subset(my.data, count>10), aes(y=pos, label=count), size=4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With