网络图颜色与图例不匹配

时间:2019-01-21 16:42:54

标签: r plot legend igraph

我有一个igraph网络,我想用RColorBrewer上色。顶点具有“扇形”属性,我想使用它为它们着色。为此,我基于扇区定义了一个调色板:

color.range <- brewer.pal(nlevels(as.factor(V(g)$sector)), name = "Dark2")
V(g)$color  <- color.range[as.factor(V(g)$sector)]

当我绘制图形时,图例的颜色与顶点的“ sector”属性中的信息不匹配:

plot.igraph(g,
        vertex.label = ifelse(V(g)$indegree > 5, V(g)$sector, NA),
        vertex.label.family = "Arial",
        vertex.label.color = "black",
        vertex.label.cex = 0.5,
        vertex.frame.color = NA,
        vertex.color = V(g)$color,
        vertex.size = 3,
        layout = layout.fruchterman.reingold,
        edge.arrow.mode = 1,
        edge.arrow.size = 0.2)

legend("topleft",
        legend = levels(as.factor(V(g)$sector)),
        col = levels(as.factor(V(g)$color)),
        pch = 19,
        cex = 0.8,
        title = "",
        bg="transparent",
        bty = "n")

在图上,我看到了一些高顶点的类别,并将它们与图例进行比较,颜色不匹配: example plot where colors on graph do not match legend

我的问题是:如何定义与我的行业类别实际匹配的颜色范围,或者如何创建可以正确表示颜色的图例。不幸的是,我不知道是哪个问题。

2 个答案:

答案 0 :(得分:0)

我认为您计算的图例颜色不正确。如果相反,我使用

col = color.range[as.numeric(levels(as.factor(V(g)$sector)))]

图例中的颜色与图中的标记点匹配。

答案 1 :(得分:0)

对我来说,G5W的解决方案无法完全发挥作用

levels(as.factor(V(g)$sector))

将级别作为无法转换为数字的字符串列表返回,因此出现错误:

Warning message:
In legend("topleft",legend = levels(as.factor(V(g)$sector)),col = 
color.range[as.numeric(levels(as.factor(V(g)$sector)))],: NAs introduced by coercion

我又添加了一个as.factor(),它现在似乎可以工作了:

col = color.range[as.numeric(as.factor(levels(as.factor(V(g)$sector))))],
相关问题