使用ggnet2在R中按度数着色

时间:2016-05-20 16:21:53

标签: r ggplot2 igraph graph-visualization ggally

我一直在尝试使用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

我想要绘制的是一个图表,节点的颜色基于它们的程度,如下所示: enter image description here

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

修改

添加完整示例

1 个答案:

答案 0 :(得分:7)

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

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

我还为所有调用添加了库前缀,这样我就可以看到从什么网络库(igraph,网络等)中使用了什么。这些库中存在大量重叠和相互依赖。

请注意,此代码应将0-1映射到black2,将red映射到3,将green映射到>=4 }和redlibrary(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()

   String output = "";  
   for (int i = 0; i < NumberOfSlot; i++) {
        output = Math.random() * 10 <= 5 ? output+"R" : output+"L";
    }
    JOptionPane.showMessageDialog(null, output);
    //edited the answer according to op's last comment.

产量:

enter image description here