Search code examples
rggplot2jitter

Aligning geom_jitter points on x axis and treating y as frequency


This is a slightly odd question but here goes ...

I want to make some plots using geom_jitter where I plot a categorical variable on the x-axis and plot y as individual data points in a straight line. I also want the data points to be vertically aligned across each of the categories on the x-axis.

At the moment I have something like this:

y <- rep(1:5, each = 4)
x <- rep(c("1", "2", "3", "4", "5"), each = 4)
df <- cbind(y, x)
df <- as.data.frame(df)
df$y <- as.numeric(df$y)

p <- ggplot(df, aes(x, y))
p + geom_jitter(shape = 4, color = 'darkred', width = 0, height = 1, size = 5, alpha = 1)

jittered plot

which gives me this plot.

As mentioned I would like the data points to be vertically aligned and equidistant from each other.

Does anyone know if this is possible?

Essentially I want to treat y a little bit like frequency in a dot-plot.

Many thanks!


I forgot to mention that I would also like the points to align horizontally so that the plot appears a little like frequency histogram.


Solution

  • You want to use the ggbeeswarm package for this.

    library(ggplot2)
    library(ggbeeswarm)
    
    y <- rep(1:5, each = 4)
    x <- rep(c("1", "2", "3", "4", "5"), each = 4)
    df <- cbind(y, x)
    df <- as.data.frame(df)
    df$y <- as.numeric(df$y)
    
    p <- ggplot(df, aes(x, y))
    p + geom_beeswarm(shape = 4, color = 'darkred', size = 4,
                      groupOnX = F, # only swarm on Y axis
                      cex = 2) # increase space between points
    

    This plots

    enter image description here