6

I have this dotplot:

ggplot(mpg, aes(drv, hwy)) +
  geom_dotplot(binwidth = 1, binaxis = 'y', stackdir = 'center')

which renders as

enter image description here

I want to color the dots by manufacturer. If I add a fill aesthetic:

ggplot(mpg, aes(drv, hwy, fill = manufacturer)) +
  geom_dotplot(binwidth = 1, binaxis = 'y', stackdir = 'center')

it renders as

enter image description here

It looks like adding color has defeated the stacking algorithm somehow, causing the dots to overlap. How do I fix this?

aosmith
  • 34,856
  • 9
  • 84
  • 118
Tom Crockett
  • 30,818
  • 8
  • 72
  • 90

2 Answers2

5

Using geom_beeswarm from package ggbeeswarm is an option. It doesn't center the even numbered rows of dots quite the same way, but the point color seems to work out better than geom_dotplot.

library(ggbeeswarm)

ggplot(mpg, aes(drv, hwy, color = manufacturer)) +
     geom_beeswarm(size = 2)

enter image description here

aosmith
  • 34,856
  • 9
  • 84
  • 118
  • I wish I could accept both this and Mako212's answer, but I went with theirs because it more literally answered the question of how to add color to a `geom_dotplot`, and the result looks more symmetric. This answer wins for simplicity of use though, and I didn't know about `ggbeeswarm`, so thanks! – Tom Crockett Aug 02 '17 at 04:52
4

This is the closest I've gotten:

ggplot(mpg, aes(drv, hwy, fill = manufacturer)) +
  geom_dotplot(stackdir = "centerwhole",stackgroups = TRUE,
  binpositions = "all", binaxis = "y", binwidth = 1)+
  theme_bw()

enter image description here

If you need everything to be perfectly centered, I'd review this example of writing a for loop to plot three separate charts (one for each factor level), using a shared legend.

Edit:

And here's the chart following the linked process of using a function to combine three plots with the same legend:

enter image description here

Community
  • 1
  • 1
Mako212
  • 6,787
  • 1
  • 18
  • 37
  • Yikes, pretty ugly without the centering. No link for "this example"? – Tom Crockett Aug 01 '17 at 18:49
  • I followed the above template, and it produces your desired result. I'd recommend using @epsilone's modified version of the originally linked `grid_arrange_shared_legend` function that let's you pass `nrow` and `ncol` – Mako212 Aug 01 '17 at 18:59
  • And here's the original implementation from the ggplot devs: https://github.com/tidyverse/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs – Mako212 Aug 01 '17 at 19:02