Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot2:通过使用不同变量标识每个堆栈来组合堆叠图_R_Ggplot2 - Fatal编程技术网

R ggplot2:通过使用不同变量标识每个堆栈来组合堆叠图

R ggplot2:通过使用不同变量标识每个堆栈来组合堆叠图,r,ggplot2,R,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,

我有一些数据。我想使用堆叠图对其进行绘制,但每个堆叠都引用不同的变量:

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)

我想要A1a与B1堆叠,A1b与B1堆叠,A2与B2堆叠,并排存放5月份;6月份A1与B1叠加,A2a与B2叠加,A2b与B2叠加。每个月将有3个条,每个条将是我指定的2个变量的堆栈。提前谢谢。

我不确定我是否正确理解了你的问题。
下面是一个试图找到解决方案的尝试。希望它能帮助你

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)

id您的df中没有A1a、A1b、A2a、A2b。另外,我假设您想要的是y=data,而不是y=date。@EricWatt Opps忘记更新我的代码了。
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)