Matplotlib padding between plot and axis

2020-07-10 11:39发布

问题:

I am trying to do a matplolib figure with some padding between the axis and the actual plot.

Here is my example code :

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1)

x = np.linspace(0, 1)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)

plt.plot(x, y, 'r')
plt.grid(True)


plt.show()

And here is what I am trying to get :

回答1:

In your case, it's easiest to use ax.margins(some_percentage) or equivalently plt.margins(some_percentage).

For example:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.linspace(0, 1)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)

ax.plot(x, y, 'r')
ax.grid(True)
ax.margins(0.05) # 5% padding in all directions

plt.show()



回答2:

you can set the limits of the plot with xlim and ylim. See here