horcle_buzz
horcle_buzz

Reputation: 2161

Pythonic way of setting a label in matplotlib

I am iterating over many lists of gpx data to create a plot of cumulative training for 2016. To do so, I set up a loop as follows, where paces is a list of lists of smoothed pacing data from each gpx file and total_distances the associated distances computed from the coordinate data.

for i in range(0, len(paces)):

    if i == 0: 
        # need offset on paces from filtered data/NaN
        plt.plot(total_distances[i:i+1][0], 
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1], 
                 linewidth=.5, ls='-', color='#00FF00', label = 'all runs')
    else:
        plt.plot(total_distances[i:i+1][0], 
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1], 
                 linewidth=.5, ls='-', color='#00FF00')

If I do not use the above conditional, the label gets printed as many times as there are lists.

Any suggestions for a my pythonic way of doing this?

Upvotes: 0

Views: 73

Answers (2)

DYZ
DYZ

Reputation: 57033

Not having the actual data, I cannot test my answer, but I believe you should use this code:

for i,(distance,pace) in enumerate(zip(total_distances, paces)):
    plt.plot(distance, pace[10:],
             linewidth=.5, ls='-', color='#00FF00', 
             label='' if i else 'all runs')

Upvotes: 1

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

I don't know what pythonic means (everyone seems to understand it differently), but here is a solution which might be easier to implement.

The idea is based on the fact that matplotlib ignores labels which start with an underscore (_). So adding i underscores in the loop to the label, leaves only the first label without an underscore. This is then the label being shown.

import matplotlib.pyplot as plt

x = range(39)
y = range(39)

for i in range(len(x)-1):
    plt.plot(x[i:i+2],y[i:i+2], lw=10, label="_"*i + "label")

plt.legend(borderpad=1.5)
plt.show()

enter image description here

Upvotes: 1

Related Questions