Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally hiding data labels in ggplot2 graph

Tags:

r

ggplot2

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)
like image 235
user1839897 Avatar asked Nov 11 '14 16:11

user1839897


1 Answers

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)

enter image description here

like image 96
MrFlick Avatar answered Oct 10 '22 01:10

MrFlick