I have a data set of events with year, gender and some other data. I’d like to draw a dotplot that shows one dot per event
I reproduced the problem with this test data set. Here’s the setup:
library(ggplot2)
gender<-c("f","f","f","f","m","m","m","m","m","m","m")
year<-c(2002, 2005, 2009, 2011, 2015, 2002, 2021, 2009, 2011, 2006,2015)
testdata<-as.data.frame(cbind(gender, year))
And here’s the code I’m having a problem with:
table(testdata$year,testdata$gender)
ggplot(testdata, aes(x=year, fill=gender))+geom_dotplot()
Somehow, even though the table shows all eleven events, just eight are appearing on the dotplot. Whenever a year should have two colors/fills, as in 2009 & 2011, it displays only one. I can tell it’s not a stacking problem because 2015, with 2 instances of one color, appears just fine. Why don’t I see two dots of different colors in 2009 and 2011?
>Solution :
It actually is a stacking problem. The following solves:
ggplot(testdata, aes(x=year, fill = gender)) +
geom_dotplot(position = "dodge")
In 2015 you see two dots of the same color, since the default option for geom_dotplot() is to stack in the upper direction dots from the same group. However, picking 2002 as example, this does not apply since automatically. position = "dodge solves.