简体   繁体   中英

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:

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':

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) . Nothing after the return(p) will run because the function will return immediately upon hitting that function.

The problem is that your call to ggsave() is wrong. 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)

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