簡體   English   中英

使用RColorBrewer根據頂點屬性設置igraph頂點顏色

[英]Set igraph vertex color based on vertex attribute using RColorBrewer

我在iGraph中有一個網絡,該網絡具有代表各種因素的多個頂點屬性。 當我基於特定屬性繪制圖形時,我想為頂點着色。 類似於在ggplot使用color = variableggplot

plot()的參數vertex.color可用於為網絡中的所有頂點設置頂點顏色,或者它可以接受RGB值並為每個頂點設置頂點顏色。

我已經將RColorBrewer視為創建貨盤的一種方式,但是我不確定如何將其映射回頂點屬性。 我也不想硬編碼每個屬性值的顏色,因為我有多個屬性,每個屬性具有不同的級別數。

library(igraph)
library(RColorBrewer)

# create an example network
g <- make_ring(5)

# assign vertex attributes
g <- set.vertex.attribute(g, 'group', 1, 'A')
g <- set.vertex.attribute(g, 'group', 2, 'A')
g <- set.vertex.attribute(g, 'group', 3, 'B')
g <- set.vertex.attribute(g, 'group', 4, 'B')
g <- set.vertex.attribute(g, 'group', 5, 'C')

# create color pallet based on unique values for vertex attribute
pal <- brewer_pal(length(unique(V(g)$group)), "Dark2")

# plot network
plot(g, vertex.color = "gray")

錯字? 至少在我的RColorBrewer版本中,它是brewer.pal而不是brewer_pal

我們想使用group屬性的值從生成的調色板中選擇一種顏色,但是這些值是字符串,而不是數字。 一種解決方法是將字符串轉換為因數,然后將其用作數字。 這樣會將每個唯一的字符串值轉換為唯一的數字值。 我們可以用它來選擇顏色。

plot(g, vertex.color = pal[as.numeric(as.factor(vertex_attr(g, "group")))])

按屬性選擇的顏色

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM