1

I want to create a plot using facet_grid(), with free scales for the y axis. However, for each row, the scale breaks should be distributed evenly, that is, with 3 breaks. I lended from this question, but I was not able to adapt the code in a way that the scale breaks are actually pretty.

However, this is my current approach:

# Packages
  library(dplyr)
  library(ggplot2)
  library(scales)


# Test Data
  set.seed(123)

  result_df <- data.frame(
    variable = rep(c(1,2,3,4), each = 4),
    mode     = rep(c(1,2), each = 2),
    treat    = rep(c(1,2)) %>% as.factor(),
    mean     = rnorm(16, mean = .7, sd = 0.2),
    x       = abs(rnorm(16, mean = 0, sd = 0.5))) %>%
    mutate(lower = mean - x,upper = mean + x)

# Function for equal breaks, lended from

  equal_breaks <- function(n = 3, s = 0.05, ...) {
    function(x) {
      d <- s * diff(range(x)) / (1+2*s)
      round(seq(min(x)+d, max(x)-d, length=n), 2)
  }}


  ## Plot

 result_df %>%
   ggplot(aes(y = mean*100, x = treat)) +
   geom_pointrange(aes(ymin = lower*100, ymax = upper*100), shape = 20) +
   facet_grid(variable ~ mode, scales = "free_y")+
   scale_y_continuous(breaks = equal_breaks(n = 3, s = .2))+
   labs(x = "", y = "")

Which leads to this current plot. As one can see, the breaks are far from being reasonable.

Thanks in advance for any kind of recommendation, and please excuse me in case I have missed a already existing solution.

Best, Malte

m_ky
  • 51
  • 6
  • 1
    Have you looked at the function `axisTicks` ? – G5W Apr 29 '19 at 13:53
  • 1
    The `equal_breaks()` function has `digits = 2` hard-coded as the second argument of `round()`. If what you want are breaks that are closer to "round" numbers, change this argument to 0 to get the closest integer. Or if you want the nearest multiple of a larger number, say 10, you could replace `round` with `round_any()`. See here: https://stackoverflow.com/questions/43627679/round-any-equivalent-for-dplyr – qdread Apr 29 '19 at 13:57
  • Also just to point out, it will not be possible to simultaneously have *exactly* equal locations of the breaks and have very few significant figures in the breaks. You will need slightly uneven breaks if you want "round" numbers with few sig figs. – qdread Apr 29 '19 at 14:00

0 Answers0