6

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 :

plot with x and y shift

Anthony Lethuillier
  • 1,439
  • 4
  • 14
  • 32

2 Answers2

14

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()

enter image description here

Joe Kington
  • 258,645
  • 67
  • 583
  • 455
  • 1
    Note the margins setting applies to autoscale; if this has been turned off, it needs to be re-enabled for margins to have an effect: `ax.autoscale(True)` – SpinUp Feb 13 '20 at 18:56
1

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

jake77
  • 1,584
  • 2
  • 12
  • 21