1

I'd like to create custom labels for each axis in the following plot. Each facet has a different number of breaks. Instead of visually counting the breaks, I'd like to call a function that provides the lengths of each facet break. I know the axTicks function in the scales package provides this for base R plots. Is there something for ggplots? Here is the actual plot I'm working with and then some code to reproduce something similar.

enter image description here

require(tidyverse)
require(scales)

vary_1 <- c(
  exp(rnorm(250,5,1)),
  rnorm(250,10,10),
  exp(rnorm(250,20,1)),
  exp(rnorm(250,30,1)))


  vary_2 <- c(
      rep('A',250),
      rep('B',250),
      rep('C',250),
      rep('D',250))

  data_frame(vary_1,vary_2) %>% 
      ggplot(aes(vary_1,color = vary_2,fill = vary_2))+
      geom_density()+
      facet_wrap(~vary_2,scales = 'free')

axTicks(side = 2)
[1] 0.0 0.2 0.4 0.6 0.8 1.0 # not the correct answer
elliot
  • 1,844
  • 16
  • 45

1 Answers1

1

See if this solves your problem.

p <- data_frame(vary_1,vary_2) %>% 
  ggplot(aes(vary_1,color = vary_2,fill = vary_2))+
  geom_density()+
  facet_wrap(~vary_2,scales = 'free')

q <- layer_data(p)
q %>%
  group_by(PANEL) %>%
  summarise_at(vars(x), funs(min, max))

# # A tibble: 4 x 3
#   PANEL      min     max
#   <fct>    <dbl>   <dbl>
# 1 1      9.95e 0 2.74e 3
# 2 2     -2.10e 1 4.42e 1
# 3 3      3.24e 7 7.95e 9
# 4 4      7.42e11 1.45e14

For more information, see this post.

hpesoj626
  • 3,529
  • 1
  • 17
  • 25
  • 1
    That works perfectly. It seems `ggplot` has both `layer_data()` and `layer_scale()` to grab data from a plot. – elliot May 01 '18 at 09:59