2017-03-07 58 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

相关问题