How to change the x axis scale limits to adjust itself depending on the max value of each group in ggplot2, for R?

Advertisements

Here is some randomly generated sample data:

[Data Info: The number of customers that visit a particular shop per day, across different branches]

library(tidyverse)
library(ggplot2)

make_skewed_data <- function(n = 20){
  round(rlnorm(n = n, meanlog = 0.3, sdlog = 0.5)*1000, 0)
}

num_customers <- 
  c(make_skewed_data(50), make_skewed_data(50), make_skewed_data(50),
    make_skewed_data(50), make_skewed_data(50), make_skewed_data(50))

DF <- tibble(day = paste0("day", seq(1:50)) %>% rep(6),
             branch = paste0("branch", rep(seq(1:6), each = 50)),
             num_customers = num_customers)

# > DF
# # A tibble: 300 × 3
#    day   branch  num_customers
#  <chr> <chr>           <dbl>
# 1 day1  branch1          1097
# 2 day2  branch1          1658
# 3 day3  branch1          1372
# 4 day4  branch1          1448
# 5 day5  branch1          1501
# 6 day6  branch1          2036
# 7 day7  branch1          2599
# 8 day8  branch1          1049
# 9 day9  branch1          1142
# 10 day10 branch1          1105
# # … with 290 more rows

The below code produces a collection of historgrams using facet_wrap.

DF %>%
  ggplot(aes(x = num_customers)) +
  geom_histogram(bins = 40) +
  theme_bw() +
  facet_wrap(~branch) 

Currently

  • At the moment the scale limits for the x axis is the same for each histogram

Desired solution

  • I would like to reproduce the same ggplot, but I would like the scale limits for the x axis to range from 0 to n (where n is the maximum value for each group of values by branch)

Tried

  • I’m currently aware that the scale_x_continuous(limits = c(min, max)) can be used
  • But the issue is that whatever min/max number I enter will be reflected across all the histograms
  • I want each histogram have different limits

Any help is appreciated 🙂

>Solution :

You can use scales = "free_x" in the facet_wrap function to let scales vary per plot, which should give you what you want:

DF %>%
    ggplot(aes(x = num_customers)) +
    geom_histogram(bins = 40) +
    theme_bw() +
    facet_wrap(~branch, scales = "free_x") 

Leave a ReplyCancel reply