R 当位置=”时,ggplot2 geom_栏给出错误;填写「;在某些情况下

R 当位置=”时,ggplot2 geom_栏给出错误;填写「;在某些情况下,r,ggplot2,R,Ggplot2,尝试对几何图形条使用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(

尝试对几何图形条使用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。你知道为什么会发生这种情况,以及是否有解决办法吗?

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

ggplot(temp[temp$weight > 0,], 
    aes(x=X, weight=weight, fill=factor(fill))) + 
    geom_bar(bin_width=1, position="fill")    
然后它就起作用了