Peter
Peter

Reputation: 355

R ggplot stacked geom_rect

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?

Upvotes: 1

Views: 1368

Answers (2)

Sandipan Dey
Sandipan Dey

Reputation: 23129

You can try this too (in case you want different color for different rects):

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))
data$right=cumsum(data$number_of_obs) + 30*c(0:(nrow(data)-1))
data$left=data$right - data$number_of_obs 

# dataframe with value
data1 <- data[-2:-3]
data1$ymin <- 0
data1$ymax <- data$value

# dataframe with value2
data2 <- data[-2:-3]
data2$ymin <- data$value
data2$ymax <- data$value + data$value2
data2$group <- paste(data$group, '2') # same group but with value2

# combine
data <- rbind(data1, data2)

# plot
ggplot(data) + 
  geom_rect(aes(xmin = left, xmax = right, ymin=ymin, ymax = ymax, colour = group, fill = group)) +
  xlab("number of obs") + ylab("value")         

enter image description here

Upvotes: 2

timat
timat

Reputation: 1500

following the same logic you use xmin and xmax:

data$value_tot <- data$value + data$value2
# Plot
ggplot(data) + 
  geom_rect(aes(ymin = 0, xmin = left, xmax = right, ymax = value), fill = "blue") +
  geom_rect(aes(ymin = value, xmin = left, xmax = right, ymax = value_tot), fill = "red") +
  xlab("number of obs") + ylab("value")

I let you choose better color

Upvotes: 1

Related Questions