Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting multiple axvspan labels as one element in legend

I am trying to set up a series of vertical axis spans to symbolize different switching positions at different times. For example, in the figure below, switching position 1 (green) happens quite a few times, alternating between other positions.

Switching positions symbolized by axvspan plots

I plot these spans running a for loop in a list of tuples, each containing the initial and final indexes of each interval to plot the 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")

This function is then called upon another one, that plots the shades for each different switching position:

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()

Doing so with the code snippets I've put here (not the best code, I know - I'm fairly new in Python!) the legend ends up having one item for each interval, and that's pretty awful. This is how it looks:

I'd like to get a legend with only 7 items, each for a single color in my plot of axvspans. How can I proceed to do so? I've searched quite extensively but haven't managed to find this situation being asked before. Thank you in advance for any help!!

like image 782
Sergio Avatar asked Jun 19 '17 14:06

Sergio


1 Answers

A small trick you can apply using the fact that labels starting with "_" are ignored:

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

Thereby a label is only created for the case where i==0.

like image 71
ImportanceOfBeingErnest Avatar answered Sep 21 '22 09:09

ImportanceOfBeingErnest