【问题标题】:Setting multiple axvspan labels as one element in legend将多个 axvspan 标签设置为图例中的一个元素
【发布时间】:2017-06-19 14:12:17
【问题描述】:

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

我将这些跨度绘制在一个元组列表中运行一个 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()

使用我放在这里的代码 sn-ps 这样做(不是最好的代码,我知道 - 我在 Python 中相当新!)传说最终每个间隔都有一个项目,这非常糟糕。看起来是这样的:

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

【问题讨论】:

    标签: python-3.x matplotlib


    【解决方案1】:

    您可以应用一个小技巧,即忽略以"_" 开头的标签:

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

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

    【讨论】:

    • 非常感谢!!这是一个很棒的技巧,对我的其余代码也非常有用。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多