【问题标题】:Smooth passage from one graph to another从一张图平滑过渡到另一张图
【发布时间】:2015-05-23 03:25:36
【问题描述】:

考虑以下两个图表

require(ggplot2)
set.seed(5276)
my_mtcars = mtcars
my_mtcars$rand = rnorm(nrow(mtcars))

ggplot(my_mtcars, aes(rand, mpg)) + geom_point()

ggplot(my_mtcars, aes(wt, mpg)) + geom_point()

我想制作一部电影(或任何可以在 .ppt 中轻松引入的动画图片),它可以从第一个图表顺利过渡到第二个图表。在通过过程中,我们会看到这些点平稳地水平移动以到达目的地。 x 轴刻度和标签也应该出现(最终平滑)。

我会尝试创建许多中间图片的 .png,然后使用 ImageMagick (Bash) 将其制作成 gif,但我很确定应该有更好的解决方案。我使用ggplot2 来制作情节,但我对此并不严格。这是我目前尝试的方法

IntFormat = function(x,nbdigits=0){
  cx = paste0(x)
  l = length(strsplit(cx,"")[[1]])
  if (nbdigits < l){nbdigits = l; print("WARNING: Parameter `nbdigits` too small")}
  before = paste(rep("0",nbdigits-l), collapse="")
  paste0(before, cx)
}

SmoothGraph = function(x1, x2, y1, y2, times = "NOTSET", ...){
    path = "/Users/remi/Desktop/"
    if (times == "NOTSET") {
        times = c(seq(0,0.1,length.out=10), seq(0,0.2, length.out=5), seq(0.2,0.8, length.out=6), seq(0.8,0.9, length.out=5), seq(0.9,1,length.out=10))
    }
    nbdigits = length(times)
    count = 0
    x1_rel = x1 / (max(x1) - min(x1))
    x1_rel = x1_rel - max(x1_rel) + 1
    x2_rel = x2 / (max(x2) - min(x2))
    x2_rel = x2_rel - max(x2_rel) + 1
    y1_rel = y1 / (max(y1) - min(y1)) - min(y1)
    y1_rel = y1_rel - max(y1_rel) + 1
    y2_rel = y2 / (max(y2) - min(y2)) - min(y2)
    y2_rel = y2_rel - max(y2_rel) + 1
    x_diff = x2_rel - x1_rel
    y_diff = y2_rel - y1_rel
    for (time in times){
        count = count + 1
        xtmp = x1_rel + x_diff * time
        ytmp = y1_rel + y_diff * time
        print(count)
        png(paste0(path, "SmoothGraph_", IntFormat(count, nbdigits=nbdigits), ".png"))
        plot(x=xtmp, y=ytmp, ...)
        dev.off()
    }
    system (command="
    cd /Users/remi/Desktop/
    convert SmoothGraph_*.png -delay 1 SmoothGraph.gif
    rm SmoothGraph_*.png
    ")
}

SmoothGraph(x1=rnorm(12), y1=mtcars$mpg , x2 = mtcars$wt, y2=mtcars$mpg)

【问题讨论】:

  • 您是否寻找过动画示例:rforpublichealth.blogspot.com/2014/12/… ?您是否至少尝试过自己实现它?我不清楚 x 轴在过渡期间会是什么样子。
  • @MrFlick 不,我没有尝试过动画。我在答案中添加了我当前的试用版

标签: r graphics graph


【解决方案1】:

这似乎很适合animation 包。你可以做这样的事情。首先,定义一个可以在两个图之间进行插值的函数

framedata<-function(x) {
    subset(transform(my_mtcars, 
        x=rand + x*(wt-rand),
        y=mpg
    ), select=c(x,y))
}

然后你可以用动画制作它们

library(animation)
frame <- seq(0, 1, length.out=20)
saveGIF(lapply(frame, function(f) {
    print( ggplot(framedata(f), aes(x, y)) + geom_point() )
}), "go.gif", interval = 0.05, loop=1)

这将创建一个 20 帧动画,在播放一次的帧之间有 0.05 秒的延迟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多