我有一些数据。我想使用堆叠图来绘制图形,但每个堆栈都引用不同的变量:
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叠加在一起为5月; A1与A1堆叠,A2a与B2堆叠,A2b与B2堆叠6月。每个月将有3个柱,每个柱将是我指定的2个变量的堆栈。提前谢谢。
答案 0 :(得分: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)