Mapping a specific column of values to the scale color of vertexs in R

主宰稳场 提交于 2020-01-14 03:06:06

问题


Now I have a data frame df1:

v1                v2
a                 10
b                 1
c                 3
d                 7
.......

And another data frame df2:

v1                v2
d                 a
c                 a
b                 c
c                 d
...

I'd like to plot a network based on df2 with igraph:

plot(g, layout = layout_in_circle(g))

And the color of vertexes(a,b,c,d...) should be in range of red to blue and the bigger the value in v2, the color of that vertex should be more closer to red. I have tried:

require(igraph)
g = graph.data.frame(df)
plot(g, layout = layout_in_circle(g), vertex.color = color.scale(mention_counted$V2,c(0,1,1),c(1,1,0),0))

But the color of vertexes is not map to the value in v2 properly. Is there a way to do that? Thank you in advance!


回答1:


library(igraph)
library(dplyr)

# data frame to get colours
dt1 = data.frame(v1 = c("a","b","c","d"),
                 v2 = c(10, 1, 3, 7))

dt1

#   v1 v2
# 1  a 10
# 2  b  1
# 3  c  3
# 4  d  7


# create color column
dt1$color = colorRampPalette(c("blue","red"))(max(dt1$v2))[dt1$v2]

dt1

#   v1 v2   color
# 1  a 10 #FF0000
# 2  b  1 #0000FF
# 3  c  3 #3800C6
# 4  d  7 #AA0055


# data frame to get network
dt2 = data.frame(v1 = c("d","c","b","c"),
                 v2 = c("a","a","c","d"))

dt2

#   v1 v2
# 1  d  a
# 2  c  a
# 3  b  c
# 4  c  d


# build graph
g = graph.data.frame(dt2)

# check order of vertices
V(g)

# + 4/4 vertices, named:
#   [1] d c b a


# get info for vertices in the right order
dt_info =
  data.frame(names = names(V(g))) %>%
  inner_join(dt1, by = c("names"="v1"))

dt_info

#   names v2   color
# 1     d  7 #AA0055
# 2     c  3 #3800C6
# 3     b  1 #0000FF
# 4     a 10 #FF0000

# plot graph
plot(g, vertex.color = dt_info$color)


来源:https://stackoverflow.com/questions/34994503/mapping-a-specific-column-of-values-to-the-scale-color-of-vertexs-in-r

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