If your factor is capable of having all those levels at some point, it makes more sense to set the levels of the factor than to add it to the limits when you ggplot
it. So:
Make cyl
a factor starting with M (So M4, M6 and M8 only)
mtcars$cyl=factor(paste("M",mtcars$cyl,sep=""))
Augment the levels:
mtcars$cyl = factor(mtcars$cyl, levels=paste("M",1:10,sep=""))
Now its just a drop=FALSE
in your ggplot
:
ggplot(mtcars, aes(cyl)) + geom_bar() + scale_x_discrete(drop=FALSE)
Why do I think this is better? Well, because you have tied an aspect of your data (the possible levels) with the data itself, rather than a plotting function. Suppose you have a bunch of plotting functions, now you have to code that level fix in each of them. Put the possible levels in the factor and that information is carried around with the data. All you need to do is decide on drop=FALSE
or drop=TRUE
at plot time.