3

I want to graph a distribution along two dimensions using a violinplot with a boxplot in it. The result can be really fascinating, but only when done right.

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
head(ToothGrowth)
plot <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=supp)) +
  geom_violin() + geom_boxplot(width=0.1)  + theme(legend.position="none")
ggsave(filename="Violinboxplot.png", plot, height=6, width=4)

This is however what I get:

enter image description here

The boxplots are aligned along the axis belonging to the factor. How can I shift them to be in the center of the violinplots?

MERose
  • 4,048
  • 7
  • 53
  • 79

1 Answers1

3

There is an answer to this question here: how to align violin plots with boxplots

You can use the position argument to shift the graph elements as needed:

dodge <- position_dodge(width = 0.5)

ggplot(ToothGrowth, aes(x=dose, y=len, fill=supp)) +
  geom_violin(position = dodge) +
  geom_boxplot(width=.1, position = dodge) +
  theme(legend.position="none")
Community
  • 1
  • 1
tsurudak
  • 602
  • 7
  • 14