It's easy to create plots where the x-axis has each of the factor levels as follows:
df <- data.frame(value = rnorm(100), group = rep(1:3, length=100))
ggplot() + geom_boxplot(aes(factor(group), value), data=df)
I want to add another factor level on the x-axis that uses data from the entire sample (instead of from only one group). A manual way to do is to rbind
the data frame to itself as follows:
df2 <- rbind(df, df)
df2$group[100:200] <- "entire sample"
ggplot() + geom_boxplot(aes(factor(group), value), data=df2)
However, sometimes my data frame is quite complex and I want to avoid duplicating my data frame as such. Is there a better way?
You can do it like this:
ggplot() + geom_boxplot(aes(factor(group), value), data=df) +
geom_boxplot(aes('entire sample', value), data=df)
And you get the same result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With