样本数据:
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
输出一个图:
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(YEAR, statistic), width = .5) +
scale_x_continuous(breaks = f(1)) + # Uses the function to set YEAR breaks
scale_y_continuous(breaks = f(0.1)) +
theme_bw() +
coord_flip() +
labs(
title = "statistic Statistic: player",
subtitle = "statistic over seasons played",
x = "Year",
y = "statistic Stat",
caption = "Data from espn.com")
print(p)
return(baseball_stats)
}
baseball_stats("Corey Kluber", WHIP)
我得到了Error: Discrete value supplied to continuous scale
或关于$
和原子向量的另一个错误(我的数据集是用rvest
抓取的,我必须清理它,然后尝试将其包括在我的功能)。谢谢
答案 0 :(得分:1)
将aes
更改为aes_string
后我得到了一个情节
geom_col(aes_string("YEAR", statistic), width = .5)
请注意,YEAR
位于quot。我将其称为以下命令
baseball_stats("Corey Kluber", "WHIP")
同样将WHIP
传入quot。
完整的代码在这里:
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.1)) +
theme_bw() +
coord_flip() +
labs(
title = "statistic Statistic: player",
subtitle = "statistic over seasons played",
x = "Year",
y = "statistic Stat",
caption = "Data from espn.com")
print(p)
return(baseball_stats)
}
baseball_stats("Corey Kluber", "WHIP")