2017-06-15 7 views
0

igraphを使用してSQL Serverからグラフをプロットしています。私は、入力として3列の表を提供しています:Rグラフ:列の内容による色の頂点

from to  color 
Node1 NodeA red 
Node1 NodeB green 
Node1 NodeC blue 
Node2 NodeD red 
Node2 NodeE green 

マイRスクリプトは次のようになります。

require(igraph) 
g <- graph.data.frame(graphdf) 
V(g)$label.cex <- 2 
png(filename = "'[email protected]+'", height = 3000, width = 3000, res = 100); 
plot(g, vertex.label.family = "sans", vertex.size = 5) 
dev.off() 

プロットのエッジが希望色で表示されますが、頂点自体はない - 理想的私は 'to'頂点を 'color'カラムに示された色にしたい。私は 'from'の色を気にしません(デフォルトのオレンジ色にすることができます)。

私は、この(および変形)を追加しようとしました:PNGラインの前に

V(g)$color <- graphdf[V(g), 3] 

、それはランダムな頂点の色のように見えるものを生成します。

答えて

2

これは、graphdfの作成方法によって異なります。列の文字列または要素ですか?私は両方の場合の解決方法を示します。

graphdfが文字列

library(igraph) 

## Create data 
graphdf = read.table(text="from to  color 
Node1 NodeA red 
Node1 NodeB green 
Node1 NodeC blue 
Node2 NodeD red 
Node2 NodeE green", 
header=TRUE, stringsAsFactors=FALSE) 
g <- graph.data.frame(graphdf) 

が含まれている私は、すべてのノードがオレンジ色に作るが、その後、宛先ノードの色を調整します。

## Make default color orange 
V(g)$color = "orange" 
V(g)[graphdf$to]$color = graphdf$color 

Graph 1

graphdfが要因

メシエケースが含まれていますが、すべての文字列が要因になることを許可されている場合です。ここでの唯一の違いは、使用する際にすべての要因にas.characterを適用する必要があることです。

graphdf = read.table(text="from to  color 
Node1 NodeA red 
Node1 NodeB green 
Node1 NodeC blue 
Node2 NodeD red 
Node2 NodeE green", 
header=TRUE) 
g <- graph.data.frame(graphdf) 

V(g)$color = "orange" 
V(g)[as.character(graphdf$to)]$color = as.character(graphdf$color) 
plot(g) 
+0

データはSQL SELECTから提供され、sp_execute_external_scriptのパラメータとして提供されていたため、要因が含まれているかどうかわかりませんでした。 2番目のソリューションは完全に機能しました。ありがとう! –

+0

ところで、 'str(graphdf)'は文字列か要素かを表示します。 – G5W

関連する問題