将值的特定列映射到R中顶点的刻度颜色 [英] Mapping a specific column of values to the scale color of vertexs in R

查看:66
本文介绍了将值的特定列映射到R中顶点的刻度颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个数据框df1:

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

和另一个数据帧df2:

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

我想基于df2igraph绘制网络:

plot(g, layout = layout_in_circle(g))

并且顶点(a,b,c,d...)的颜色应该在红色到蓝色的范围内,并且v2中的值越大,该顶点的颜色应该越接近红色. 我已经尝试过:

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))

但是顶点的颜色未正确映射到v2中的值. 有没有办法做到这一点?预先谢谢你!

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!

推荐答案

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)

这篇关于将值的特定列映射到R中顶点的刻度颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆