ggplot2 change axis limits for each individual facet panel

library(tidyverse)
ggplot(mpg, aes(displ, cty)) + 
  geom_point() + 
  facet_grid(rows = vars(drv), scales = "free")

The ggplot code above consists of three panels 4, f, and r. I’d like the y-axis limits to be the following for each panel:

Panel y-min y-max breaks
----- ----- ----- ------
4     5     25    5
f     0     40    10
r     10    20    2

How do I modify my code to accomplish this? Not sure if scale_y_continuous makes more sense or coord_cartesian, or some combination of the two.

5

This is a long-standing feature request (see, e.g., 2009, 2011, 2016) which is tackled by a separate package facetscales.

devtools::install_github("zeehio/facetscales")
library(g)
library(facetscales)
scales_y <- list(
  `4` = scale_y_continuous(limits = c(5, 25), breaks = seq(5, 25, 5)),
  `f` = scale_y_continuous(limits = c(0, 40), breaks = seq(0, 40, 10)),
  `r` = scale_y_continuous(limits = c(10, 20), breaks = seq(10, 20, 2))
)
ggplot(mpg, aes(displ, cty)) + 
  geom_point() + 
  facet_grid_sc(rows = vars(drv), scales = list(y = scales_y))

If the parameters for each facet are stored in a dataframe facet_params, we can compute on the language to create scale_y:

library(tidyverse)
facet_params <- read_table("drv y_min y_max breaks
4     5     25    5
f     0     40    10
r     10    20    2")

scales_y <- facet_params %>% 
  str_glue_data(
    "`{drv}` = scale_y_continuous(limits = c({y_min}, {y_max}), ", 
                "breaks = seq({y_min}, {y_max}, {breaks}))") %>%
  str_flatten(", ") %>% 
  str_c("list(", ., ")") %>% 
  parse(text = .) %>% 
  eval()

6

preliminaries

Define original plot and desired parameters for the y-axes of each facet:

library(ggplot2)
g0 <- ggplot(mpg, aes(displ, cty)) + 
    geom_point() + 
    facet_grid(rows = vars(drv), scales = "free")

facet_bounds <- read.table(header=TRUE,
text=                           
"drv ymin ymax breaks
4     5     25    5
f     0     40    10
r     10    20    2",
stringsAsFactors=FALSE)

version 1: put in fake data points

This doesn’t respect the breaks specification, but it gets the bounds right:

Define a new data frame that includes the min/max values for each drv:

ff <- with(facet_bounds,
           data.frame(cty=c(ymin,ymax),
                      drv=c(drv,drv)))

Add these to the plots (they won’t be plotted since x is NA, but they’re still used in defining the scales)

g0 + geom_point(data=ff,x=NA)

This is similar to what expand_limits() does, except that that function applies “for all panels or all plots”.

version 2: detect which panel you’re in

This is ugly and depends on each group having a unique range.

library(dplyr)
## compute limits for each group
lims <- (mpg
    %>% group_by(drv)
    %>% summarise(ymin=min(cty),ymax=max(cty))
)

Breaks function: figures out which group corresponds to the set of limits it’s been given …

bfun <- function(limits) {
    grp <- which(lims$ymin==limits[1] & lims$ymax==limits[2])
    bb <- facet_bounds[grp,]
    pp <- pretty(c(bb$ymin,bb$ymax),n=bb$breaks)
    return(pp)
}
g0 + scale_y_continuous(breaks=bfun, expand=expand_scale(0,0))

The other ugliness here is that we have to set expand_scale(0,0) to make the limits exactly equal to the group limits, which might not be the way you want the plot …

It would be nice if the breaks() function could somehow also be passed some information about which panel is currently being computed …

1

Another more recent option would be to use the ggh4x package which via ggh4x::facetted_pos_scales allows to individually specify the positional scales per panel:

library(ggplot2)
library(ggh4x)

df_scales <- data.frame(
  Panel = c("4", "f", "g"),
  ymin = c(5, 0, 10),
  ymax = c(25, 40, 20),
  n = c(5, 10, 2)
)
df_scales <- split(df_scales, df_scales$Panel)

scales <- lapply(df_scales, function(x) {
  scale_y_continuous(limits = c(x$ymin, x$ymax), n.breaks = x$n)
})

ggplot(mpg, aes(displ, cty)) +
  geom_point() +
  facet_grid(rows = vars(drv), scales = "free") +
  ggh4x::facetted_pos_scales(
    y = scales
  )

Recognized by R Language Collective

1

I wanted to use a log scale with facetscales and struggled.

It turned out I have to specify the log10 at two positions:

scales_x <- list(
  "B" = scale_x_log10(limits=c(0.1, 10), breaks=c(0.1, 1, 10)),
  "C" = scale_x_log10(limits=c(0.008, 1), breaks=c(0.01, 0.1, 1)),
  "E" = scale_x_log10(limits=c(0.01, 1), breaks=c(0.01, 0.1, 1)),
  "R" = scale_x_log10(limits=c(0.01, 1), breaks=c(0.01, 0.1, 1))
)

and in the plot

ggplot(...) + facet_grid_sc(...) +  scale_x_log10()

0

Unfortunately, as far as I can tell (I may be wrong) the above mentioned methods cannot help you if you want to shrink the axis of a facet. For example, here is a figure from my work, with anonymized data:

In two of the facets (right column) the confidence intervals of one or two individual data points wildly shift the domain of the facet, making the general trends in the main body of data difficult to discern. I need to shrink these axes.

I’ve hacked together a function scale_inidividual_facet_y_axes which very roughly accomplishes this. It’s a standalone function which accepts two parameters: plot which is the ggproto object output by ggplot functions, and ylims which is a list of tuples, each corresponding to the y-axis for a particular facet. If you want the axis of a particular facet to remain unmodified, simply use a NULL value for that facet’s element in the ylims list.

For example:

plot = 
  data %>% 
  ggplot(aes(...)) +
  geom_thing() + 
  # ... construct your ggplot object as normal, and save it to a variable
  geom_whatever()

ylims = list(NULL, c(-20, 100), NULL, c(0, 120))

  
scale_inidividual_facet_y_axes(plot, ylims = ylims)

Which produces this:

As you can see the axes of the righthand column facets have been modified, while the left hand facets remain in their original form.

This method has one immediately apparent problem: It occurs before the figures are drawn, so data which fall outside of the new axes will no longer be drawn. You can see this in the righthand facets where the extreme values of the confidence interval ribbons are no longer drawn, as the fall outside of the imposed axis limits.

In the future I may be able to find a method which somehow gets around this, but for now it is what it is.

Function code:

#' Scale individual facet y-axes
#' 
#' 
#' VERY hacky method of imposing facet specific y-axis limits on plots made with facet_wrap
#' Briefly, this function alters an internal function within the ggproto object, a function which is called to find any limits imposed on the axes of the plot. 
#' We wrap that function in a function of our own, one which intercepts the return value and modifies it with the axis limits we've specified the parent call 
#' 
#' I MAKE NO CLAIMS TO THE STABILITY OF THIS FUNCTION
#' 
#'
#' @param plot The ggproto object to be modified
#' @param ylims A list of tuples specifying the y-axis limits of the individual facets of the plot. A NULL value in place of a tuple will indicate that the plot should draw that facet as normal (i.e. no axis modification)
#'
#' @return The original plot, with facet y-axes modified as specified
#' @export
#'
#' @examples 
#' Not intended to be added to a ggproto call list. 
#' This is a standalone function which accepts a ggproto object and modifies it directly, e.g.
#' 
#' YES. GOOD: 
#' ======================================
#' plot = ggplot(data, aes(...)) + 
#'   geom_whatever() + 
#'   geom_thing()
#'   
#' scale_individual_facet_y_axes(plot, ylims)
#' ======================================
#' 
#' NO. BAD:
#' ======================================
#' ggplot(data, aes(...)) + 
#'   geom_whatever() + 
#'   geom_thing() + 
#'   scale_individual_facet_y_axes(ylims)
#' ======================================
#' 
scale_inidividual_facet_y_axes = function(plot, ylims) {
  init_scales_orig = plot$facet$init_scales
  
  init_scales_new = function(...) {
    r = init_scales_orig(...)
    # Extract the Y Scale Limits
    y = r$y
    # If this is not the y axis, then return the original values
    if(is.null(y)) return(r)
    # If these are the y axis limits, then we iterate over them, replacing them as specified by our ylims parameter
    for (i in seq(1, length(y))) {
      ylim = ylims[[i]]
      if(!is.null(ylim)) {
        y[[i]]$limits = ylim
      }
    }
    # Now we reattach the modified Y axis limit list to the original return object
    r$y = y
    return(r)
  }
  
  plot$facet$init_scales = init_scales_new
  
  return(plot)
}

6

I mostly feel the need to set the axis limits if I have excessive errorbars in one condition steal all the space of my plot. If one there are no facets or all facets have the same range one can simply use something like + coord_cartesian(ylim = range(yourdata$your_y_axis_data))
to zoom into relevant part of the plot. (using scale_y_continous(limits= <whatever>) would complete remove the large error bar from the plot ( and using oob=scales::squish` would make them look smaller)

But there is a better way than setting the limits in `coord_*:

Remove the errorbar’s aesthetics from the scale to avoid it beeing used for training:

my_y_scale <- scale_y_continous() ; my_y_scale$aesthetics <- "y"

ggplot(... + my_y_scale 

Full example:

library(ggplot2)

mpg |> ggplot(aes(x=class, y= cty)) +
  geom_point() +
  stat_summary(fun.data = mean_cl_normal, color="red") +
  facet_grid(vars(year), vars(manufacturer), scales="free", space="free") +
  guides(x = guide_axis(angle=90)) + # cosmetic
  NULL

Note, how the error bar of 2008 nissans suv usually extends the y limits to below 0 in above plot but is nicely clipped to the data range in the plot below – without any manual limit specifications.


scale_set_aesthetics <- function(scale, aesthetics) {scale$aesthetics <- aesthetics; scale}

mpg |> ggplot(aes(x=class, y= cty)) +
  geom_point() +
  stat_summary(fun.data = mean_cl_normal, color="red") +
  facet_grid(vars(year), vars(manufacturer), scales="free", space="free") +
  guides(x = guide_axis(angle=90)) + # cosmetic
  scale_set_aesthetics(scale_y_continuous(), "y") + # use only y aesthetic, not ymin and ymax, to train scale
  NULL

(For some reason it does not work the other way around (you cannot prevent that y aesthetics train the scale). Ideally one would be able to exclude a layer from training the scales.)

2

Apparently, the facetscales package is no longer maintained. The package maintainer suggested to use the patchwork library instead.

Solution with patchwork:

library(patchwork)

p1 <- mpg |> 
  filter(drv == "4") |> 
  ggplot(aes(displ, cty)) + 
  geom_point() + 
  facet_grid(drv ~ .) +
  scale_y_continuous(limits = c(5, 25), breaks = seq(5, 25, by=5)) +
  theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank()) +
  ylab("")

p2 <- mpg |> 
  filter(drv == "f") |> 
  ggplot(aes(displ, cty)) + 
  geom_point() + 
  facet_grid(drv ~ .) +
  scale_y_continuous(limits = c(0, 40), breaks = seq(0, 40, by=10)) +
  theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())

p3 <- mpg |> 
  filter(drv == "r") |> 
  ggplot(aes(displ, cty)) + 
  geom_point() + 
  facet_grid(drv ~ .) +
  scale_y_continuous(limits = c(10, 20), breaks = seq(10, 20, by=2)) +
  ylab("")

p1 / p2 / p3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật