2016-11-01 170 views
1

我想繪製一個條形圖與ggplot,其中我調整了酒吧的寬度。我找到了一個例子here,它工作得很好。但是我不希望數據框中每行有一個條,而是要製作一個2到4列的堆疊條。這裏是原來的代碼:現在R ggplot堆疊geom_rect

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或有其他我應該嘗試?

回答

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

我讓你選擇更好的色彩

+0

@亞歷克斯KLI ndt是否有效?你可以標記爲已解決? – timat

1

你也能試試這個(如果你想不同的顏色,不同的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