首页 > 解决方案 > 如何通过连接 R 中相邻位置的线的粗细或颜色来可视化地图上的距离矩阵?

问题描述

假设我有两个数据集:(1)一个数据框:地点坐标,每个都有 ID;(2) 语言距离矩阵,反映这些地区之间的语言距离。

# My data are similar to this structure 
# dataframe
id <- c("A","B","C","D","E")
x_coor <- c(0.5,1,1,1.5,2)
y_coor <- c(5.5,3,7,6.5,5)
my.data <- data.frame(id = id, x_coor = x_coor, y_coor = y_coor)

# linguistic distance matrix
       A          B          C          D
B 308.298557                                 
C 592.555483 284.256926                      
D 141.421356 449.719913   733.976839           
E 591.141269 282.842712   1.414214     732.562625

现在,我想通过连接 R 中相邻位置的线的粗细或颜色将每两个站点之间的语言距离可视化到地图上。

就像这样: 在此处输入图像描述

我的想法是通过 deldir 或 tripack 包在 R 中生成 delaunay 三角剖分。

# generate delaunay triangulation
library(deldir)
de=deldir(my.data$x_coor,my.data$y_coor)
plot.deldir(de,wlines="triang",col='blue',wpoints = "real",cex = 0.1)
text(my.data$x_coor,my.data$y_coor,my.data$id)

这是情节: 在此处输入图像描述

我的问题是如何通过三角形边缘的厚度或颜色来反映语言距离?还有其他更好的方法吗?

非常感谢!

标签: rdictionaryedgesdelaunaydistance-matrix

解决方案


deldir 包可以“相当容易地”完成您想要在线宽方面做的事情。您只需使用适当的“lw”(线宽)值调用 plot.deldir()。

这个答案的底部是一个演示脚本“demo.txt”,它显示了如何在您的示例中执行此操作。特别是,此脚本显示了如何从“语言距离矩阵”中获取适当的 lw 值。我不得不对这个矩阵的呈现方式进行一些调整。即我必须将其转换为适当的矩阵。

我已将距离重新调整为介于 0 和 10 之间以获得相应的线宽值。您可能希望以不同的方式重新缩放。

关于颜色,有两个问题:

(1) 完全不清楚您希望如何将“语言距离”映射到颜色。

(2) 不幸的是,plot.deldir() 的代码是以非常笨拙的方式编写的,因此,segments() 的“col”参数不能以与“lw”参数相同的方式适当地传递。(我很久以前写了 plot.deldir() 代码,当时我对 R 编程的了解远比我现在知道的少!:-))

我将调整此代码并很快将新版本的 deldir 提交给 CRAN。

#
# Demo script
#

# Present the linguistic distances in a useable way.
vldm <- c(308.298557,592.555483,284.256926,141.421356,449.719913,
         733.976839,591.141269,282.842712,1.414214,732.562625)
ldm <- matrix(nrow=5,ncol=5)
ldm[row(ldm) > col(ldm)] <- vldm
ldm[row(ldm) <= col(ldm)] <- 0
ldm <- (ldm + t(ldm))/2
rownames(ldm) <- LETTERS[1:5]
colnames(ldm) <- LETTERS[1:5]

# Set up the example data.  It makes life much simpler if
# you denote the "x" and "y" coordinates by "x" and "y"!!!
id <- c("A","B","C","D","E")
x_coor <- c(0.5,1,1,1.5,2)
y_coor <- c(5.5,3,7,6.5,5)
# Eschew nomenclature like "my.data".  Such nomenclature
# is Micro$oft-ese and is an abomination!!!
demoDat <- data.frame(id = id, x = x_coor, y = y_coor)

# Form the triangulation/tessellation.
library(deldir)
dxy <- deldir(demoDat)

# Plot the triangulation with line widths proportional
# to "linguistic distances".  Note that plot.deldir() is
# a *method* for plot, so you do not have to (and shouldn't)
# type the ".deldir" in the plotting command.
plot(dxy,col=0) # This, and plotting with "add=TRUE" below, is
                # a kludge to dodge around spurious warnings.
ind <- as.matrix(dxy$delsgs[,c("ind1","ind2")])
lwv <- ldm[ind]
lwv <- 10*lwv/max(lwv)
plot(dxy,wlines="triang",col='grey',wpoints="none",
            lw=10*lwv/max(lwv),add=TRUE)
with(demoDat,text(x,y,id,col="red",cex=1.5))

推荐阅读