对于篮球数据集,我正在尝试使用y轴上的EPV度量和x轴上的时间构建线形图的动画。我可以使它起作用,但是现在我想在出现任何event
的特定时间点添加文本标签。 event
是指篮球比赛中某项动作(如控球,运球或传球)发生的时间。这是我到目前为止的内容:
library(tidyverse)
library(gganimate)
library(ggrepel)
theme_set(theme_minimal())
epv_curve_228 <- read_csv("https://raw.githubusercontent.com/jasonbaik94/stackoverflow-data/master/epv_curve_228.csv")
epv_curve_228 %>%
ggplot() +
geom_path(aes(x = 720 - game_clock, y = epv.smooth)) +
# Add description of event for home players
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = h1_event), force = 5) +
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = h2_event), force = 5) +
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = h3_event), force = 5) +
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = h4_event), force = 5) +
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = h5_event), force = 5) +
# Add description of event for away players
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = a1_event), force = 5) +
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = a2_event), force = 5) +
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = a3_event), force = 5) +
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = a4_event), force = 5) +
geom_label_repel(aes(x = 720 - game_clock, y = epv.smooth, label = a5_event), force = 5) +
transition_reveal(720 - game_clock) +
labs(x = "Time (Seconds)",
y = "EPV",
title = "Possession #228 EPV")
问题是不是所有的文本标签(诸如Dribble,Possession等事件)都会出现。我知道可以通过将NA替换为“”来消除NA标签。我不确定如何显示与所有事件关联的所有文本标签。我看到至少4个不同的event
值
答案 0 :(得分:0)
这是一种方法。我发现合并事件,然后填充以下几行(在本例中为5,以与100帧和约500行对齐)很有用,以避免丢失可能在动画的帧之间发生的事件。
epv_curve_228_excerpt <- epv_curve_228 %>%
select(game_clock, epv.smooth, ends_with("event")) %>%
unite(event, a1_event:h5_event) %>%
mutate(event = str_remove_all(event, "NA|_")) %>%
# Add event to a few following time stamps so we don't miss any in our frames
mutate(event_count = cumsum(event != "")) %>%
group_by(event_count) %>%
mutate(event_fill = if_else(row_number() <= 5, first(event), "")) %>%
ungroup()
a <- ggplot(epv_curve_228_excerpt,
aes(x = 720 - game_clock,
y = epv.smooth,
label = event_fill)) +
geom_path() +
geom_label_repel(nudge_x = -1, size = 5) +
transition_reveal(720 - game_clock) +
shadow_wake(wake_length = 0.5, alpha = 0.7, size = 3,
exclude_layer = 1)
animate(a, nframes = 100, width = 600, height = 250)