Reputation: 614
I would like to know how to use a single factor level as a reference to plot other factors against. For instance I have the following:
set.seed(4)
x <- factor(c('A','B','A','B','A','B','A','B'))
z <- factor(c('a','a','b','b','c','c','d','d'))
y <- runif(8)
df <- data.frame(x,y,z)
p <- ggplot(df, aes(x=x, y=y, fill=z)) +
geom_bar(stat = 'identity', position='dodge')
However unlike the above plot I would like to add a facet dimension something like:
p+facet_grid(.~z)
but unlike what the above code would give, only showing facets for c('a','b','c') levels and plotting each of these against 'd' as a reference with position='dodge'.
Upvotes: 0
Views: 530
Reputation: 215117
If allowed, you can do some transformation of your data before you visualize the result. It might be cumbersome, but you can add an additional variable to discriminate the variable z with c("a", "b", "c")
and with "d"
. And then place the color and position according to the additional variable while transforming the original z
variable into a facet variable. In this way you separate variables which determine the facets from the variables that determine the color and position.
library(dplyr)
library(tidyr)
df1 <- df %>% mutate(m = ifelse(z == "d", "d", "abc")) %>%
mutate(z = ifelse(z == "d", "a,b,c", as.character(z))) %>%
mutate(z = strsplit(z, ",")) %>% unnest(z)
p <- ggplot(df1, aes(x=x, y=y, fill=m)) +
geom_bar(stat = 'identity', position='dodge') + facet_grid(. ~ z)
Upvotes: 1