R ggplot stacked geom_rect

ぃ、小莉子 提交于 2021-02-11 04:54:30

问题


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?


回答1:


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




回答2:


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")         



来源:https://stackoverflow.com/questions/40361800/r-ggplot-stacked-geom-rect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!