Ggplot2 geom_bar gives error when position = "fill" in some scenarios

I am getting an error when I try to use position = "fill" for geom_bar. Here's the 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")

      

The first call to ggplot works great, creating a bar with three colors for each bar, corresponding to levels 0,1 and 2. The legend shows the final level (3), but since the weight is always 0, it is not displayed on the graph.

However, the second call to ggplot returns an error. I expected it to return the same plot as before, but just scales each bar height to 1. Any idea why this is happening and if there is a workaround?

+3


source to share


1 answer


Seems to weight

be <0> when used position=fill

. If you do:

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

      



then it works.

+3


source







All Articles