0

Suppose you have the following code:

grid.arrange(
  ggplot(data[data$Year = 2018,], aes(x = Var1, y = Var2))+
    geom_violin()+
    geom_jitter()+
    ggtitle("2018"),
  ggplot(data[data$Year = 2019,], aes(x = Var1, y = Var2))+
    geom_violin()+
    geom_jitter()+
    ggtitle("2019"), ncol = 2)

This will produce a side-by-side combined violin and jittered scatterplot of Var1 and Var 2 at two timepoints (2018 and 2019). However, it can happen that the y-axis range will not be the same in 2018 and 2019, which is bad for visual comparison of the data. Therefore, we can add the following line:

+scale_y_continuous(limits = c(1, 5))

to both ggplot object in the grid.arrange function in order to constrain the y-axes to be the same on both plots (1 is the minimum possible result on the scale and 5 is the maximum).

However, the usage of geom_jitter() resulted in some points exceeding the y-axis limits of 1 and 5. Is it possible to somehow see what is the scale range that ggplot has internally produced and to manually set the scale limits to these values on both plots?

I have found this answer, but I do not want to first save the plot in an object and then pull the information from that object and modify the plot. I want to produce a clean plot as described above with no intermediate saved objects. Is it possible to do so?

J. Doe
  • 1,544
  • 1
  • 11
  • 26
  • 2
    why don't you use `facet_wrap()`instead of `grid.arrange()` and two plots? – Humpelstielzchen May 27 '19 at 11:35
  • See this. https://stackoverflow.com/questions/48032561/keep-points-above-zero-in-geom-jitter – bbiasi May 27 '19 at 11:58
  • The facet_* functions do the trick in about one-third the amount of code, for arbitrary years. Your example doesn't work anyway because of the wrong expression "data$Year = 2018" – musbur May 27 '19 at 12:09

1 Answers1

0
ggplot(data, aes(x=Var1, y=Var2)) +
    geom_violin() +
    geom_jitter() +
    facet_grid(.~Year)

Try Year~. if the plots come out stacked. I keep forgetting the proper order. You may have to turn Year into a factor beforehand.

musbur
  • 567
  • 4
  • 16
  • Thanks! This works, I usually avoided `facet_grid` because the syntax was confusing as compared to `grid.arrange`, but I see this was the only option here! – J. Doe May 29 '19 at 09:24