Generate colors based on unique entries in another list in R

亡梦爱人 提交于 2019-12-25 08:13:50

问题


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

Is there a way I can use the E(g)$fruit as an index into the colrs list?

There are 4 types of fruits in E(g)$fruit:

unique(E(g)$fruit)
"Apple"       "Orange"      "Grapes"     "Pear"

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

回答1:


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)



回答2:


I needed similar code but I needed a bigger color pallet (more then 8 provided in "Accent"), we can use the colorRampPalette function for that. That way we can create our own palette with the amount of colors we need.

colourCount = length(unique(g$fruit))
getPalette = colorRampPalette(brewer.pal(9, "Set1"))
colrs<- getPalette(colourCount)
names(colrs) <- unique(E(g)$fruit)
E(g)$color <- colrs[E(g)$fruit]  
E(g)$color
plot(g,layout=layout.fruchterman.reingold, vertex.color='grey80', vertex.label.color="black", edge.color=E(g)$color)


来源:https://stackoverflow.com/questions/40349343/generate-colors-based-on-unique-entries-in-another-list-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!