ggplot + facet:没有数据的丢弃因子

时间:2015-06-17 15:33:30

标签: r ggplot2

我们说我有以下数据:

z <- structure(list(EVTYPE = c("AAA", "BBB", "CCC", "DDD", "ZZZ", 
"WWW", "AAA", "BBB", "CCC", "DDD", "ZZZ", "WWW"), variable = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("ZOMBIES", 
"PLANTS"), class = "factor"), value = c(354, 765, 389, 321, 438, 
NA, 121, 10, 90, 300, NA, 212)), .Names = c("EVTYPE", "variable", 
"value"), row.names = c(NA, -12L), class = "data.frame")

然后我就这样绘制:

ggplot(z, aes(EVTYPE, value, fill = variable)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    facet_wrap( ~ variable, scales = "free") + 
    theme(axis.text.x = element_text(angle=90, vjust=1))

具有以下结果:

sample plot

问题是:有没有办法不在左边显示因子WWW,在右边显示因子ZZZ(如你所见,两者都得{原始数据框中的{1}}?

1 个答案:

答案 0 :(得分:2)

可以通过以下方式使用na.omit完成此操作:

ggplot(na.omit(z), aes(EVTYPE, value, fill = variable)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  facet_wrap( ~ variable, scales = "free") + 
  theme(axis.text.x = element_text(angle=90, vjust=1))

结果如下:enter image description here

希望这有帮助。