Reputation: 32558
Here is my data
set.seed(42)
dat = data.frame(iter = rep(1:3, each = 10),
variable = rep(rep(letters[1:2], each = 5), 3),
value = rnorm(30))
I know I can draw violin plots for a
and b
with
library(ggplot2)
ggplot(data = dat, aes (x = variable, y = value)) + geom_violin()
But how do I draw violin plots for each iteration of a
and b
so that there will be three plots for a
next to three plots for b
. I have done it previously using base plot but I am looking for a better solution since the number of iterations as well as number of 'a's and 'b's keeps on changing.
Upvotes: 1
Views: 3682
Reputation: 170
There are two possible ways. One would be by adding a fill command, the other using facet_wrap
(or facet_grid
)
With fill:
ggplot(data = dat, aes (x = variable, y = value, fill = as.factor(iter))) + geom_violin(position = "dodge")
Or using facet_wrap
:
ggplot(data = dat, aes (x = as.factor(iter), y = value)) + geom_violin(position = "dodge") + facet_wrap(~variable)
Upvotes: 3
Reputation: 363
Maybe there is a better way but in this kind of situation I usually create a new variable:
set.seed(42)
dat = data.frame(iter = rep(1:3, each = 10),
variable = rep(rep(letters[1:2], each = 5), 3),
value = rnorm(30))
dat <- dat %>% mutate(x_axis = as.factor(as.numeric(factor(variable))*100 + 10*iter))
levels(dat$x_axis)<- c("a1", "a", "a3", "b2", "b", "b3")
ggplot(data = dat,
aes(x = x_axis,
y = value, fill =variable)) + geom_violin() + scale_x_discrete(breaks = c("a","b"))
Result is:
Upvotes: 1