0

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?

1
  • First things first, total_distances[i:i+1][0] is exactly total_distances[i] (same with paces). Commented Mar 30, 2017 at 22:44

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Good question about the term pythononic. I guess easy to read, succinct, and efficient works for me! Worked like a charm. I've seen the _ usage before, especially for unpacking values from functions, but its usage, while pythonic(!), has always confused me.
1

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

3 Comments

Only issue with this is that distance and pace are of different lengths, so not sure how to adopt that with the slicing I need to do.
They are of different length in your original code, too, aren't they?
Never mind. I did not see the slicing term on pace. My apologies!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.