R ggplot堆积了geom_rect

时间:2016-11-01 14:11:18

标签: r ggplot2

我想用ggplot画一个条形图,我调整条形的宽度。我找到了一个很好的例子here。但是,在数据框中每行不是一个条,我想制作2到4列的堆叠条。这是原始代码:

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

我的数据现在看起来像这样:

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

我想在一个条形图中用不同的颜色绘制值和值2。有没有办法用geom_rect做这个或者还有其他我应该尝试的东西吗?

2 个答案:

答案 0 :(得分:1)

按照相同的逻辑使用xminxmax

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

我让你选择更好的颜色

答案 1 :(得分:1)

您也可以尝试这种方式(如果您想要不同颜色的不同颜色):

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