如何更改networkx/matplotlib绘图的属性?

7

NetworkX包含函数,可使用matplotlib绘制图形。这是一个示例,使用了伟大的IPython笔记本(使用ipython3 notebook --pylab inline启动):

enter image description here

不错,作为一个开始。但是我如何影响绘图的属性,比如颜色、线宽和标签?我以前没有使用过matplotlib。

http://networkx.lanl.gov/reference/drawing.html - 你需要使用 draw_networkx_edgesdraw_networkx_nodes 函数。 - job
1个回答

12

IPython是一个非常好的工具,用于查询函数(和对象)的功能。如果您键入

[1]: import networkx as nx
[2]: nx.draw?

您看到了

Definition: nx.draw(G, pos=None, ax=None, hold=None, **kwds)

**kwds: optional keywords
   See networkx.draw_networkx() for a description of optional keywords.

如果您输入以下内容

[10]: nx.draw_networkx?

你将看到

node_color: color string, or array of floats
edge_color: color string, or array of floats
width: float
   Line width of edges (default =1.0)
labels: dictionary
   Node labels in a dictionary keyed by node of text labels (default=None)

因此,掌握了这些信息,并进行一些实验后,就不难得出:

import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import string

G = nx.generators.erdos_renyi_graph(18, 0.2)
nx.draw(G,
        node_color = np.linspace(0,1,len(G.nodes())),
        edge_color = np.linspace(0,1,len(G.edges())),
        width = 3.0,
        labels = {n:l for n,l in zip(G.nodes(),string.ascii_uppercase)}
        )
plt.show()

这将产生

在此输入图片描述


1
谢谢。我得试着实验一下。我特别感兴趣的是将边缘权重映射到线宽上。 - clstaudt
4
要实现可变线条宽度,我认为您需要针对每个线条宽度分别调用nx.draw_networkx_edges。参见此处的示例。他们在该示例中更改了线条样式,但是也展示了您如何更改线条宽度。 - unutbu
很好,你不仅回答了问题,还解释了如何获得答案。 - Lukas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接