1

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.

Con Des
  • 359
  • 1
  • 2
  • 9
  • Can you please add example of wanted output? – pogibas Dec 11 '19 at 08:24
  • by definition, `geom_jitter` plots random position, so you cannot control this. You can maybe get closer from what you want with `p + geom_dotplot(binaxis = "y", stackdir = "center", fill = 'darkred', size = 5, alpha = 1)` ? – Jrm_FRL Dec 11 '19 at 11:56
  • Hi there, I initially tried this with the dotplot but I not able to change the shape with a dotplot so opted for a different strategy. – Con Des Dec 12 '19 at 00:33

1 Answers1

3

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

RoB
  • 1,833
  • 11
  • 23
  • thanks so much, I had never heard of beeswarm. Do you know if any of the arguments can be used to align the points horizontally as well? – Con Des Dec 12 '19 at 00:31
  • @ConDes Yes, you can. Set `groupOnX` to TRUE (the default). There's a bunch of examples on the front page of the repo I linked in my answer if you need more. – RoB Dec 12 '19 at 06:42