我在 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))
还有其他办法可以让颜色较深的节点仍然具有可见的标签吗?
我认为这取决于您对颜色区分的主观看法。您可以专门为顶点标签定义调色板,例如,
labelcolor_palette <- colorRampPalette(c("white", "lightyellow", "red", "purple", "black"))(max_dist + 1)
V(g)$labelcolor <- labelcolor_palette[distances_from_50 + 1]
plot(g,
vertex.size = 7,
vertex.label = V(g)$value,
vertex.label.cex = 1,
vertex.label.color = V(g)$labelcolor,
main = "Distance-based Color Gradient from Node 50",
layout = cbind(V(g)$x, V(g)$y)
)