Reputation: 129
In ggplot2, geom_point defaults to plotting over the current plot. For example, calling geom_point after a call to geom_boxplot results in the points plotted over the boxplot:
ggplot(iris, aes(x = "All", y = Sepal.Length)) +
geom_boxplot() +
geom_point(aes(color=Species), position = "jitter")
Is there a way to plot the points separately to the side, rather than over the boxplot?
In my particular case I want to do this because the points obscure the plot (even with transparency, etc), a problem that is not an issue with the example dataset here.
Upvotes: 3
Views: 1889
Reputation: 93811
You can plot them separately by supplying separate x-values for the boxplot and the points:
ggplot(iris, aes(y = Sepal.Length)) +
geom_boxplot(aes(x="Boxplot")) +
geom_point(aes(x="Points", color=Species),
position = position_jitter(width=0.15, height=0))
Another option is to use boxplots by species:
ggplot(iris, aes(y = Sepal.Length)) +
geom_boxplot(aes(x="All Data"), width=0.5) +
geom_boxplot(aes(x="By Species", colour=Species), width=0.5,
position=position_dodge(width=0.6))
Here's what the two plots look like:
Upvotes: 5