我有以下示例数据:
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)https://stackoverflow.com/questions/51388863
复制相似问题