如何在使用networkx和matplotlib时显示x轴和y轴?

3

嗨,我正在尝试使用networkx和matplotlib绘制图形,但是尽管将轴设为“on”,并添加了x/y轴的极限值,但我的x和y轴仍未显示。

我尝试实施其他人的代码以查看轴是否会显示,但没有运气。

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from(
        [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
         ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
               'D': 0.5714285714285714,
               'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
                    for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), 
node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

以下是另一个线程中的一些示例代码:如何在Python中使用NetworkX绘制有向图?

我甚至尝试了他/她提供的代码,但我从他的截图中可以看到他能够显示轴,但在我的端上却没有任何显示。

这是我的输出结果 没有错误信息。

2个回答

13

在一些早期版本的networkx中,刻度和标签没有被设置。现在它们被设置了 - 主要是因为坐标轴上的数字很少具有特殊含义。

但是如果它们确实具有特殊含义,您需要再次打开它们。

fig, ax = plt.subplots()
nx.draw_networkx_nodes(..., ax=ax)

#...

ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)

输入图片描述


非常感谢,现在它可以工作了。是的,我明白这个数字并没有太多意义。这只是为了我的可视化,特别是使用pos来确定放置节点的位置。 - Onyx

5

这个问题很古老了,但我对已有的解决方案还有疑问。

nx.draw_networkx_nodesnx.draw 不完全相同(尤其是默认不画出边)。但是使用 draw 单独不能显示坐标轴。

加上 plt.limits("on") 可以让使用 draw(及其语法)时显示坐标轴。

fig, ax = plt.subplots()
nx.draw(G,...,ax=ax) #notice we call draw, and not draw_networkx_nodes
limits=plt.axis('on') # turns on axis
ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)

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