Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use color in a geom_dotplot?

Tags:

r

ggplot2

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?

like image 976
Tom Crockett Avatar asked Aug 01 '17 18:08

Tom Crockett


People also ask

What is Binaxis R?

binaxis. The axis to bin along, "x" (default) or "y" method. "dotdensity" (default) for dot-density binning, or "histodot" for fixed bin widths (like stat_bin) binpositions.

What is Mean_sdl?

Add mean and standard deviation The function mean_sdl is used. mean_sdl computes the mean plus or minus a constant times the standard deviation. In the R code below, the constant is specified using the argument mult (mult = 1). By default mult = 2.

How do you make a dot plot in R?

There are two methods you can use to create a stacked dot plot in R: Method 1: The stripchart() function in base R. Method 2: The geom_dotplot() function in ggplot2. This tutorial provides a brief example of how to use each of these methods to produce a stacked dot plot.

What package is Dotplot in R?

dotplot is an easy to use function for making a dot plot with R statistical software using ggplot2 package.


2 Answers

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

like image 198
aosmith Avatar answered Sep 21 '22 16:09

aosmith


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

like image 41
Mako212 Avatar answered Sep 20 '22 16:09

Mako212