R ggplot堆叠geom_rect [英] R ggplot stacked geom_rect

查看:41
本文介绍了R ggplot堆叠geom_rect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用ggplot绘制条形图,在其中调整条形的宽度.我在

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?

解决方案

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

这篇关于R ggplot堆叠geom_rect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆