Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib padding between plot and axis

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

like image 213
Anthony Lethuillier Avatar asked Oct 01 '15 10:10

Anthony Lethuillier


People also ask

How do you add padding between subplots?

We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.

How do you make Xticks evenly spaced?

To make xticks evenly spaced despite their values, we can use set_ticks() and set_ticklabels() methods.

How do I change the axis spacing in matplotlib?

MatPlotLib with Python To adjust the spacing between the edge of the plot and the X-axis, we can use tight_layout() method or set the bottom padding of the current figure. Set the figure size and adjust the padding between and around the subplots.

Do You Need %Matplotlib inline?

The only reason %matplotlib inline is used is to render any matplotlib diagrams even if the plt. show() function is not called. However, even if %matplotlib inline is not used, Jupyter will still display the Matplotlib diagram as an object, with something like matplotlib. lines.


2 Answers

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

like image 138
Joe Kington Avatar answered Oct 23 '22 13:10

Joe Kington


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

like image 27
jake77 Avatar answered Oct 23 '22 11:10

jake77