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
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 usesstack
.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.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
I get this,
Is that what you are looking?