将ggsave纳入R函数

时间:2018-07-17 19:24:50

标签: r ggplot2

我有以下示例数据:

df <- tibble(
  "PLAYER" = c("Corey Kluber", "CLayton Kershaw", "Max Scherzer", "Chris Sale",
       "Corey Kluber", "Jake Arrieta", "Jose Urena", "Yu Darvish"),
  "YEAR" = c(2016, 2016, 2016, 2016, 2017, 2017, 2017, 2017),
  "WHIP" = c(1.24, 1.50, 1.70, 1.35, 1.42, 1.33, 1.61, 1.10),
  "ERA" =  c(3.27, 4.0, 2.56, 1.45, 3.87, 4.23, 3.92, 2.0)
  )

我希望下面编写的函数还保存ggplot,最后使用ggsave

baseball_stats <- function(player, statistic) {

  # Libraries
  library(tidyverse)
  library(rvest)
  library(ggrepel)

  # Function to set YEAR scale to number of seasons played by pitcher
  f <- function(k) {
    step <- k
    function(y) seq(floor(min(y)), ceiling(max(y)), by = step)
  }

  # ggplot of player and chosen statistic
  p <- df %>% 
    group_by(PLAYER) %>% 
    filter(PLAYER == player) %>% 
    ggplot() +
    geom_col(aes_string("YEAR", statistic), width = .5) +
    scale_x_continuous(breaks = f(1)) +  # Uses the function to set YEAR breaks
    scale_y_continuous(breaks = f(0.5)) +
    theme_bw() +
    coord_flip() +
    labs(
      title = player,
      subtitle = statistic,
      x = "Year",
      y = statistic,
    caption = "Data from espn.com")

  return(p)

  # ggsave (before or after return()?)
  ggsave(p, file = "/Documents/sports-analysis/MLB/plots-mlb/", player, ".png", 
      device = "png",
      width = 10,
      height = 7)
}
baseball_stats("Corey Kluber", "WHIP)

该函数在被调用时,将return(p)放在ggsave之后会产生错误:

Error in to_inches(dim) * scale : non-numeric argument to binary 
operator Called from: plot_dim(c(width, height), scale = scale, units = units, 
limitsize = limitsize)

1 个答案:

答案 0 :(得分:1)

ggsave必须在return(p)之前。 return(p)之后什么也不会运行,因为该函数在点击该函数后会立即返回。

问题是您对ggsave()的呼叫是错误的。您需要将文件名作为单个参数传递。您似乎通过在各部分之间放置逗号将其拆分为不同的参数,但实际上并没有将那些部分合并为一个文件名。试试

ggsave(p, file = paste0("/Documents/sports-analysis/MLB/plots-mlb/", player, ".png"), 
  device = "png",
  width = 10,
  height = 7)