I have a theoretical range of factors from M1 to M11. In the data M1 to M3 and M5 doesn't exist. How can I ggplot2 barplot with all Ms, not only the existing, so that M1 to M3 and M5 are also shown in the x-axis?

有帮助吗?

解决方案 2

Your question is not reproducible, so I'll illustrate on a stand alone code

If you"ll run

library(ggplot2)
ggplot(mtcars, aes(factor(cyl))) + geom_bar()

You'll get

enter image description here

If you wish to add unused levels to factor(cyl) you can use scale_x_discrete using limits and drop = F.

For Example

ggplot(mtcars, aes(factor(cyl))) + geom_bar() + 
scale_x_discrete(limits = c(1, 2, levels(factor(mtcars$cyl)), 10), drop=FALSE)

Will produce

enter image description here

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top