close

How can I change the x axis in matplotlib so there is no white space?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can I change the x axis in matplotlib so there is no white space in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How can I change the x axis in matplotlib so there is no white space?

  1. How can I change the x axis in matplotlib so there is no white space?

    If you only want to remove the margin on one side but not the other, e.g. remove the margin from the right but not from the left, you can use set_xlim() on a matplotlib axes object.

  2. change the x axis in matplotlib so there is no white space

    If you only want to remove the margin on one side but not the other, e.g. remove the margin from the right but not from the left, you can use set_xlim() on a matplotlib axes object.

Method 1

There is an automatic margin set at the edges, which ensures the data to be nicely fitting within the axis spines. In this case such a margin is probably desired on the y axis. By default it is set to 0.05 in units of axis span.

To set the margin to 0 on the x axis, use

plt.margins(x=0)

or

ax.margins(x=0)

In case you want to get rid of the margin in the whole script, you can use

plt.rcParams['axes.xmargin'] = 0

at the beginning of your script (same for y of course). If you want to get rid of the margin entirely and forever, you might want to change the according line in the matplotlib rc file:

axes.xmargin : 0
axes.ymargin : 0

Example

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset('tips')

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
tips.plot(ax=ax1, title='Default Margin')
tips.plot(ax=ax2, title='Margins: x=0')
ax2.margins(x=0)
enter image description here

Alternatively, use plt.xlim(..) or ax.set_xlim(..) to manually set the limits of the axes such that there is no white space left.

Method 2

If you only want to remove the margin on one side but not the other, e.g. remove the margin from the right but not from the left, you can use set_xlim() on a matplotlib axes object.

import seaborn as sns
import matplotlib.pyplot as plt
import math

max_x_value = 100

x_values = [i for i in range (1, max_x_value + 1)]
y_values = [math.log(i) for i in x_values] 

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
sn.lineplot(ax=ax1, x=x_values, y=y_values)
sn.lineplot(ax=ax2, x=x_values, y=y_values)
ax2.set_xlim(-5, max_x_value) # tune the -5 to your needs
enter image description here

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read