【问题标题】:Set a parameter for scale in multiple ggplots在多个ggplots中设置比例参数
【发布时间】:2017-11-21 18:51:32
【问题描述】:

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

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)

非常感谢任何帮助。

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

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

    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)
    

    两者都给出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      相关资源
      最近更新 更多