我的设置:
我有一些篮球运动员及其统计资料。
library(tidyverse)
df <- tibble(
season = c(2010, 2011, 2012, 2013, 2014,
2010, 2011, 2012, 2013, 2014),
player = c("player_a", "player_a", "player_a", "player_a", "player_a",
"league_avg", "league_avg", "league_avg", "league_avg", "league_avg"),
fg_perc = c(.4912, .6083, .3095, .5525, .4289,
.4825, .4836, .4819, .4860, .4848),
points_game = c(20, 18, 15, 19, 18,
12, 12, 13, 11, 12)
)
我已经为player_a和League_avg显示了特定的列(fg_perc)作为geom_line()。我还将它包装在一个自定义函数中,因为我将对其他统计信息使用相同的方法。
make_chart <- function(target_column) {
df %>%
ggplot(aes_string("season", target_column, label = target_column)) +
geom_line(aes(color = player), size = 1.33)
}
make_chart("fg_perc")
我的问题:
我只想将fg_perc值显示为player_a数据的百分比。我无法弄清楚如何消除不了图例(当我传播()League_avg时)。我正在寻找一种解决方案,该解决方案还能够按原样保留非百分比数字,并以类似的方式显示它们(例如,points_game仅适用于player_a)。输出看起来像这样(请原谅MS Paint):
谢谢!
最佳答案
如果要使用make_chart
函数而不进行硬编码,则需要使用非标准评估(nse)。许多tidyverse
函数具有nse版本,在函数名称后用_
表示。如果您以编程方式使用它们,则可以使用这些版本。
下面是使用aes
和filter
,aes_
和filter_
的nse版本的粗略示例。使用nse构建功能比我在这里所做的要多得多。我建议您阅读dplyr vignette on nse以获得更多信息。
我只是用filter_
而不是ifelse
复制了提供的@OmaymaS解决方案。我还随意在函数中添加数据参数.data
和player_highlight
参数。 .data
允许您的功能是可移植的,而player_highight
则允许您选择要突出显示的播放器(因为它们可能不止一个)。您很可能想扩展功能,应该这样做!
library(tidyverse)
df <- data_frame(
season = c(2010, 2011, 2012, 2013, 2014,
2010, 2011, 2012, 2013, 2014),
player = c("player_a", "player_a", "player_a", "player_a", "player_a",
"league_avg", "league_avg", "league_avg", "league_avg", "league_avg"),
fg_perc = c(.4912, .6083, .3095, .5525, .4289,
.4825, .4836, .4819, .4860, .4848),
points_game = c(20, 18, 15, 19, 18,
12, 12, 13, 11, 12)
)
make_chart <- function(.data, target_column, player_highlight) {
ggplot(.data, aes_(x = ~season, y = as.name(target_column))) +
geom_line(aes_(color = ~player), size = 1.33) +
geom_text(data = filter_(.data, ~ player == player_highlight), aes_(label = as.name(target_column)))
}
make_chart(df,"fg_perc","player_a")
df %>%
make_chart("fg_perc","player_a")