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,489
  • 4
  • 15
  • 33

2 Answers2

17

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
  • 275,208
  • 71
  • 604
  • 463
  • 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 __ A Davis Feb 13 '20 at 18:56
0

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

jake77
  • 1,892
  • 2
  • 15
  • 22