这是一个衍生问题,与[Set line colors]中给出的答案有关 根据颜色图](https://stackoverflow.com/questions/19868548/set-line- 颜色(根据colormap),其中有一个伟大的解决方案是建议绘图 根据颜色条用颜色表示的几行(参见代码和输出图像 以下)。 我有一个列表,其中存储与每一条打印线相关联的字符串,如下所示:
legend_list = ['line_1', 'line_2', 'line_3', 'line_4']
我想将这些字符串作为图例添加到一个框中(其中第一个字符串 对应于图右上角的第一条绘制线(以此类推) 情节。我怎么能这么做? 如果有必要的话,我可以不使用“LineCollection”,但我必须这样做 保留colorbar和与之关联的每行的颜色。
Code and output
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()
@ubuntu的答案是正确的方法,如果你有少量的行。(和 如果你想添加一个传奇,你可能会这样做!) 不过,为了显示另一个选项,您仍然可以使用“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()