【问题标题】:Color by degree in R using ggnet2使用 ggnet2 在 R 中按度数着色
【发布时间】:2016-09-17 23:56:44
【问题描述】:

我一直在尝试使用ggnet2 绘制图表。为此,我使用以下代码:

library(igraph)
lapply(c("sna", "intergraph", "GGally", "igraph", "network"), require, character.only=T)
data <- read.table('CA-CondMat.txt',sep="\t",header=TRUE)
g = graph.data.frame(data, directed = TRUE)
N = vcount(g)
E = ecount(g)
perc = 0.1
d.g = degree(g,mode='all')/N
new_nodes = sample.int(N,ceiling(perc*N),replace=FALSE,prob =d.g)
new_g = subgraph(g,new_nodes)
dg = degree(g,mode='all')
prob = dg/sum(dg)
png('example_plot2.png')
ggnet2(new_g, size = "degree", node.color = "steelblue", size.cut = 4,
                                          edge.size = 1, edge.color="grey" )
dev.off()

我得到一个完全蓝色的图表。

我正在使用包igraph

我要绘制的是一个基于节点颜色的图表,如下所示:

文件链接:
https://snap.stanford.edu/data/ca-CondMat.html

编辑:

添加完整示例

【问题讨论】:

  • 您需要提供带有示例输入数据的reproducible example。这样可以更轻松地为您提供帮助。
  • 这仍然无法重现,因为我们没有任何数据可以运行它(我们无权访问“CA-CondMat.txt”)。您应该按照我最初提供的链接中描述的方式提供数据。
  • 不要添加文件。链接可能会中断。请阅读@Mrflick 给你的链接。阅读How to Ask 可能也是一个好主意。

标签: r ggplot2 igraph graph-visualization ggally


【解决方案1】:

我很欣赏挑战,图表总是很有趣。我认为这就是你想要的(我修改了我的原件以使用你稍后提供的文件,因为我正在处理它):

在我的代码中clr-degree 是度数的一半,因为这个文件只有对称链接,没有黑色和绿色节点看起来很无聊。

我还为所有调用添加了库前缀,这样我就可以从哪个网络库(igraph、网络等)中查看正在使用的内容。这些库中有很多重叠和相互依赖关系。

请注意,此代码应将clr-degree 映射到0-1black,将2 度映射到red,将3 度映射到green,并将&gt;=4 映射到red

library(ggplot2)
library(igraph)
library(GGally)

# the following libraries will be required too - used internally
lapply(c("sna", "scales","intergraph", "network"),require, character.only=T)

set.seed(1234)

# data from  https://snap.stanford.edu/data/ca-CondMat.html
data <- read.table('CA-CondMat.txt',sep="")

g = igraph::graph.data.frame(data, directed = TRUE)
N = vcount(g)
E = ecount(g)
d.g = igraph::degree(g,mode='all')/N

# Use new smaller subgraph
perc = 0.05
new_nodes = sample.int(N,ceiling(perc*N),replace=FALSE,prob =d.g)
new_g = igraph::subgraph(g,new_nodes)
dg = igraph::degree(new_g,mode='all')

dg <- dg/2  # for some reason there are only even degrees in this file - so we divide by 2

clrvek = pmax(0,pmin(dg,4))
clrnames = c("0"="lightgrey","1"="black", "2"="blue", "3"="green", "4"="red")

#png('example_plot2.png')
GGally::ggnet2(new_g, 
       color.legend="clr-degree",palette=clrnames,color=clrvek,
       size = "degree",
       edge.size = 1, edge.color="grey",
       legend.position = "bottom") + coord_equal()
#dev.off()

产量:

【讨论】:

  • 我已经想出了这样的事情。现在我试图通过使用size.cut 划分节点并给每个组一个特定的颜色来改进它,但我就是不明白该怎么做。
  • 好吧,你能把它标记为正确(因为它回答了问题),然后再问一个新的吗?这就是 SO 的工作方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 2021-06-16
相关资源
最近更新 更多