在较新版本的 matplotlib (2.0.0) 中使用 LineCollection 时,图中线条的大小与图例中 handle 的线条不匹配。由于 handle 的线条比图中的线条大,因此需要使用 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)
好的。之前的情节是用 matplotlib 版本 2.0.0b4+2415.g6ad368b 制作的。现在我已经尝试使用 matplotlib 版本 1.5.3,并且图中的线条和图例中的线句柄之间没有不匹配。所以新版本的 matplotlib 出现了问题(更改)。
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 = matplotlib.pyplot.subplots()
ax.add_collection(lc1)
ax.add_collection(lc2)
aaa = ax.legend([lc1,lc2],["line1","line2"])
请您参考如下方法:
发生这种情况是因为 the dash patterns now scale with line width但是与 LineCollection 关联的图例句柄似乎没有正确处理(看起来像一个错误)。您可以按照链接中的说明恢复旧行为。
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"])
