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

标签 python matplotlib networkx

您好,我正在尝试使用 networkx 和 matplotlib 绘制图形,但是,尽管将轴设置为“打开”并向轴添加 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()

来自另一个线程的一些示例代码:how to draw directed graphs using networkx in python?

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

Here is the output on my end 没有错误信息。

最佳答案

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

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

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

#...

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

enter image description here

关于python - 使用networkx和matplotlib时如何使x和y轴出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56994061/

相关文章:

python - 如何监控特定网站 CSS 的变化?

python - Revit 链接内的 Revit 链接的 ActiveProjectLocation.Name

python - 如何引用列表绘制 Pandas 数据框的值(索引问题)?

python - NetworkX - 如何从 Shapefile 创建 MultiDiGraph?

python - 如何从嵌套列表中提取特定项目并附加到新列?

python - 使用 K-D 树的 NetworkX 随机几何图实现

python - 在 numpy 数组中围绕定义的对角线设置递增值

python - 使用 python 在服务器端处理 Markdown 并在客户端渲染

python - 为数据框中的每一行创建条形图的子图

python - 在 python 中绘制自定义函数