在matplotlib版本2.00中,如何固定图例中的行大小以匹配使用“LineCollection”的绘图中的线?

2024-09-27 07:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

在更新版本的matplotlib(2.0.0)中使用LineCollection时,绘图中的线条大小与图例中句柄的线条大小不匹配。由于句柄的行比绘图中的行大,因此需要使用handlelength,以便破折号贯穿整个循环,但问题是图例中的行仍然较大。如何使它们与图上的尺寸相同?。请参见以下示例:

lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]]
lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]]
lc1 = matplotlib.collections.LineCollection(lines1, linestyles="--")
lc2 = matplotlib.collections.LineCollection(lines2, linestyles="-.")
fig, ax = plt.subplots()
ax.add_collection(lc1)
ax.add_collection(lc2)
ax.legend([lc1,lc2],["line1","line2"],handlelength=3)

enter image description here

好吧。上一个绘图是用matplotlib版本2.0.0b4+2415.g6ad368b绘制的。现在我尝试使用matplotlib版本1.5.3,并且plot中的线和图例中的line句柄之间没有不匹配。所以matplotlib的更新版本出了问题(改变了)。在

^{pr2}$

enter image description here


Tags: 版本绘图matplotlibax句柄collections线条图例
1条回答
网友
1楼 · 发布于 2024-09-27 07:30:23

发生这种情况是因为the dash patterns now scale with line width但是与LineCollection关联的图例句柄似乎没有正确处理(看起来像一个bug)。您可以按照链接中的说明恢复旧的行为。在

classic_dashes = {
    'lines.dotted_pattern': [1, 3],
    'lines.dashdot_pattern': [3, 5, 1, 5],
    'lines.dashed_pattern': [6, 6],
    'lines.scale_dashes': False
}

with plt.rc_context(classic_dashes):
    lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]]
    lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]]
    lc1 = matplotlib.collections.LineCollection(lines1, linestyles=" ")
    lc2 = matplotlib.collections.LineCollection(lines2, linestyles="-.")
    fig, ax = plt.subplots(figsize=(6, 4))
    ax.add_collection(lc1)
    ax.add_collection(lc2)
    ax.legend([lc1,lc2],["line1","line2"])

enter image description here

相关问题 更多 >

    热门问题