I am having issues with making barchart in which the y axis is not count, but value from variables.
I use stat=identity
, which is fine for one variable. But what if I have two variables and want to create a stacking / dodging barchart?
I have some mock data here:
foo <- data.frame(case=c('A','B','C'), var1=rnorm(3), var2=rnorm(3))
So my three cases on x-axis are A, B, and C. I want to plot the values of var1 and var2 as bars. Thanks!
First, changed your sample data. When making data frame you don't need cbind()
because in this case you make all columns as factors.
foo <- data.frame(case=c('A','B','C'), var1=rnorm(3), var2=rnorm(3))
To use two variables for barplot easiest way would be to melt the data from wide to long format.
library(reshape2)
foo.long<-melt(foo)
foo.long
case variable value
1 A var1 0.7150827
2 B var1 -0.5279363
Now use value
as y values and variable
for the fill. stat="identity"
and position="dodge"
will ensure that actual values are plotted and bars are dogged.
ggplot(foo.long, aes(case,value,fill=variable))+
geom_bar(position="dodge",stat="identity")
I am not answering the question, in the sens I am not using ggplot2
. But, if you want to use the data.frame in its wide format, one other way is to use ``barchartfrom
latticepackage. To get
ggplot2theme, I am using
latticeExtra`. Using @Didzis data:
library(latticeExtra)
barchart(var1+var2~case,data=foo,origin=0,
par.settings = ggplot2like(),axis=axis.grid,auto.key=TRUE)