用R绘图时如何改变分辨率?

时间:2013-02-16 12:38:28

标签: r

我最近开始在R编码,并偶然发现了这个代码,它绘制了一个Mandelbrot分形:

library(caTools)         # external package providing write.gif function
jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", 
                                 "yellow", "#FF7F00", "red", "#7F0000")) 
m <- 1200                # define size
C <- complex( real=rep(seq(-1.8,0.6, length.out=m), each=m ), 
              imag=rep(seq(-1.2,1.2, length.out=m), m ) ) 
C <- matrix(C,m,m)       # reshape as square matrix of complex numbers
Z <- 0                   # initialize Z to zero
X <- array(0, c(m,m,20)) # initialize output 3D array
for (k in 1:20) {        # loop with 20 iterations
  Z <- Z^2+C             # the central difference equation  
  X[,,k] <- exp(-abs(Z)) # capture results
} 
write.gif(X, "Mandelbrot.gif", col=jet.colors, delay=100)

我做了一些测试并查看了结果。我发现图像的分辨率太低,所以我尝试使用这段代码来提高分辨率:基本上,它会计算两次函数(即f(1)f(1.5)f(2),我认为f(2.5)代替f(1)f(2))。

library(caTools)         # external package providing write.gif function
jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", 
                                 "yellow", "#FF7F00", "red", "#7F0000")) 
m <- 1200                # define size
C <- complex( real=rep(seq(-1.8,0.6, length.out=m), each=m ), 
              imag=rep(seq(-1.2,1.2, length.out=m), m ) ) 
C <- matrix(C,m,m)       # reshape as square matrix of complex numbers
Z <- 0                   # initialize Z to zero
X <- array(0, c(m,m,20*2)) # initialize output 3D array
for (n in 1:20) {        # loop with 20 iterations
  for (m in 1:2) { # Loop twice
    k <- n+m/2 # Does the trick of adding .5
    Z <- Z^2+C             # the central difference equation  
    X[,,k] <- exp(-abs(Z)) # capture results
  }
} 
write.gif(X, "Mandelbrot.gif", col=jet.colors, delay=100)

虽然它计算的数字量是两倍,但Mandelbrot.gif的分辨率和尺寸(1200x1200)似乎相同。

1 个答案:

答案 0 :(得分:1)

只需增加m的值即可提高分辨率。但是,X中的元素数量是m ^ 2 * 20,它很容易变得大于2 ^ 31-1,这是矢量长度的当前限制(数组是具有附加属性的向量) R.要么你找到一个不同的函数来创建动画GIF,不需要将所有信息保存在一个数组中,或者你等待R的下一个主要更新,这将增加对象大小限制afaik。

以下代码允许更高的分辨率,但要注意,它需要大量的CPU时间,并且您将快速耗尽内存。你还需要ImageMagick。

library(animation)         # external package providing saveGIF function
jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", 
                                 "yellow", "#FF7F00", "red", "#7F0000")) 
m <- 200                # define size
C <- complex( real=rep(seq(-1.8,0.6, length.out=m), each=m ), 
              imag=rep(seq(-1.2,1.2, length.out=m), m ) ) 
C <- matrix(C,m,m)       # reshape as square matrix of complex numbers
Z <- 0                   # initialize Z to zero
saveGIF(
  for (k in 1:20) {        # loop with 20 iterations
    Z <- Z^2+C             # the central difference equation  
    image(exp(-abs(Z)),col=jet.colors(255)) # plot results
  },"Mandelbrot2.gif"  
)