首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将ggsave合并到R函数中

将ggsave合并到R函数中
EN

Stack Overflow用户
提问于 2018-07-18 03:24:50
回答 0查看 598关注 0票数 0

我有以下示例数据:

代码语言:javascript
复制
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

代码语言:javascript
复制
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’之后时,只会给出一个错误:

代码语言:javascript
复制
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)
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51388863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档