简体   繁体   中英

How to add a factor level on the x-axis that represents all the observations in ggplot2?

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM