在多个 ggplots 中设置比例参数

Set a parameter for scale in multiple ggplots

我可以很容易地设置一个可以重复使用多次的因子水平参数,如下例所示:

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

我也可以用 ggplot 刻度来做这个吗?我想设置 scale_y_continuous(scale_y_parameter) 以便 scale_y_continuous 参数可以在一系列绘图中轻松更新。

此代码有效:

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

这是我想使用的代码,但不知道如何设置参数:

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)

非常感谢任何帮助。

将参数存储在列表中,然后您可以硬编码将参数写入函数:

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)

或使用do.call将参数列表应用于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)

都给: