在 R 中增量绘图而不是重置 [英] Plotting incrementally in R and not resetting

查看:79
本文介绍了在 R 中增量绘图而不是重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您会使用哪些选项(和包)来增量绘制计算结果?

What options (and package) would you use to incrementally plot the results of a calculation?

想象一下,我想绘制一个持续很长时间的计算结果,我不想等到最后才能看到一些结果.绘制每个点并不是一个好主意,因为每次启动 plot 命令都会非常慢.我将改为每 N 个点绘制一次(将它们保存在一个向量上).

Imagine I want to plot the results of a computation that lasts for a very long time and I don't want to wait till the end to see some results. It won't be a good idea to plot every single point because it would be very slow to launch the plot command every time. I will plot every N points instead (saving them on a vector).

例如,如果我使用斐波那契数列进行操作,将循环分成两个嵌套循环,以便每 10 次迭代绘制一次结果:

For example if I do it with the Fibonacci series, breaking the loop in two nested loops in order to plot the results every 10 iterations:

fibo=rep(0,112);fibo[1]=0;fibo[2]=1;
plot(fibo)              #to initialize 
for(ii in 0:10) {
  for(jj in 0:9) {
    fibo[ii*10+jj+3]=fibo[ii*10+jj+2]+fibo[ii*10+jj+1];
  }
plot(fibo)
}

但它不会保留上一次迭代的图形.我怎么做?这不是一个很好的例子,因为数字增长得太快了.并且绘图初始化事先不知道最大 y 值.也许使用其他更好的图形包会更好?

But it doesn't keep the graph from the previous iteration. How I do this? This is not a good example because the numbers grow too quickly. And the plot initialization doesn't know the max y value in advance. Maybe it is better to use some other better graph package?

推荐答案

这是一个简单的示例,说明如何通过设置应绘制的点并仅在满足此条件时添加 points 来执行此操作:

Here's a simple example of how to do this by setting the points which should be plotted and only adding points when this criteria is met:

# set the frequency with which to plot points
plotfreq <- 10

# set the x and y limits of the graph
x.limits <- c(1,100)
y.limits <- c(0,100)

# initialise a vector and open a plot
result <- vector(mode="numeric",length=100)
plot(result,ylim=y.limits,xlim=x.limits,type="n")

# do the plotting
plot.iterations <- seq(plotfreq,length(result),by=plotfreq)
for (i in seq_along(result)) {
  result[i] <- result[i] + i

  # only plot if the data is at the specified interval
  if (i %in% plot.iterations) {
    points(i,result[i])
  }

}

这篇关于在 R 中增量绘图而不是重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆