Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hide '0' values (zero counts) in plots utilizing geom_count

I use geom_count() from the ggplot2 library to overlay the count (blue) on top of the total number (gray) for each dataset split by weeks (see example dataset and plot below). Sometimes, the count value is ‘0’ (here: in DS1, week 3).

# sample dataset
set.seed(1)
df = data.frame(dataset = paste0("DS",rep(1:4, each = 5)),
                week = paste0("Week ",rep(1:4,5)),
                count = c(sample(0:50, 20, replace = TRUE)),
                total = rep(50,20)) 

> df
   dataset   week count total
1      DS1 Week 1     3    50
2      DS1 Week 2    38    50
3      DS1 Week 3     0    50
4      DS1 Week 4    33    50
5      DS1 Week 1    22    50
6      DS2 Week 2    42    50
7      DS2 Week 3    13    50
8      DS2 Week 4    17    50
9      DS2 Week 1    50    50
10     DS2 Week 2    32    50
11     DS3 Week 3    20    50
12     DS3 Week 4    20    50
13     DS3 Week 1    41    50
14     DS3 Week 2    45    50
15     DS3 Week 3     9    50
16     DS4 Week 4     6    50
17     DS4 Week 1     8    50
18     DS4 Week 2    14    50
19     DS4 Week 3    20    50
20     DS4 Week 4    36    50

In this case, I don’t want the count (blue) to show up at all. However, there is still a tiny blob visible. Is it possible to remove that blob (top row, third column) from the plot somehow?

# plot
ggplot(df, aes(x = week, y = dataset)) +
  geom_count (aes(size=total), colour="lightgrey") +
  geom_count(aes(size=count), colour="cornflowerblue")  +
  scale_size(range = c(0,15), breaks=c(0,10,20,30,40,50)) +
  theme_minimal() +
  labs(y = "", x = "") +
  scale_y_discrete(limits=rev)  #invert order

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can remove the missing values inside ggplot using ifelse and na.rm = TRUE

ggplot(df, aes(x = week, y = dataset)) +
  geom_count(aes(size = total), colour = "lightgrey") +
  geom_count(aes(size = ifelse(count == 0, NA, count)), 
             colour = "cornflowerblue", na.rm = TRUE)  +
  scale_size(range = c(0, 15), breaks = c(0, 10, 20, 30, 40, 50)) +
  theme_minimal() +
  labs(y = "", x = "") +
  scale_y_discrete(limits = rev) 

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading