Ggplot barchart: how to show categories with zero counts?

3,166 views
Skip to first unread message

Bart

unread,
Mar 16, 2012, 4:37:11 AM3/16/12
to ggp...@googlegroups.com
First of all, sorry I'm double posting (already posted this in R-help), but I only just found out there was a seperate R mailinglist.

My question is how can I make sure that unused factor levels (those zero counts in dataset) show up in the barchart, but simply without a bar (zero counts). I would like to achieve this because I'm displaying data from a Likert-like scale and it looks very strange when categories disappear from question to question.

This pictures shows my problem http://oi40.tinypic.com/fodsm0.jpg

Example code:
library(ggplot2) 
mtcars$cyl<-factor(mtcars$cyl) 
ggplot(mtcars[!mtcars$cyl==4,], aes(cyl))+geom_bar() 
levels(mtcars[!mtcars$cyl==4,]$cyl)

Thanks in advance!

Kohske Takahashi

unread,
Mar 16, 2012, 8:25:33 AM3/16/12
to Bart, ggp...@googlegroups.com
try this:

ggplot(mtcars[!mtcars$cyl==4,], aes(cyl))+geom_bar() + scale_x_discrete(drop=F)


2012年3月16日17:37 Bart <bartsm...@gmail.com>:


> library(ggplot2)
> mtcars$cyl<-factor(mtcars$cyl)
> ggplot(mtcars[!mtcars$cyl==4,], aes(cyl))+geom_bar()
> levels(mtcars[!mtcars$cyl==4,]$cyl)

--
--
Kohske Takahashi <takahash...@gmail.com>

Research Center for Advanced Science and Technology,
The University of Tokyo, Japan.
http://www.fennel.rcast.u-tokyo.ac.jp/profilee_ktakahashi.html

Bart

unread,
Mar 16, 2012, 12:06:57 PM3/16/12
to ggp...@googlegroups.com, Bart
Thanks! I guess the standard behaviour changed in ggplot2.0.9 vs. ggplot2.0.8.9?

Regards,
Bart

Op vrijdag 16 maart 2012 13:25:33 UTC+1 schreef kohske het volgende:
Reply all
Reply to author
Forward
0 new messages