Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 774
Heisenberg Avatar asked May 31 '15 21:05

Heisenberg


1 Answers

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

enter image description here

like image 84
LyzandeR Avatar answered Sep 27 '22 23:09

LyzandeR