2013-03-25 52 views
4

在ggplot2中绘制条形图时,我有因子变量的正确顺序问题。我使用两个geom_bars与原始数据集的子集(变量g与两个级别'A'和'B')。两个geom_bar()和因子变量的错误顺序

如何保留因子变量的原始顺序? 当我的var是数字时没有问题,但假设x应该是因子。

这里是我的代码:

library(plyr) 
library(ggplot2) 

dane<-data.frame(x=1:10,y=seq(-5,4),g=rep(c('A','B'),each=5)) 
    dane$x<-as.factor(dane$x) 

     ggplot(data=dane,aes(x=x,y=y,fill=g)) + 
     geom_bar(subset=.(g=='A'),stat='identity') + 
     geom_bar(subset=.(g=='B'),stat='identity') 

,并导致

WrongOrder

编辑: 我忘了图书馆复制代码。

+0

看来值得指出的是你的示例的简化版本产生所需的输出:'ggplot(丹麦人,AES(X = X,Y = Y,填充=克))+ geom_bar( STAT = “同一性”)'。 – bdemarest 2013-03-25 21:25:49

+0

我认为子集可能会搞乱因子水平。这对我来说就像是错误的行为。无论如何,它都应该尊重关卡的顺序。您可以尝试在github上查找与此相关的问题。 – joran 2013-03-25 21:32:51

+0

@bdemarest这只是一个例子。我知道我只能使用一个geom_bar,但实际上有时我需要多个。 – Maciej 2013-03-25 21:35:29

回答

3

我在github上得到了一个答案(真的很快,我印象深刻:))。 Brian Diggs建议使用scale_x_discrete(drop = FALSE)来解决我的问题。 Here's the link to my github report and solution。现在,结果如我所愿。

ggplot(data=dane,aes(x=x,y=y,fill=g)) + 
    geom_bar(subset=.(g=='A'),stat='identity') + 
    geom_bar(subset=.(g=='B'),stat='identity') + 
    scale_x_discrete(drop=FALSE) 

enter image description here

+0

(+1)感谢您将它写回到此处。 – Arun 2013-03-25 22:34:42

+0

我希望其他用户会发现这篇文章有用。 ;) – Maciej 2013-03-25 22:46:51