Reputation: 73
I have 2 variables in 2 different datasets organized in the same sequences
df1:
LoopGW NPV Model
1 200 1
2 300 1
df2:
LoopGW NPVadjusted Model
1 300 3
2 400 3
I've tried this:
boxplot(NPV ~ loopGW, data = df1)
boxplot(NPVadjusted ~ loopGW, data= df2, add = TRUE)
But what I got is the boxplot with overlap.
I want all four boxplots separated and colored by model. Could anyone please help? Thanks so much
Upvotes: 1
Views: 76
Reputation: 6441
You haven't really provided a reproducible example, so i just worked with what I had. Hope it does what you want. There might be better ways to get there but this is what I did:
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()
And that's the result. You have to imagine 4 nice boxplots there. ^^
I hope thats what you want. 4 Boxplots seperated by Loop and Model? And Colored by Model.
Upvotes: 2