Home > Backend Development > Python Tutorial > How to Eliminate White Space on the X-Axis in Matplotlib Plots?

How to Eliminate White Space on the X-Axis in Matplotlib Plots?

DDD
Release: 2024-11-19 11:50:02
Original
685 people have browsed it

How to Eliminate White Space on the X-Axis in Matplotlib Plots?

Eliminating White Space on the X-Axis in Matplotlib Plots

In matplotlib, there is an automatic margin set at the edges of the plot to ensure that the data fits nicely within the axis spines. This margin can be desirable on the y-axis, but in some cases, it may be preferred to remove it on the x-axis.

Solution Using plt.margins()

To set the margin to 0 on the x-axis, use the following code:

plt.margins(x=0)  # Context-dependent syntax
ax.margins(x=0)  # Explicitly set margin on specified axis
Copy after login

Alternatively, to remove the margin on both axes throughout the script, use:

plt.rcParams['axes.xmargin'] = 0
plt.rcParams['axes.ymargin'] = 0
Copy after login

For a permanent solution, modify the matplotlib rc file:

axes.xmargin : 0
axes.ymargin : 0
Copy after login

Example Using Seaborn

import seaborn as sns
import matplotlib.pyplot as plt

sns.load_dataset('tips').plot(ax=ax1, title='Default Margin')
sns.load_dataset('tips').plot(ax=ax2, title='Margins: x=0')
ax2.margins(x=0)
Copy after login

Solution Using plt.xlim()

Alternatively, you can manually set the limits of the axes using plt.xlim():

plt.xlim(min(dates), max(dates))  # Set x-axis limits to remove white space
Copy after login

This will adjust the plot to eliminate any white space between the start and end of the x-axis.

The above is the detailed content of How to Eliminate White Space on the X-Axis in Matplotlib Plots?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template