gpt4 book ai didi

matplotlib - 为 fill_between() 段的不同颜色添加图例

转载 作者:行者123 更新时间:2023-12-02 00:47:16 24 4
gpt4 key购买 nike

我正在创建一个当前看起来像这样的“事件图”:

enter image description here

但是,我不知道如何为每个颜色组添加图例。这就是现在创建情节的方式:

handles = dict()

for i, channel_events in enumerate(channel_event_list):

for event in channel_events:
start = event[0]
end = event[1]
y = (i, i + padding)

c = 'red' if colors is None else colors[i]

h = plt.fill_between([start, end], y[0], y2=y[1], color=c)

if c not in handles:
handles[c] = list()
handles[c].append(h)

我以为我可以使用 fill_between() 的输出作为句柄,但似乎我错了。

那么只为此处的颜色获取图例的最简单方法是什么?

最佳答案

要从 fill_between 调用或任何其他 PolyCollection 创建图例句柄,您可以使用此 PolyCollection 并将其提供给图例。

import matplotlib.pyplot as plt

h = plt.fill_between([1,2,3],[1,3,4], y2=[1,2,3], color="#c1009b")

plt.legend(handles=[h], labels=["MyLabel"])
plt.show()

enter image description here

一种更简单的方法是直接使用 fill_between 图(就像任何其他图一样)的 label 参数来创建自动图例条目。

import matplotlib.pyplot as plt

plt.fill_between([0,1,2],[4,3,4], y2=[3,2.5,3], color="#c1009b", label="Label1")
plt.fill_between([0,1,1.3],[1,2,0.5], y2=[0,-1,0], color="#005ec1", label="Label2")
plt.fill_between([2,3,4],[0.5,1,0], y2=[-1,-1,-1.5], color="#005ec1", label="_noLabel")

plt.legend()
plt.show()

enter image description here

关于matplotlib - 为 fill_between() 段的不同颜色添加图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42836778/

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