在 r 中具有相同组的多个数据集中具有多个变量的箱线图

Boxplot with multiple variables in multiple dataset with the same group in r

我在以相同序列组织的 2 个不同数据集中有 2 个变量

df1:

LoopGW    NPV         Model
1          200         1
2          300         1

df2:

LoopGW    NPVadjusted        Model
1            300              3
2            400              3

我试过这个:

boxplot(NPV ~ loopGW, data = df1)
boxplot(NPVadjusted ~ loopGW, data= df2, add = TRUE)

但我得到的是重叠的箱线图。

我想要所有四个箱线图按模型分开和着色。有人可以帮忙吗?非常感谢

你并没有真正提供一个可重现的例子,所以我只是用我所拥有的。 希望它做你想要的。可能有更好的方式到达那里,但这是我所做的:

library(tidyr)
library(ggplot2)

#read the data
df1 <- read.table(text = "
LoopGW    NPV         Model
1          200         1
2          300         1", stringsAsFactors = FALSE, header = TRUE)

df2 <- read.table(text = "
LoopGW    NPVadjusted        Model
1            300              3 
2            400              3", stringsAsFactors = FALSE, header = TRUE)

#preparing the data.frames for binding so no information gets lost.
d1g <- gather(df1, key = "NPV_flag", value = "NPV", -Model, -LoopGW)
d2g <- gather(df2, key = "NPV_flag", value = "NPVadjusted", -Model, -LoopGW)

#binding the two data.frames
d12g <- rbind(d1g, setNames(d2g, names(d1g)))

#create the groups after which to seperate
d12g$Model_Loop <- paste(d12g$Model, "_", d12g$LoopGW, sep = "")

#Model as factor
d12g$Model <- as.factor(d12g$Model)

#Plot with ggplot
ggplot(d12g, aes(x = Model, y = NPV, group = Model_Loop, color = Model)) + geom_boxplot()

这就是结果。你必须想象那里有 4 个漂亮的箱线图。 ^^

希望这就是你想要的。 4 个由循环和模型分隔的箱线图?并按型号着色。