问题描述
我想将某些数据设置为一条黑线,并用两条静态红线作为边界。静态线是UP和DOWN。我的动画数据是y,时间轴是x。
我做了很多尝试-使用transition_components()
和transition_layers()
-但是没有用...但是也许我的代码中有一些错误,我不确定...如何为行分配颜色我发现Changing line colors with ggplot(),但处理不当...
我必须完成的gganimate代码:
# load the needed packages
library(gifski)
library(ggplot2)
library(gganimate)
theme_set(theme_bw())
# add the time vector x
### 10.1 seconds with timestep 0.1 seconds
x=rep(seq(from=0,to=10,by=0.1),times=3)
# y should be the line in the plot which should be animated
y=c(seq(from=0,length.out=which(round(x,1)==2)[1]),rep(10,times=which(round(x,1)==5)[1]-which(round(x,10*0.95^(seq(from=1,by=1,length.out=50)))
# UP and DOWN should be static lines in the animated plot
### there shouldn't be a "linemoving" from left to rigth side of the plot
UP=c(seq(from=1,to=12,1)==1.8)[1]),rep(12,1)==5.5)[1]-which(round(x,seq(from=12,to=4,length.out=length(seq(from=0,by=0.1))-which(round(x,1)==1.8)[1]-(which(round(x,1)==1.8)[1]))
)
DOWN=c(seq(from=0,to=8,1)==2.2)[1]),rep(8,1)==4.5)[1]-which(round(x,seq(from=8,to=1,1)==2.2)[1]-(which(round(x,1)==2.2)[1]))
)
value=c(y,UP,DOWN)
h=length(seq(from=0,by=0.1))
variable=c(rep("y",h),rep("UP",rep("DOWN",h) )
# the dataframe with the three columns
df=data.frame(x,variable,value)
p=ggplot(df,aes(x=x,y=value,group=variable,colour=variable ) ) + geom_line(size=2) + scale_color_manual(values=c("black","red","red")) # I want that y is a black line and UP and DOWN are red lines
# x is my time variable in the dataframe
p2=p + transition_reveal(x)
# animating p2
animate(p2)
完成的图应该像这张图片
对我来说,这里出现了一些问题:
- 我如何才能实现只有黑线(y矢量)具有动画效果并且两条黑线(上和下)保持静态
- 以正确的方式为线条分配颜色
- 我的gif保存在哪里
- 是否需要从时间轴x的开头定义我的所有行?或者有可能在x [10] = 0.9秒时启动UP向量。
解决方法
问题1最棘手。您需要组织数据,以使两条静态线的x值具有不同的名称(例如static_x
),并且没有任何实际的x
值。将df分为两个不同的帧可能最容易做到这一点:
df_y <- df[variable == "y",]
df_not_y <- df[variable != "y",]
df_not_y$static_x <- df_not_y$x
df_not_y <- df_not_y[names(df_not_y) != "x"]
然后,为处理问题4,我们将在1秒前删除变量UP
的所有值:
df_not_y$value[df_not_y$static_x < 1 & df_not_y$variable == "UP"] <- NA
现在我们可以绘图。我们需要两个 geom_line
调用,一个调用静态变量,另一个调用移动变量。为回答问题2,我们在scale_color_manual
中按名称分配颜色,以确保级别正确。
p <- ggplot(df_y,aes(x = x,y = value,colour = variable)) +
geom_line(aes(x = static_x),data = df_not_y,size = 2) +
geom_line(size = 2) +
scale_color_manual(values = c(UP = "red",y = "black",DOWN = "red"))
p2 <- p + transition_reveal(x)
animate(p2)
剩下问题3。在这种情况下,我只需在查看器面板上单击鼠标右键,然后选择“保存图像”,但是如果发现更方便的话,也可以执行gganimate::anim_save("mygif.gif",last_animation())
。