Tom Crockett
Tom Crockett

Reputation: 31579

How do I use color in a geom_dotplot?

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?

Upvotes: 6

Views: 6538

Answers (2)

Mako212
Mako212

Reputation: 7292

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

Upvotes: 4

aosmith
aosmith

Reputation: 36076

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

Upvotes: 5

Related Questions