pythonpython-3.xmatplotlib

How can I set a default zoom in a matplotlib figure?


I have the following code...

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(seed=2021)

x = np.arange(0, 200)
y = np.random.randint(1, 10, 200)

plt.plot(x, y)

plt.show()

...that generates this chart:

enter image description here

What I need is when the code start, the chart zooms by default to the last 25 records.

enter image description here

I do not want to limit the data. I want the 200 records to continue graphing, so that later I can move through the chart (with the arrow in the lower left corner) in case I want to see the historical data.

Is there a way to set a default zoom when the chart start?


Solution

  • If you do not want to hard code the left limit in xlim, you can read the shape of your x array and use this to plot only the last 25 samples:

    plt.xlim(left=x.shape[0]-25)