python - 绘制表示边权重的连续宽度图例

标签 python matplotlib networkx legend graph-theory

我正在使用networkx包创建一个网络图,并且边缘的宽度是连续的(在本例中它是一个相关值),效果很好。但我在为此创建一个传奇时遇到了麻烦。

在我通过连续灰色颜色图可视化相关值之前,我将颜色条作为图例。我现在的问题是:是否有可能创建类似颜色条的东西,但对于我的边缘宽度?我认为它应该看起来像一个长三角形。

最佳答案

实现这一目标的一种方法如下。请注意,它不会产生您所描述的连续三角形,而是评估等距点处的边缘宽度并将其添加到离散图例中。

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import networkx as nx

# Number of lines to include in legend
NUM_INTERVALS = 6

# Set up random graph with random weights
G = nx.Graph()
for i in range(50):
    G.add_edge(random.randint(1,10), random.randint(1,10), weight = random.uniform(0,8))
pos = nx.circular_layout(G)

# Get weights from graph
weights = [G[s][e]['weight'] for s, e in G.edges()]

# Get evenly distributed points over range of weights
lines = np.linspace(min(weights), max(weights), NUM_INTERVALS)

# Create lines from the weights
line2ds = [Line2D([],[], linewidth=width, color='black') for width in lines]

# Draw graph
nx.draw(G, pos, width=weights)

# Draw legend (rounding decimals to 2 places)
legend2 = plt.legend(line2ds, np.round(lines, decimals=2), bbox_to_anchor=(0, 1))

输出:

enter image description here

关于python - 绘制表示边权重的连续宽度图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60148709/

相关文章:

python - 对列表中的文件进行排序

python - IndexError:索引1080超出了尺寸为1080的轴0的范围

python - scipy gaussian_kde 根据使用的方法(权重与无权重)产生不同的结果

python - 如何使用 matplotlib 在同一行中绘制多个图形?

python - 如何使用 Matplotlib (Python 2.7) 和您自己的数据创建烛台图表

python - Networkx:寻找到图中多个节点之一的最短路径

python - 如何修改约翰逊的基本循环算法以限制最大循环长度?

python - 将 f.write 文件保存到与找到的 Askopenfilename 相同的目录中

Python:正则表达式删除字母前面的零?

python - 绘制对数分级网络度分布