python-3.x - 将多个 axvspan 标签设置为图例中的一个元素

标签 python-3.x matplotlib

我正在尝试设置一系列垂直轴跨度来象征不同时间的不同切换位置。例如,在下图中,切换位置 1(绿色)发生了很多次,在其他位置之间交替。

Switching positions symbolized by axvspan plots

我在元组列表中绘制运行 for 循环的这些跨度,每个包含每个间隔的初始和最终索引以绘制 axvspan。

def plotShades(timestamp, intervals, colour):
    for i in range(len(intervals)):
        md.plt.axvspan(timestamp[intervals[i][0]], timestamp[intervals[i][1]], alpha=0.5, color=colour, label="interval")

然后调用另一个函数,绘制每个不同开关位置的阴影:
def plotAllOutcomes(timestamp, switches):
    #switches is a list of 7 arrays indicating when the switcher is at each one of the 7 positions. If the array has a 1 value, the switcher is there. 0 otherwise.

    colors = ['#d73027', '#fc8d59', '#fee08b', '#ffffbf', '#d9ef8b', '#91cf60', '#1a9850']     
    intervals = []        

    for i in range(len(switches)):
        intervals.append(getIntervals(switches[i], timestamp))
        plotShades(timestamp, intervals[i], colors[i])    
        md.plt.legend()

使用我放在这里的代码片段(不是最好的代码,我知道 - 我在 Python 中相当新!)图例最终每个间隔都有一个项目,这非常糟糕。这是它的外观:



我想得到一个只有 7 个项目的图例,每个项目都用于我的 axvspans 图中的一种颜色。我怎样才能继续这样做?我已经进行了相当广泛的搜索,但没有设法找到之前询问过的这种情况。预先感谢您的任何帮助!!

最佳答案

您可以使用标签以 "_" 开头的事实来应用一个小技巧。被忽略:

plt.axvspan( ... , label =  "_"*i + "interval")

因此,仅针对 i==0 的情况创建标签。 .

关于python-3.x - 将多个 axvspan 标签设置为图例中的一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44632903/

相关文章:

python - 在 Python 中对整个应用程序进行回归测试

Python异常处理: Is there a method to know what type of exceptions my code can possibly throw?

Matplotlib:带有边缘颜色但没有面部颜色的颜色图的散点图

python - 在 python 中绘制带有邻接矩阵和坐标列表的连接图

python - 用 matplotlib 绘图 : TypeError: float() argument must be a string or a number

Python 3.6.3 Idle 正在终止当前 session

python - 如何始终获得正输出?

python - 如何在Python中将十六进制代码行(\x)获取到十六进制地址(0x)?

python - 值错误 : scatter requires x column to be numeric

python - matplotlib.pyplot 和 numpy 中的递减