简体   繁体   中英

Set a parameter for scale in multiple ggplots

I can easily set a parameter for factor levels that can be reused multiple times as in the example below:

am_labels_parameter <- c("auto", "manual")

d <- 
  mtcars %>% 
  mutate(
    cyl = as.factor(cyl), 
    am = factor(am, labels = am_labels_parameter)
  ) %>% 
  group_by(cyl, am) %>% 
  summarise(mpg = mean(mpg)) 

Can I also do this with the a ggplot scale? I would like to set scale_y_continuous(scale_y_parameter) so that the scale_y_continuous parameters could be easily updated across a series of plots.

This code works:

d %>% 
  ggplot(aes(x = cyl, y = mpg, fill = am)) + 
  geom_col(position = "dodge") + 
  scale_y_continuous(
    breaks = seq(0, 30, by = 10),
    limits = c(0, 30)
    )

This is the code I'd like to work, but don't know how to set the parameter:

scale_y_parameter <- 
    c(breaks = seq(0, 30, by = 10),
    limits = c(0, 30))

d %>% 
  ggplot(aes(x = cyl, y = mpg, fill = am)) + 
  geom_col(position = "dodge") + 
  scale_y_continuous(scale_y_parameter)

Any help is greatly appreciated.

Store the parameters in a list, then you can either hard coding the parameters into the function:

scale_y_parameter <- 
    list(breaks = seq(0, 30, by = 10),
         limits = c(0, 30))

d %>% 
    ggplot(aes(x = cyl, y = mpg, fill = am)) + 
    geom_col(position = "dodge") + 
    scale_y_continuous(breaks = scale_y_parameter$breaks, limits = scale_y_parameter$limits)

Or use do.call to apply the list of parameters to scale_y_continuous :

scale_y_parameter <- 
    list(breaks = seq(0, 30, by = 10),
         limits = c(0, 30))

d %>% 
    ggplot(aes(x = cyl, y = mpg, fill = am)) + 
    geom_col(position = "dodge") + 
    do.call(scale_y_continuous, scale_y_parameter)

both give:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM