根据R中另一个列表中的唯一条目生成颜色 [英] Generate colors based on unique entries in another list in R
问题描述
我想使用调色板为 igraph 中的图形边缘定义颜色。我已经使用 RColorBrewer
创建了调色板,并且需要根据边缘属性信息为每个边缘分配唯一的颜色。
I want to use a color palette to define colors for my graph edges in igraph. I have create the color palette using RColorBrewer
and need to assign a unique color to each edge based on edge attribute information.
到目前为止,这是我的尝试:
Here is my attempt so far:
colrs<- brewer.pal(length(unique(E(g)$fruit)), "Accent")
E(g)$color <- colrs[E(g)$fruit] #Does not work
E(g)$color
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[40] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[79] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
有没有一种方法可以使用 E(g)$ fruit
作为 colrs
列表?
Is there a way I can use the E(g)$fruit
as an index into the colrs
list?
E(g)$ fruit
有4种水果:
unique(E(g)$fruit)
"Apple" "Orange" "Grapes" "Pear"
因此,取决于哪种水果类型每个边缘都有,它应该从 colrs
列表中获得相应的颜色,以使所有带有 Apple的边缘具有相同的颜色,所有带有橙色的边缘具有相同的颜色,依此类推等等。我最终将使用以下代码绘制该图:
Thus depending on what type of fruit each edge has, it should get the corresponding color from the colrs
list such that all edges with "Apple" have the same color, all edges with "Orange" has the same color and so on and so forth. I will eventually plot the graph with the following code:
plot(g,layout=layout.fruchterman.reingold, vertex.color='grey80', vertex.label.color="black", edge.color=E(g)$color)
这里是我的图表边列表的示例:
Here is a sample of the edgelist of my graph:
from to fruit
1 A B Apple
2 A C Apple
3 B C Grapes
4 D B Pear
5 D C Orange
推荐答案
通过唯一的 E(g)$ fruit <命名您的
: colrs
向量
Name your colrs
vector by the unique E(g)$fruit
:
df <- read.table(header=T, text="
from to fruit
1 A B Apple
2 A C Apple
3 B C Grapes
4 D B Pear
5 D C Orange")
library(igraph)
library(RColorBrewer)
g <- graph_from_data_frame(df)
colrs<- brewer.pal(length(unique(E(g)$fruit)), "Accent")
names(colrs) <- unique(E(g)$fruit)
E(g)$color <- colrs[E(g)$fruit] #Does not work
E(g)$color
# [1] "#7FC97F" "#7FC97F" "#BEAED4" "#FDC086" "#FFFF99"
plot(g,layout=layout.fruchterman.reingold, vertex.color='grey80', vertex.label.color="black", edge.color=E(g)$color)
这篇关于根据R中另一个列表中的唯一条目生成颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!