I would like to draw a bar chart with ggplot where I adjust the width of the bars. I have found an example here which works perfectly fine. But instead of one bar per row in the data frame I would like to make a stacked bar of 2 to 4 columns. Here is the code of the original:
library(ggplot2)
# make data
data=data.frame(group=c("A ","B ","C ","D ") , value=c(33,62,56,67) , number_of_obs=c(100,500,459,342))
# Calculate the future positions on the x axis of each bar (left border, central position, right border)
data$right=cumsum(data$number_of_obs) + 30*c(0:(nrow(data)-1))
data$left=data$right - data$number_of_obs
# Plot
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = value, colour = group, fill = group)) +
xlab("number of obs") + ylab("value")
My data now looks like this:
data=data.frame(group=c("A ","B ","C ","D ") , value=c(33,62,56,67) , value2=c(10,20,30,40), number_of_obs=c(100,500,459,342))
and I would like to plot value and value2 in one bar with different colors. Is there a way to do this with geom_rect or is there something other I should try?