简体   繁体   English

将ggsave纳入R函数

[英]Incorporating ggsave into R function

I have this sample data: 我有以下示例数据:

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

I want the function written below to also save the ggplot , using ggsave at the end: 我希望下面编写的函数也可以使用ggsave来保存ggplot

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)

The function, when called, just gives an error when return(p) is placed after the `ggsave': 当调用函数时,将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)

The ggsave must be before return(p) . ggsave必须在return(p)之前。 Nothing after the return(p) will run because the function will return immediately upon hitting that function. return(p)将什么也不会运行,因为该函数在点击该函数后将立即返回。

The problem is that your call to ggsave() is wrong. 问题是您对ggsave()调用是错误的。 You need to pass in the file name as a single parameter. 您需要将文件名作为单个参数传递。 You seem to have split it up into different parameters by placing commas between the parts but didn't actually combine those parts into a single file name. 您似乎通过在各部分之间放置逗号将其拆分为不同的参数,但实际上并没有将那些部分合并为一个文件名。 Try 尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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