[R] Ggplot barchart drops factor levels: how to show them with zero counts?

Helios de Rosario helios.derosario at ibv.upv.es
Fri Mar 16 12:43:12 CET 2012


You can tell that levels must not be dropped with scale_x_discrete():

library(ggplot2)
mtcars$cyl<-factor(mtcars$cyl)
plot1 <- ggplot(mtcars[!mtcars$cyl==4,], aes(cyl))+geom_bar()
plot1 + scale_x_discrete(drop=FALSE)

Or explicitly set the values you want in the x axis with the argument
"limits":

plot1 + scale_x_discrete(limits=levels(mtcars$cyl))


Regards,
Helios


>>> El día 15/03/2012 a las 16:47, Bart6114 <bartsmeets86 at gmail.com>
escribió:
> Hello,
> 
> When plotting a barchart with ggplot it drops the levels of the
factor for
> which no counts are available.
> 
> For example:
> 
> library(ggplot)
> mtcars$cyl<-factor(mtcars$cyl)
> ggplot(mtcars[!mtcars$cyl==4,], aes(cyl))+geom_bar()
> levels(mtcars[!mtcars$cyl==4,])
> 
> This shows my problem. Because no counts are available for
factorlevel '4',
> the label 4 dissapears from the plot. However, I would still like it
to show
> up, but without a bar (zero observations).
> 
> I would like to use this for the presentation of data with a
Likert-like
> scale.
> 
> Thanks in advance!
> Bart
> 
> --
> View this message in context: 
>
http://r.789695.n4.nabble.com/Ggplot-barchart-drops-factor-levels-how-to-show-the

> m-with-zero-counts-tp4475417p4475417.html
> Sent from the R help mailing list archive at Nabble.com.

INSTITUTO DE BIOMECÁNICA DE VALENCIA
Universidad Politécnica de Valencia • Edificio 9C
Camino de Vera s/n • 46022 VALENCIA (ESPAÑA)
Tel. +34 96 387 91 60 • Fax +34 96 387 91 69
www.ibv.org

  Antes de imprimir este e-mail piense bien si es necesario hacerlo.
En cumplimiento de la Ley Orgánica 15/1999 reguladora de la Protección
de Datos de Carácter Personal, le informamos de que el presente mensaje
contiene información confidencial, siendo para uso exclusivo del
destinatario arriba indicado. En caso de no ser usted el destinatario
del mismo le informamos que su recepción no le autoriza a su divulgación
o reproducción por cualquier medio, debiendo destruirlo de inmediato,
rogándole lo notifique al remitente.



More information about the R-help mailing list