gpt4 book ai didi

python - 如何在图形绘图中添加键?

转载 作者:行者123 更新时间:2023-12-03 19:14:42 26 4
gpt4 key购买 nike

我使用 networkx 创建了一个图表.当我绘制此图时,节点标签不适合(节点名称可能很长),因此我将它们替换为数字索引。这种变通方法的问题是生成的图形更难解释,因为这些数字毫无意义。这是我的代码:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_nodes_from(['First', 'Second', 'Third'])
G.add_edges_from([('First', 'Second'), ('First', 'Third'), ('Second', 'Third')])
name2num = {name: num + 1 for num, name in enumerate(list(G.nodes))}
H = nx.relabel_nodes(G, mapping=name2num, copy=True)

fig, (ax0, ax1) = plt.subplots(1, 2)
nx.draw(G, ax=ax0, with_labels=True)
nx.draw(H, ax=ax1, with_labels=True)
graphs
我的问题是:如何在右侧的绘图中添加键?
这是我想显示的信息:
1 - First
2 - Second
3 - Third
我试图添加一个图例,但无济于事:
ax0.legend(list(name2num.values()), list(name2num.keys()))
PS : 我发现了许多与我的问题相关的线程。所提出的解决方案包括通过不同颜色对节点标签进行编码。我宁愿通过数字对节点标签进行编码。

最佳答案

而不是使用 ax.legend你可以放置一个 text box :

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_nodes_from(["First", "Second", "Third"])
G.add_edges_from([("First", "Second"), ("First", "Third"), ("Second", "Third")])
name2num = {name: num + 1 for num, name in enumerate(list(G.nodes))}
H = nx.relabel_nodes(G, mapping=name2num, copy=True)

fig, (ax0, ax1) = plt.subplots(1, 2)
nx.draw(G, ax=ax0, with_labels=True)
nx.draw(H, ax=ax1, with_labels=True)


legend_text = "\n".join(f"{v} - {k}" for k, v in name2num.items())
props = dict(boxstyle="round", facecolor="w", alpha=0.5)
ax1.text(
1.15,
0.95,
legend_text,
transform=ax1.transAxes,
fontsize=14,
verticalalignment="top",
bbox=props,
)

Network figure with text box legend

关于python - 如何在图形绘图中添加键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61155722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com