ggplot2 stacked bar chart - object y not found

2019-06-16 19:35发布

I'm trying to make a very simple stacked bar chart in ggplot2, but for some reason it doesn't work and I get the error message: "Error in pmin(y, 0) : object 'y' not found". Where's the problem?

factorvar <- c(1,1,1,2,2,2,3,3,3)
factorvar <- factor(factorvar, labels=c("Type", "Size", "Outcome"))
freq <- c(3,1,4,1,2,2,4,1,1)
fillvar <- c(1,1,1,2,2,2,3,3,3)
fillvar <- factor(fillvar)

df.harvest <- data.frame(fillvar,freq,factorvar)

harvest <- ggplot(df.harvest, aes(x=factorvar, y=freq, fill=fillvar)) + geom_bar()
harvest

标签: r ggplot2
3条回答
ゆ 、 Hurt°
2楼-- · 2019-06-16 20:17

This is pretty old but I didn't see any good answer for it:

You should always specify the arguments in geom_bar if you are providing the y axis.

You are already providing frequency as y axis and don't want geom_bar to calculate it for you, so you must specify geom_bar(stat = "identity")

Also, here your fillvar is essentially the same as factorvar and there is no point in using one as axis and one as fill color.

However if they were different, you had to also specify geom_bar(stat = "identity", position="dodge") or (stat = "identity", position="stack").

By default, the stat was switching to "bin" in your case and it was giving the error. Also by default, the position uses stack.

查看更多
贼婆χ
3楼-- · 2019-06-16 20:28

I'm not sure what the error message means, but if you use fillvar = c(1,2,3,1,2,3,1,2,3), (in place of your fillvar variable) you will get a stacked bar chart.

查看更多
The star\"
4楼-- · 2019-06-16 20:35

I'm not really sure if I understand what you want to count and what you want to stack, but using some of your data and this code

qplot(factor(freq), data=df.harvest, geom="bar", fill=factorvar) 

I get this,

qplot(factor(freq), data=df.harvest, geom="bar", fill=factor(factorvar))

Is that what you are looking?

查看更多
登录 后发表回答