gpt4 book ai didi

python - 将图例添加到 LineCollection 图中

转载 作者:太空狗 更新时间:2023-10-29 21:22:21 26 4
gpt4 key购买 nike

这是与Set line colors according to colormap中给出的答案相关的派生问题其中提出了一个很好的解决方案,即根据颜色条绘制多 strip 有颜色的线条(请参见下面的代码和输出图像)。

我有一个列表,其中存储了与每条标绘线关联的字符串,如下所示:

legend_list = ['line_1', 'line_2', 'line_3', 'line_4']

我想将这些字符串作为图例添加到绘图右上角的框中(其中第一个字符串对应于第一条绘制线等)。我怎么能这样做?

如果有必要,我愿意不使用 LineCollection,但我需要保持颜色条和与其关联的每条线的颜色。


代码和输出

import numpy
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

# The line format you curently have:
lines = [[(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)],
[(0, 1, 2, 3, 4), (0, 1, 2, 3, 4)],
[(0, 1, 2, 3, 4), (8, 7, 6, 5, 4)],
[(4, 5, 6, 7, 8), (0, 1, 2, 3, 4)]]

# Reformat it to what `LineCollection` expects:
lines = [zip(x, y) for x, y in lines]

z = np.array([0.1, 9.4, 3.8, 2.0])

fig, ax = plt.subplots()
lines = LineCollection(lines, array=z, cmap=plt.cm.rainbow, linewidths=5)
ax.add_collection(lines)
fig.colorbar(lines)

# Manually adding artists doesn't rescale the plot, so we need to autoscale
ax.autoscale()

plt.show()

enter image description here

最佳答案

如果您的行数较少,@unutbu 的回答是正确的方法。 (如果您想添加图例,您大概会这样做!)

只是为了显示另一个选项,您仍然可以使用 LineCollection,您只需要为图例使用“代理艺术家”:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.lines import Line2D

# The line format you curently have:
lines = [[(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)],
[(0, 1, 2, 3, 4), (0, 1, 2, 3, 4)],
[(0, 1, 2, 3, 4), (8, 7, 6, 5, 4)],
[(4, 5, 6, 7, 8), (0, 1, 2, 3, 4)]]

# Reformat it to what `LineCollection` expects:
lines = [tuple(zip(x, y)) for x, y in lines]

z = np.array([0.1, 9.4, 3.8, 2.0])

fig, ax = plt.subplots()
lines = LineCollection(lines, array=z, linewidths=5,
cmap=plt.cm.rainbow, norm=plt.Normalize(z.min(), z.max()))
ax.add_collection(lines)
fig.colorbar(lines)

# Manually adding artists doesn't rescale the plot, so we need to autoscale
ax.autoscale()

def make_proxy(zvalue, scalar_mappable, **kwargs):
color = scalar_mappable.cmap(scalar_mappable.norm(zvalue))
return Line2D([0, 1], [0, 1], color=color, **kwargs)
proxies = [make_proxy(item, lines, linewidth=5) for item in z]
ax.legend(proxies, ['Line 1', 'Line 2', 'Line 3', 'Line 4'])

plt.show()

enter image description here

关于python - 将图例添加到 LineCollection 图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19877666/

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