我想用
ggplot
时间序列和矩形制作动画。
我的实际代码如下:
library(ggplot2)
library(gganimate)
df <- data.frame(
x = c(1,2,3,4,5,6,7,8,9,10),
y = c(4,5,6,7,6,5,4,5,6,7)
)
p <- ggplot()+
geom_line(data=df,aes(x=x,y=y))+
geom_rect(aes(xmin=5,xmax=7,ymin=-Inf,ymax=+Inf),alpha=0.1)+
transition_reveal(x)+
theme_minimal()
animate(p,fps=20,renderer=gifski_renderer(file="test"))
我得到了这个结果:
但是,我希望当时间序列到达时出现矩形。我希望矩形随着时间序列而增加。我不希望矩形立即出现。
这个问题可以用
gganimate
解决吗?
不能 100% 确定您想要的结果,但这是一种使用过滤数据集和多个矩形的可能方法:
library(ggplot2)
library(gganimate)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_line() +
geom_rect(
data = ~ subset(., x >= 5),
aes(xmin = x, xmax = x + 1, ymin = -Inf, ymax = +Inf, group = x),
alpha = 0.1
) +
transition_reveal(x) +
theme_minimal()
p
#> `geom_line()`: Each group consists of only one observation.
#> ℹ Do you need to adjust the group aesthetic?
#> `geom_line()`: Each group consists of only one observation.
#> ℹ Do you need to adjust the group aesthetic?
#animate(p, fps = 20, renderer = gifski_renderer(file = "test"))
或者为了更平滑的过渡,您可以为矩形使用单独的数据框,如下所示:
width <- .05
df_rect <- data.frame(
x = seq(5, 10, width),
y = NA_real_
)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_line() +
geom_rect(
data = df_rect,
aes(xmin = x, xmax = x + width, ymin = -Inf, ymax = +Inf, group = x),
alpha = 0.1
) +
transition_reveal(x) +
theme_minimal()
p
#> `geom_line()`: Each group consists of only one observation.
#> ℹ Do you need to adjust the group aesthetic?
#> `geom_line()`: Each group consists of only one observation.
#> ℹ Do you need to adjust the group aesthetic?