2017-06-29 63 views
1

我有一些数据。我想用堆积曲线来绘制,但每个堆栈指不同的变量:ggplot2:通过不同变量识别每个堆栈来组合堆积图

id <- c(1:10) 
date <- c("May","May","May","May","May", 
      "June","June","June","June","June") 
locations <- c("A1a","A1b","B1","A2","B2", 
       "A1","B1","A2a","A2b","B2") 
data <- c(220, 350, 377, 655, 740, 
      615, 760, 480, 179, 560) 
df <- data.frame(id,date,locations,data) 

library(ggplot2) 

这是亲如我能得到。

ggplot(df, aes(x=date, y=data, fill=locations)) + 
    geom_bar(stat="identity", position = "stack") 

我想A1a堆放B1,A1b堆放B1和A2堆放B2彼此相邻的五月; A1与B1堆叠,A2a与B2堆叠,A2b与B2堆叠在一起。每个月将有3个小节,每个小节将是我指定的2个变量的堆栈。提前致谢。

+0

没有A1A,A1B,A2A,A2B在DF。另外,我假设你想要y =数据,而不是y =日期。 –

+0

@EricWatt Opps忘了更新我的代码。 – phaser

回答

1

我不知道我是否正确理解了你的问题。
这里试图找到一个解决方案。希望它能帮助你。

id <- c(1:10) 
date <- c("May","May","May","May","May", 
      "June","June","June","June","June") 
locations <- c("A1a","A1b","B1","A2","B2", 
       "A1","B1","A2a","A2b","B2") 
data <- c(220, 350, 377, 655, 740, 
      615, 760, 480, 179, 560) 
df <- data.frame(id,date,locations,data) 

df$date <- factor(df$date, levels=c("May","June")) 
df1 <- cbind(df[c(1,3,2,3,4,5,6,7,8,10,9,10),], 
      grp=factor(rep(c(1:3),each=2))) 

library(ggplot2) 
ggplot(df1, aes(x=grp, y=data, fill=locations)) + 
    geom_bar(stat="identity", position = "stack")+ 
    facet_grid(.~date) 

enter image description here