问题描述
是否有R,它可以简化生产彗星情节的任何库或功能?我的意思是一个动画图形,其中头部(箭头)跟踪的粒子的路径,它的主体(线)头后面小径,以正比于粒子的速度的长度。
Are there any libraries or functions in R which would simplify the production of a comet plot? By this I mean an animated graph where the head (an arrow) traces the path of a particle, and it's body (a line) trails behind the head, with a length proportional to the velocity of the particle.
Matlab具有记录在这里一个非常简单的彗星()函数:http://www.mathworks.co.uk/help/matlab/ref/comet.html
Matlab has a very simple comet() function documented here: http://www.mathworks.co.uk/help/matlab/ref/comet.html
显示当前风速彗星情节的一个令人难以置信的很好的例子是在这里:
An incredibly nice example of a comet plot showing current wind speeds is here:http://earth.nullschool.net/
我意识到这是一个非常普遍的问题,但我已经找到R中绝对没有那么远。
I realise this is a very general question, but I have found absolutely nothing in R so far.
推荐答案
这个怎么样用动画
# required libraries
require(animation) # NB you must install ImageMagick
require(ggplot2)
require(grid) # for arrow()
# create a path with variable speed (1 point per time unit)
path<-data.frame(time=1:100,x=1:100,y=c((1:50)^2,(50:1)^2))
# plot it, just to see
ggplot(path)+geom_point(aes(x,y))
# work out the path and previous points of each observation
# average of previous 2 steps, but could be any number
steps<-2
path$prevx<-c(rep(0,steps),path$x[1:(nrow(path)-steps)])
path$prevy<-c(rep(0,steps),path$y[1:(nrow(path)-steps)])
path$prevtime<-c(rep(0,steps),path$time[1:(nrow(path)-steps)])
# then calculate the velocity at each point, and the angle (for the arrow)
# note we could just plot point to point, but that assumes the time units are regular
path$v<-((((path$x-path$prevx)^2)+((path$y-path$prevy)^2))^0.5)/(path$time-path$prevtime)
path$atan2<-atan2((path$x-path$prevx),(path$y-path$prevy))
# OK, we now have all the data; let's plot first without animation
ggplot(path)+geom_segment(aes(x = x-(v*sin(atan2)), y = y-(v*cos(atan2)), xend = x, yend = y),
arrow=arrow(length = unit(0.5, "cm")) ,
alpha=0.5, size=2,
color="blue")
# create function which takes a vector of rows (to plot a subset of arrows)
plot_arrow<-function(vec){
alphas<-rev(1/(1:length(vec))^1.5) # this create an alpha scale
g<-ggplot(path[vec,])+geom_segment(aes(x = x-(v*sin(atan2)), y = y-(v*cos(atan2)), xend = x, yend = y),
arrow=arrow(length = unit(0.5, "cm")) , # create arrow
alpha=alphas, size=2,
color="blue")+
coord_cartesian(xlim=c(min(path$x),max(path$x)),ylim=c(min(path$y),max(path$y))) # fix width
print(g)
}
# then create the animated GIF with 5 arrows per frame
saveGIF({
lapply(1:nrow(path),function(x)plot_arrow(max(1,x-5):x))
},movie.name="comet.gif",interval=0.2)
PS:你也可以去掉尾随箭头,通过改变 plot_arrow()
函数调用如下[在箭头()
拨打'geom_segment']:
PS: you can also remove the trailing arrowheads, by changing the plot_arrow()
function call as follows [the arrow()
call in 'geom_segment']:
arrow=arrow(length = unit(c(rep(0,length(vec)-1),0.5), "cm"))
这篇关于生产R中的动画情节彗星的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!