Search code examples
rggplot2colorsfill

geom_dotplot() loses dodge after applying colour aesthetics


I want to organize my data by one category on the X-axis, but color it by another category as in this example:

Graph 1, without coloring:

require(ggplot2)
nocolor <- ggplot(mtcars, aes(x=as.factor(cyl), y=disp)) + 
  geom_dotplot(binaxis="y", stackdir = "center")
print(nocolor)

enter image description here

Graph 2, with coloring:

nododge <- ggplot(mtcars, aes(x=as.factor(cyl), y=disp, fill=as.factor(gear))) + 
  geom_dotplot(binaxis="y", stackdir = "center")
print(nododge)

enter image description here

One problem that occurs after introducing coloring is that the dots belonging to different groups wont dodge one another anymore. This causes problems with my real data, as I get dots that happen to have the same value and completely obscure one another.

Then I tried this, but it garbled my data:

Graph 3:

garbled <- ggplot(mtcars, aes(x=as.factor(cyl), y=disp)) +
  geom_dotplot(binaxis="y", stackdir = "center", fill=as.factor(mtcars$gear))
print(garbled)

enter image description here

The dots dodge one another, but the the coloring is just random and is not true to the actual data.

I expected the answer to this question to solve my problem, but the coloring remained random:

Graph 4:

graphdata <- mtcars
graphdata$colorname <- as.factor(graphdata$gear) 
levels(graphdata$colorname) <- c("red", "blue", "black")
jalapic <- ggplot(graphdata, aes(x=as.factor(cyl), y=disp)) +
  geom_dotplot(binaxis="y", stackdir = "center", fill=as.character(graphdata$colorname))
print(jalapic)

enter image description here

Does anyone have an idea how to get the dots in Graph #2 to dodge one another, or how to fix the coloring in graphs 3 or 4? I would really appreciate any help, thanks.


Solution

  • Using binpositions = "all" and stackgroups = TRUE:

    ggplot(mtcars, aes(x=as.factor(cyl), y=disp, fill=as.factor(gear))) + 
      geom_dotplot(binaxis="y", stackdir = "center", binpositions="all", stackgroups=TRUE)
    

    gives:

    enter image description here

    A possible alternative is using stackdir = "up":

    ggplot(mtcars, aes(x=as.factor(cyl), y=disp, fill=as.factor(gear))) + 
      geom_dotplot(binaxis="y", stackdir = "up", binpositions="all", stackgroups=TRUE)
    

    which gives:

    enter image description here