我在 R 中有这张图:
library(igraph)
width <- 30
height <- 20
num_nodes <- width * height
x <- rep(1:width, each = height)
y <- rep(1:height, times = width)
g <- make_empty_graph(n = num_nodes, directed = FALSE)
get_node_index <- function(i, j) (i - 1) * height + j
edges <- c()
for(i in 1:width) {
for(j in 1:height) {
current_node <- get_node_index(i, j)
if(i < width) edges <- c(edges, current_node, get_node_index(i + 1, j))
if(j < height) edges <- c(edges, current_node, get_node_index(i, j + 1))
}
}
g <- add_edges(g, edges)
V(g)$x <- x
V(g)$y <- y
par(mfrow=c(1,1))
V(g)$name <- 1:num_nodes
plot(g, vertex.size = 7, vertex.label = V(g)$name, vertex.label.cex = 0.6, main = "Map with Node Indices")
我想在这个图上选取某个节点,并根据它们与该节点的距离按比例为图上的所有节点着色。也就是说,距离相同的所有节点都具有相同的颜色 - 距离节点较近的节点颜色较深,距离较远的节点颜色较浅。
根据我之前的问题(计算图上多个点之间的最短距离?),我尝试这样做(例如选择节点 50):
distances_from_50 <- distances(g, v = 50, to = V(g))
max_dist <- max(distances_from_50)
color_palette <- colorRampPalette(c("#08306B", "#F7FBFF"))(max_dist + 1)
V(g)$color <- color_palette[distances_from_50 + 1]
V(g)$color[50] <- "red"
par(mfrow=c(1,1), mar=c(5,4,4,2))
plot(g,
vertex.size = 7,
vertex.label = V(g)$value,
vertex.label.cex = 0.6,
main = "Distance-based Color Gradient from Node 50",
layout = cbind(V(g)$x, V(g)$y))
还有其他方法可以做到让颜色较深的节点仍然具有可见的标签吗?
我认为这取决于你对颜色区分的主观感受。你可以为顶点标签专门定义一个调色板,例如,