使用networkx和matplotlib时如何使x和y轴出现?

Ony*_*nyx 1 python matplotlib networkx

嗨,所以我试图使用 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()
Run Code Online (Sandbox Code Playgroud)

来自另一个线程的一些示例代码:如何在 python 中使用 networkx 绘制有向图?

我什至尝试了他提供的他/她的代码,我什至可以从他的屏幕截图中看到他能够显示轴,但从我的角度来看,我什么也没得到。

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

Imp*_*est 8

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

但如果他们这样做,您需要再次打开它们。

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

#...

ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


小智 6

相当旧的一个,但我对接受的解决方案有疑问。 nx.draw_networkx_nodes不完全相同nx.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)
Run Code Online (Sandbox Code Playgroud)