Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ggplot2's geom_dotplot() with both fill and group

Tags:

r

ggplot2

I really like the way the ggplot2::geom_dotplot() can nicely stack dots towards the middle of a category but I cannot seem to combine that with a fill color.

Lets take a look at an example:

# test data
tmpData <- data.frame(x=c(rep('x', 3),rep('y', 3)), y=c(1,1,2,1,2,2), fill=rep(c('A', 'B', 'B'), 2))

# Plot without fill color
ggplot(tmpData, aes(x=x, y=y)) + 
    geom_dotplot(binaxis = "y", stackdir = "center", dotsize=4)

Resulting in this plot:

Dotplot without color

But when I add the fill argument:

ggplot(tmpData, aes(x=x, y=y, fill=fill)) +   
   geom_dotplot(binaxis = "y", stackdir = "center", dotsize=4)

The fill seems to overwrites the grouping done on "x" causing the two points (x, 1)(x, 1) to be collapsed I would like them to have different colors.

Dotplot with color

When I try to specify the group the fill color is ignored:

ggplot(tmpData, aes(x=x, y=y, group=x, fill=fill)) +
    geom_dotplot(binaxis = "y", stackdir = "center", dotsize=4)

Dotplot with group specified

The collapsing seems to be avoidable by enabling stackgroups:

ggplot(tmpData, aes(x=x, y=y, fill=fill)) +
    geom_dotplot(binaxis = "y", stackgroups=TRUE, stackdir = "center", dotsize=4)

dotpoot with stackgroups

But then I lose the centering of the data to the "x" and "y" that are found in the other 3 plots.

Is there a way to use geom_dotplot() with both groups and fill?

like image 481
Kristoffer Vitting-Seerup Avatar asked Jul 22 '15 08:07

Kristoffer Vitting-Seerup


2 Answers

If you're open to a bit of a hacky solution just to get it how you want it to look... You can overwrite the fill command by simply providing it with a vector of color names:

tmpData$colorname <- rep(c('red','blue','blue'),2)

ggplot(tmpData, aes(x=x, y=y)) + 
  geom_dotplot(binaxis = "y", stackdir = "center", dotsize=4, fill=tmpData$colorname)

enter image description here

like image 91
jalapic Avatar answered Oct 13 '22 18:10

jalapic


I think you have to add the argument position = "dodge":

 ggplot(tmpData, aes(x = x, y = y, fill = fill,)) +
  geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 4, position = "dodge")

enter image description here

like image 38
mpalanco Avatar answered Oct 13 '22 18:10

mpalanco