Computer >> Computer tutorials >  >> Programming >> Python

Preserve padding while setting an axis limit in matplotlib


To preserve padding while setting axis limit, we can avoid using the tight layout, i.e., plt.rcParams["figure.autolayout"] = False.

Steps

  • Set the figure size and adjust the padding between and around the subplots.

  • Create x and y data points using numpy.

  • Plot x and y data points using plot() method.

  • Set x and y axes limit.

  • To display the figure, use Show() method.

Example

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-10, 10, 100)
y = np.sin(x) ** 2

plt.plot(x, y)

plt.xlim([0, max(x)+0.125])
plt.ylim([0, max(y)+0.125])

plt.show()

Output

It will produce the following output −

Preserve padding while setting an axis limit in matplotlib