2017-03-07 57 views
1

我有三列數據,我想繪製爲二維彩色地圖。第一列代表x軸,第二列代表y軸。然而,這些值不是以規則間隔網格的形式存在,第三列的數據在二維空間中相當隨機的點上可用。我在下面給出了一個示例數據集。實際的數據集長達數千行。如何將三列中的矩陣或數據框的數據繪製爲顏色圖?

 X1  X2  X3 
1 0.000000 NaN 1760 
2 1.000000 0.0000000 1536 
3 2.000000 0.0000000 1744 
4 3.000000 0.0000000 1632 
5 1.000000 1.5707963 1616 
6 1.414214 0.7853982 1632 
7 2.236068 0.4636476 1712 
8 3.162278 0.3217506 1616 
9 2.000000 1.5707963 1616 
10 2.236068 1.1071487 1568 
11 2.828427 0.7853982 1712 
12 3.605551 0.5880026 1600 
13 3.000000 1.5707963 1536 
14 3.162278 1.2490458 1536 
15 3.605551 0.9827937 1568 
16 4.242641 0.7853982 1536 

該數據是由實際上是「熔融」(庫重塑)與值(光柵)的笛卡爾網格,然後轉換成極座標,與意圖繪製第r和θ得到。第一列是r,第二列是theta,第三列是光柵像素的強度。我希望能夠繪製網格位置(線性軸上)第三列的值,由第一列和第二列的相應值定義。因此,舉例來說,取第二行,在(1,0)

的色標上代表的值爲1536我查看了很多選項,例如熱圖,並且發現了對matlab或python,但我想在R中做到這一點。有什麼辦法可以做到這一點?如果我能夠調整色階等,則爲紅利。

爲了說明起見,第一列和第二列必須表示爲線性軸本身(我解釋了關於r和theta的部分以解釋數據的來源) 。我希望最終的結果是這樣的: Raster plot

希望它有幫助!

+0

15分是相當稀疏......你可以在'ggplot2'使用'geom_tile'。 ''geom_raster'和'?geom_contour'中有例子,但我認爲你的數據對於自動方法來說太稀疏了。 – Gregor

+0

這個答案可能是有趣的:http://stackoverflow.com/questions/19339296/plotting-contours-on-an-irregular-grid – bdemarest

+0

@Gregor,我應該更具體。這是一個有代表性的數據。實際的數據集包含數千行這樣的行。我編輯了這個問題來反映這一點。 – Pradical2190

回答

0

下面的解決方案直接取自@Henrik提供的這個夢幻般的答案Plotting contours on an irregular grid。它使用akima包來內插在2D空間上不規則地測量的z值。然後,使用geom_raster()繪製熱圖。

dat = read.table(header=TRUE, 
text="  X1  X2  X3 
1 0.000000 NaN 1760 
2 1.000000 0.0000000 1536 
3 2.000000 0.0000000 1744 
4 3.000000 0.0000000 1632 
5 1.000000 1.5707963 1616 
6 1.414214 0.7853982 1632 
7 2.236068 0.4636476 1712 
8 3.162278 0.3217506 1616 
9 2.000000 1.5707963 1616 
10 2.236068 1.1071487 1568 
11 2.828427 0.7853982 1712 
12 3.605551 0.5880026 1600 
13 3.000000 1.5707963 1536 
14 3.162278 1.2490458 1536 
15 3.605551 0.9827937 1568 
16 4.242641 0.7853982 1536") 

library(akima) 
library(reshape2) 
library(ggplot2) 

dat = dat[-1, ] # Remove row with NaN so `interp` will work properly. 

# Interpolate 500 x 500 values, using spline interpolation. 
res = interp(x=dat$X1, y=dat$X2, z=dat$X3, nx=500, ny=500, linear=FALSE) 

# Reformat `interp` results into a long-format data.frame. 
idat = melt(res$z, na.rm=TRUE) 
names(idat) = c("x", "y", "X3") 
idat$X1 = res$x[idat$x] 
idat$X2 = res$y[idat$y] 

p1 = ggplot(idat, aes(x=X1, y=X2, fill=X3)) + 
    geom_raster() + 
    scale_fill_gradientn(colours = terrain.colors(10)) 

ggsave("interpolated_heatmap.png", p1, height=4, width=6, dpi=150) 

enter image description here

+0

謝謝@bdemarest。這個答案正常工作... – Pradical2190

相關問題