2014-03-27 14 views
2

我想繪製一個x行和y列的z值矩陣作爲類似於MATLAB的這個圖表的曲面。R中的曲面圖Q-compable to surf()在matlab中

曲面圖:

enter image description here

代碼生成矩陣:

# Parameters 
shape<-1.849241 
scale<-38.87986 
x<-seq(from = -241.440, to = 241.440, by = 0.240)# 2013 length 
y<-seq(from = -241.440, to = 241.440, by = 0.240) 
matrix_fun<-matrix(data = 0, nrow = length(x), ncol = length(y)) 

# Generate two dimensional travel distance probability density function 
for (i in 1:length(x)) { 
for (j in 1:length(y)){ 
dxy<-sqrt(x[i]^2+y[j]^2) 
prob<-1/(scale^(shape)*gamma(shape))*dxy^(shape-1)*exp(-(dxy/scale)) 
matrix_fun[i,j]<-prob 
}} 

# Rescale 2-d pdf to sum to 1 
a<-sum(matrix_fun) 
matrix_scale<-matrix_fun/a 

我可以用幾個方法(persp(), persp3d(), surface3d())來生成表面圖,但顏色不顯示z值(在矩陣內保持的概率)。 z值似乎只顯示爲高度,而不像MATLAB圖中的差分顏色。的圖形碼和圖形

實施例:最後一個圖形

enter image description here

任何其他提示,以重新創建在R中的圖像將是非常理解的

library(rgl) 
persp3d(x=x, y=y, z=matrix_scale, color=rainbow(25, start=min(matrix_scale), end=max(matrix_scale))) 
surface3d(x=x, y=y, z=matrix_scale, color=rainbow(25, start=min(matrix_scale), end=max(matrix_scale))) 
persp(x=x, y=y, z=matrix_scale, theta=30, phi=30, col=rainbow(25, start=min(matrix_scale), end=max(matrix_scale)), border=NA) 

圖像(即圖例條,軸刻度線等)

+0

也許''filled.contour'可能會有幫助嗎? –

回答

1

所以這裏有一個ggplot解決方案,它似乎來得有點接近MATLAB情節

# Parameters 
shape<-1.849241 
scale<-38.87986 
x<-seq(from = -241.440, to = 241.440, by = 2.40) 
y<-seq(from = -241.440, to = 241.440, by = 2.40) 
df  <- expand.grid(x=x,y=y) 
df$dxy <- with(df,sqrt(x^2+y^2)) 
df$prob <- dgamma(df$dxy,shape=shape,scale=scale) 
df$prob <- df$prob/sum(df$prob) 

library(ggplot2) 
library(colorRamps)  # for matlab.like(...) 
library(scales)   # for labels=scientific 
ggplot(df, aes(x,y))+ 
    geom_tile(aes(fill=prob))+ 
    scale_fill_gradientn(colours=matlab.like(10), labels=scientific) 

BTW:您可以生成概率的數據幀更多高效地使用內置的dgamma(...)函數,而不是自己計算它。

+0

非常感謝dgamma()fx上的技巧,它可以簡化事物。我希望我能投票贊成,但我還沒有足夠的聲望。謝謝! – SamanthaDS

1

符合alexis_laz的評論,這裏是一個使用filled.contour的示例。您可能希望將by增加到2.40,因爲更精細的粒度會增加大量生成圖的時間,但不會提高質量。

filled.contour(x = x, y = y, z = matrix_scale, color = terrain.colors) 
# terrain.colors is in the base grDevices package 

enter image description here

如果你想要的東西更接近你上面的配色方案,您可以用rainbow功能不甘示弱:

filled.contour(x = x, y = y, z = matrix_scale, 
    color = (function(n, ...) rep(rev(rainbow(n/2, ...)[1:9]), each = 3))) 

enter image description here

更爲精細的粒度:

filled.contour(x = x, y = y, z = matrix_scale, nlevels = 150, 
    color = (function(n, ...) 
    rev(rep(rainbow(50, start = 0, end = 0.75, ...), each = 3))[5:150])) 

enter image description here

+0

您可以嘗試'colorRamps'包中的'matlab.like(...)'以使顏色更接近OP的示例 – jlhoward

+0

謝謝Robert,我喜歡ggplot解決方案稍微好一點,但填充輪廓也很棒。我真的很感激代碼顯示如何重新調整彩虹調色板以避免紅色兩端。我希望我能投票贊成,但我沒有足夠的聲望。非常感謝你的幫助。 – SamanthaDS