End plot at last data point in pyplot time series
<p>I have a pyplot chart that looks a bit like this:</p>

<p><a href="https://i.stack.imgur.com/Takm8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Takm8.png" alt="The chart in question"></a></p>

<p>How do I get the red and blue lines to stop at their last data point (May 13th and May 19th, respectively) instead of continuing a horizontal line to the far right?</p>

<p>Each line is composed of points with an increasing <code>x</code> value at each successive time <code>t</code>. The data is taken from snapshots at times in the past, hence they stop at different times.</p>

<p>I've tried my best google-fu, but not really found anything useful, short of manually drawing all the bits of the line.</p>

<p>Here's the code that generates the chart, if it helps:</p>

<pre><code>import sys
import json
from datetime import datetime
import itertools
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

if __name__ == '__main__':
    colours = itertools.cycle(['r', 'b', 'g', 'm', 'c', 'y', 'k'])

    # A bit of faff for clean printing with globbed arguments:
    filenames = [name.split('.')[0] for name in sys.argv[1:]]

    fig = plt.figure()

    axes = plt.axes()
    axes.set_ylabel('Events')

    for file in filenames:
        data = json.loads(open(file + '.json').read())['results']['data']

        # Unzip to a tuple of lists ([x], [y])
        x, y = zip(*[(datetime.utcfromtimestamp(int(d['t']/1000)), d['x']) for d in data])
        axes.plot(x, y, colours.next(), label=file)

    fig.autofmt_xdate()
    plt.savefig('plot_{0}.png'.format('_'.join(filenames)))
</code></pre>