显示带有标签的networkx图 [英] Displaying networkx graph with labels

查看:956
本文介绍了显示带有标签的networkx图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用networkx创建带标签的图形,但是在使节点和标签正确显示方面遇到困难.简而言之,标签不在正确的节点上对齐,并且有些节点在显示时没有边缘.

首先,我创建了一个图,添加了节点和边,然后添加了标签.

图形数据来自具有两列的pandas DataFrame对象,雇员和经理姓名:

                emp_name             mgr_name
0        Marianne Becker                 None
1            Evan Abbott      Marianne Becker
2               Jay Page      Marianne Becker
3             Seth Reese      Marianne Becker
4         Maxine Collier      Marianne Becker

...

每个节点是一个名称,边缘是mgr_name与emp_name的关系.

我的图形代码:

import networkx as nx
G=nx.DiGraph()

#set layout
pos=nx.spring_layout(G)

#add nodes
G.add_nodes_from(df.emp_name)
G.nodes()
G.add_node('None')

#create tuples for edges
subset = df[['mgr_name','emp_name']]
tuples = [tuple(x) for x in subset.values]

#add edges
G.add_edges_from(tuples)
G.number_of_edges()

#draw graph
import matplotlib.pyplot as plt
nx.draw(G, labels = True)
plt.show()

理想情况下,我会采用树状结构,将员工姓名作为每个节点的标签.

输出图像为

解决方案

Networkx具有许多绘制图形的功能,但也允许用户对整个过程进行精细控制.

draw是基本的,其文档字符串特别提到:

以无节点或边缘的简单表示形式绘制图形 标签,并默认使用完整的Matplotlib图形区域标签. 请参阅draw_networkx()了解允许标题,轴的更丰富的图纸 标签

draw_networkx为前缀,后跟edgesnodesedge_labelsedge_nodes的功能可以更好地控制整个绘制过程.

使用draw_networkx时,您的示例工作正常.

此外,如果您正在寻找类似于器官图的输出,我建议您使用 graphviz 通过networkx. Graphviz的dot非常适合这种图表(也请请参见以获得该点)

在下面的内容中,我试图对您的代码进行一些修改,以演示这两个功能的使用:

import networkx as nx
import matplotlib.pyplot as plt
import pandas

#Build the dataset
df = pandas.DataFrame({'emp_name':pandas.Series(['Marianne Becker', 'Evan Abbott', 'Jay Page', 'Seth Reese', 'Maxine Collier'], index=[0,1,2,3,4]), 'mgr_name':pandas.Series(['None', 'Marianne Becker', 'Marianne Becker', 'Marianne Becker', 'Marianne Becker'], index = [0,1,2,3,4])})

#Build the graph
G=nx.DiGraph()   
G.add_nodes_from(df.emp_name)
G.nodes()
G.add_node('None')
#
#Over here, you are manually adding 'None' but in reality
#your nodes are the unique entries of the concatenated
#columns, i.e. emp_name, mgr_name. You could achieve this by
#doing something like
#
#G.add_nodes_from(list(set(list(D.emp_name.values) + list(D.mgr_name.values))))
#
# Which does exactly that, retrieves the contents of the two columns
#concatenates them and then selects the unique names by turning the
#combined list into a set.

#Add edges
subset = df[['mgr_name','emp_name']]
tuples = [tuple(x) for x in subset.values] 
G.add_edges_from(tuples)
G.number_of_edges()

#Perform Graph Drawing
#A star network  (sort of)
nx.draw_networkx(G)
plt.show()
t = raw_input()
#A tree network (sort of)
nx.draw_graphviz(G, prog = 'dot')
plt.show()

通过nx.write_dot保存networkx网络,您也可以尝试直接从命令行使用graphviz的点.为此:

在您的python脚本中:

nx.write_dot(G, 'test.dot')

此后,从(linux)命令行并假设您已安装graphviz:

dot test.dot -Tpng>test_output.png
feh test_output.png #Feh is just an image viewer.
firefox test_output.png & #In case you don't have feh installed.

对于更典型的器官图格式,您可以通过以下方式强制进行正交边缘路由:

dot test.dot -Tpng -Gsplines=ortho>test_output.png

最后,这是输出

draw_networkx 的输出 > p的输出

draw_graphviz 的输出 >

的输出

dot的输出,不带正交边

具有正交边缘的dot的输出

希望这会有所帮助.

I'm trying to create a labeled graph using networkx but am having trouble getting the nodes and labels to turn out correctly. In short, the labels don't line up over the right nodes and there are some nodes which have no edges when displayed.

First I created a graph, added nodes and edges, then added labels.

The graph data comes from a pandas DataFrame object with two columns, employee and manager names:

                emp_name             mgr_name
0        Marianne Becker                 None
1            Evan Abbott      Marianne Becker
2               Jay Page      Marianne Becker
3             Seth Reese      Marianne Becker
4         Maxine Collier      Marianne Becker

...

Each node is a name and the edges are the mgr_name to emp_name relationship.

My graph code:

import networkx as nx
G=nx.DiGraph()

#set layout
pos=nx.spring_layout(G)

#add nodes
G.add_nodes_from(df.emp_name)
G.nodes()
G.add_node('None')

#create tuples for edges
subset = df[['mgr_name','emp_name']]
tuples = [tuple(x) for x in subset.values]

#add edges
G.add_edges_from(tuples)
G.number_of_edges()

#draw graph
import matplotlib.pyplot as plt
nx.draw(G, labels = True)
plt.show()

Ideally I would have a tree-like structure with employee names as the labels for each of the nodes.

Output image is

解决方案

Networkx has a number of functions to draw graphs but also allow the user fine control over the whole process.

draw is basic and its docstring specifically mentions:

Draw the graph as a simple representation with no nodeabels or edge labels and using the full Matplotlib figure areas labels by default. See draw_networkx() for more fatured drawing that allows title, axis labels

The functions prefixed by draw_networkx followed by edges, nodes, edge_labels and edge_nodes allow finer control over the whole drawing process.

Your example worked fine when using draw_networkx.

In addition, if you are looking for an output that resembles an organogram, I would suggest the use of graphviz through networkx. Graphviz's dot is ideal for this kind of diagrams (please also see this for dot).

In what follows, I have tried to modify your code slightly to demonstrate the use of both functions:

import networkx as nx
import matplotlib.pyplot as plt
import pandas

#Build the dataset
df = pandas.DataFrame({'emp_name':pandas.Series(['Marianne Becker', 'Evan Abbott', 'Jay Page', 'Seth Reese', 'Maxine Collier'], index=[0,1,2,3,4]), 'mgr_name':pandas.Series(['None', 'Marianne Becker', 'Marianne Becker', 'Marianne Becker', 'Marianne Becker'], index = [0,1,2,3,4])})

#Build the graph
G=nx.DiGraph()   
G.add_nodes_from(df.emp_name)
G.nodes()
G.add_node('None')
#
#Over here, you are manually adding 'None' but in reality
#your nodes are the unique entries of the concatenated
#columns, i.e. emp_name, mgr_name. You could achieve this by
#doing something like
#
#G.add_nodes_from(list(set(list(D.emp_name.values) + list(D.mgr_name.values))))
#
# Which does exactly that, retrieves the contents of the two columns
#concatenates them and then selects the unique names by turning the
#combined list into a set.

#Add edges
subset = df[['mgr_name','emp_name']]
tuples = [tuple(x) for x in subset.values] 
G.add_edges_from(tuples)
G.number_of_edges()

#Perform Graph Drawing
#A star network  (sort of)
nx.draw_networkx(G)
plt.show()
t = raw_input()
#A tree network (sort of)
nx.draw_graphviz(G, prog = 'dot')
plt.show()

You could also try using graphviz's dot from the command line directly, by saving your networkx network via nx.write_dot. To do this:

From within your python script:

nx.write_dot(G, 'test.dot')

After this, from your (linux) command line and assuming that you have graphviz installed:

dot test.dot -Tpng>test_output.png
feh test_output.png #Feh is just an image viewer.
firefox test_output.png & #In case you don't have feh installed.

For a more typical organogram format, you can force orthogonal edge routing by

dot test.dot -Tpng -Gsplines=ortho>test_output.png

Finally, here are the outputs

Output of draw_networkx

Output of draw_graphviz

Output of dot without orthogonal edges

Output of dot with orthogonal edges

Hope this helps.

这篇关于显示带有标签的networkx图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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