Home > Software engineering >  How can I set a default zoom in a matplotlib figure?
How can I set a default zoom in a matplotlib figure?

Time:12-10

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?

CodePudding user response:

You can just add plt.xlim(175, 200) which sets the limit of the x axis.

CodePudding user response:

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)

  • Related