【问题标题】:Color bar legend for values on vertices of igraph in RR中igraph顶点值的颜色条图例
【发布时间】:2023-11-07 01:19:01
【问题描述】:

我是 R 新手,我开始使用 igraph 进行图形可视化。下面的示例创建了一个由 10 个顶点组成的简单网络,并根据颜色值对它们进行着色(在这种情况下,为了简单起见,我将其设置为与顶点的 id 相同)。

library(igraph)
vertices <- 1:10
first <- 1:10
second <- c(2:10,1)
edges = cbind(first,second)
color = 1:10
net = graph_from_data_frame(edges,vertices=vertices ,directed=F )
V(net)$color = color
plot(net)

但是,从该图中,尚不清楚哪些颜色对应于 哪些数字:

为了解决这个问题,我尝试创建各种 我能够在文档和在线找到的传说。采取 例如下面的代码:

legend("bottom", legend=levels(as.factor(color)), bty = "n", cex =
1.5, pt.cex = 3, pch=20, col = color , horiz = FALSE , inset = c(0.1,
-0.3)

但是在这种情况下,结果是混乱的,使图片模糊,并且不提供将节点上的值范围映射到色谱的连续颜色条。我能找到的其他选项也不是更好。

您知道如何以连续颜色条的形式制作图例,放置在图片下方或右侧(使其不覆盖图片的任何部分)?理想情况下,颜色条应该显示整个连续的颜色光谱和与颜色相对应的一些值(至少是极端值)? 你碰巧知道如何做到这一点吗?

感谢您的帮助!

【问题讨论】:

    标签: r igraph


    【解决方案1】:

    您应该查看 kokkenbaker 的这个答案,虽然它有点麻烦,但它可能正是您所需要的。 How to add colorbar with perspective plot in R

    【讨论】:

    • 欢迎提供解决方案链接,但请确保您的答案在没有它的情况下有用:add context around the link 这样您的其他用户就会知道它是什么以及为什么会出现,然后引用最相关的您链接到的页面的一部分,以防目标页面不可用。 Answers that are little more than a link may be deleted.
    • 非常感谢,您提到的帖子确实提出了一个可能的解决方案。看来我无法将代码粘贴到答案中,所以我将在问题的下一条评论中这样做。
    【解决方案2】:

    感谢 ealbsho93,我能够生成以下解决方案。它创建一个调色板,然后将图形上顶点上的值映射到调色板并显示它。这并不简单,但结果看起来要好得多(见下文)

    rm(list=ls())
    library(igraph)
    library(fields)
    
    vertices <- 1:10
    first <- 1:10
    second <- c(2:10,1)
    edges = cbind(first,second)
    net = graph_from_data_frame(edges,vertices=vertices ,directed=F )
    
    #Here we create a sample function on the vertices of the graph
    color_num = 10:1
    #create a color palette of the same size as the number of vertices.
    jet.colors <- colorRampPalette( rainbow( length( unique(color_num) ) ) )
    color_spectrum <- jet.colors( length( unique(color_num ) ) )
    #and over here we map the pallete to the order of values on vertices
    ordered <- order(color_num)
    color <- vector(length = length(ordered),mode="double")
    for ( i in 1:length(ordered) )
    {
        color[ ordered[i] ] <- color_spectrum [ i ]
    }
    V(net)$color = color
    
    #Display the graph and the legend.
    plot(net)
    image.plot(legend.only=T, zlim=range(color_num), col=color_spectrum )
    

    如果有更好的解决方案,请告诉我。否则,这个似乎可以使用。

    【讨论】: