Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

PLOT IMAGE

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") 

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading