naught101
naught101

Reputation: 19563

Spread points evenly horizontally in ggplot2

I want to draw vertical boxplots of counts, and show the counts as points, overlaid over the boxplots. Because they are discrete values, there are going to be multiple points with the same value. To show the data in ggplot2, I could use geom_jitter() to spread the data and get a slightly better impression, but jitter screws up the values (the vertical component), and the randomness of the horizontal spread means that if the jitter height is set to 0, there is still a high chance of overlapping points.

Is there a way to spread all points which have the same value, evenly and horizontally? Something along the lines of this:

enter image description here

Here is some example data:

wine_votes <- melt(list(a=c(7,7,7,8,8,7,7,8,4,7,7,6,8,6),
                        b=c(5,8,6,4,3,4,4,9,5,8,4,5,4),
                        c=c(7.5,8,5,8,6,8,5,6,6.5,7,5,5,6),
                        d=c(4,4,5,5,6,8,5,8,5,6,3,6,5),
                        e=c(7,4,6,7,4,6,7,5,6.5,8.5,8,5)
                        ))
names(wine_votes) <- c('vote', 'option')

# Example plot with jitter:
ggplot(wine_votes, aes(x=blend, y=vote)) +
  geom_boxplot() + geom_jitter(position=position_jitter(height=0, width=0.2)) +
  scale_y_continuous(breaks=seq(0,10,2))

enter image description here

Upvotes: 3

Views: 6817

Answers (1)

Tyler Rinker
Tyler Rinker

Reputation: 109964

While this isn't exactly what the image looks like it can be adjusted to get there. geom_dotplot (added in version 0.9.0-ish I think) does this:

ggplot(wine_votes, aes(x=option, y=vote)) +
  geom_boxplot() +   
  scale_y_continuous(breaks=seq(0,10,2)) +
  geom_dotplot(binaxis = "y", stackdir = "center", aes(fill=option))

enter image description here

Upvotes: 8

Related Questions