Setting multiple axvspan shortcuts as one item in legend

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

Switching positions symbolized by axvspan plots

I draw these gaps starting a for loop on a list of tuples, each containing the start and end indices of each interval to build an 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")

      

Then another function is called, which displays the hues for each switch 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()

      

Having done this with the code snippets I've put here (not the best code, I know - I'm pretty new to Python!), The legend ends up having one element for each interval, which is pretty awful. This is how it looks:

I would like to get a legend with 7 points each for one color in my axvspans plot. How can i do this? I've searched quite extensively, but I haven't been able to find this situation before. Thanks in advance for any help!

+3


source to share


1 answer


A little trick you can apply using the fact that labels starting with "_"

are ignored:

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

      



Thus, the label is created only for the case when i==0

.

+2


source







All Articles