【问题标题】:ggplot2 geom_bar gives error when position="fill" in some scenariosggplot2 geom_bar 在某些情况下 position="fill" 时会出错
【发布时间】:2013-02-19 14:15:54
【问题描述】:

尝试对 geom_bar 使用 position="fill" 时出现错误。这是一个 MWE:

temp = data.frame( X=rep(1:10,10), weight=runif(100), fill=rbinom(100,size=3,p=.5) )
temp$weight[temp$fill==3] = 0
ggplot( temp, aes(x=X, weight=weight, fill=as.factor(fill)) ) +
  geom_bar(bin_width=1)
ggplot( temp, aes(x=X, weight=weight, fill=as.factor(fill)) ) +
  geom_bar(bin_width=1,position="fill")

第一个 ggplot 调用工作正常,生成一个条形图,其中每个条形图由对应于级别 0、1 和 2 的 3 种颜色组成。图例显示了最终级别 (3),但由于权重始终为 0,它没有出现在情节中。

但是,第二个 ggplot 调用返回错误。我原以为它会返回与以前相同的图,但只是将每个条形的高度缩放到 1。知道为什么会发生这种情况,是否有解决方法?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    当您使用position=fill 时,它似乎期望weight > 0。如果你这样做:

    ggplot(temp[temp$weight > 0,], 
        aes(x=X, weight=weight, fill=factor(fill))) + 
        geom_bar(bin_width=1, position="fill")    
    

    然后就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      相关资源
      最近更新 更多