首页 > 解决方案 > 网络可视化(node_shape)

问题描述

我是一个新的 Python 用户,我需要你的帮助来了解我将用于 Twitter 网络可视化的代码。我的 data_set 分为两个 csv_files :

我使用 stackoverflow 代码导入数据并进行一些测量/可视化

import csv
import matplotlib.pyplot as plt
from operator import itemgetter
import networkx as nx
with open('haropa_nodes.csv', 'r') as nodecsv: # Open the file
    nodereader = csv.reader(nodecsv, delimiter=';') # Read the csv
    # Retrieve the data (using Python list comprhension and list slicing to remove the header row, see footnote 3)
    nodes = [n for n in nodereader][1:]
node_names = [n[0] for n in nodes] # Get a list of only the node names

with open('haropa_edges.csv', 'r') as edgecsv: # Open the file
edgereader = csv.reader(edgecsv, delimiter=';') # Read the csv
edges = [tuple(e) for e in edgereader][1:] # Retrieve the data

然后这段代码获取一个网络对象:

G = nx.DiGraph()

G.add_nodes_from(node_names)

G.add_edges_from(edges)

为了可视化我的图表,我想要这个结构:

对于 node_size,我使用了以下代码:

node_size = [v * 30 for v in in_degree_dict.values()] 

也许有一个最简单的代码来做到这一点?

对于 node_color,我使用了我在 stackoverflow 上看到的一种方法,该方法包括转换数据帧中的节点

import pandas as pd
carac=pd.DataFrame(nodes)
carac.columns = ['ID', 'my_values','Genre']
carac= carac.set_index('ID')
carac=carac.reindex(G.nodes())
carac['my_values']=pd.Categorical(carac['my_values'])

我不知道是否存在其他方法可以做到这一点,因为我无法选择颜色:如果 my_values = "Politics" node_color = "green" if my_values = "Scientist",我想做 node_color = "red" 但确实如此不行 ..

对于 node_shape,我使用了与 node_color 相同的方法,但它不起作用。我试试这个:

node_shape = ['d' if entry == 'Male' else 'r' for entry in carac.Genre]

但我得到错误..

这是我使用的代码。代码正在运行,但我想添加 node_shape 参数

#seed
seed = 13648

#Layout
pos = nx.spring_layout(G, k = 0.95, iterations=30, seed = seed)


#Node_size related to in_degree
node_size = [v * 10 for v in in_degree_dict.values()] #Taille du noeud

nx.draw(G, pos, with_labels=False, #Je vire les labels 
        node_color=carac['my_values'].cat.codes, ## It works
        node_size=node_size,
        node_shape = # I do not know how to do ...
        cmap=plt.cm.Set2,
        edge_color="gainsboro",
        alpha=0.9)

plt.show()

最后一件事是我要做的是绘制两个图表:

我读了一些关于 HITS 的东西,但是,正如我之前所说,我是新手,而且还不是很清楚......

如果这篇文章太长,我很抱歉,但我会感谢你的帮助!

谢谢

罗曼

标签: networkinggraphnetworkxgraph-visualization

解决方案


推荐阅读