0

Is there a way to remove the extra space between the begin (end) of plot and the begin (end) of data range in matplotlib? I want the grids to be limited to the data range, but I cannot remove these extra spaces. See example:

import matplotlib.pyplot as plt
import numpy as np

x=np.arange(0,4*np.pi,0.1)
fig, ax = plt.subplots(figsize=(6, 8))
ax.plot(x,np.sin(x), color="black")
ax.yaxis.grid(True, color ="gray", linewidth=0.5)
ax.hlines(y=0.5, color=[66/255, 176/255, 255/255], linestyle='--', xmin=0, xmax=12, linewidth=2)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
plt.show()

I highlight the extra space in red:

enter image description here

I cannot find a way to fit the grid interval in the data or the blue horizontal line ranges. I tried to reduce the xmin argument in the later case but it didn't work. The documentation of ax.yaxis.grid shows only 3 arguments for this method (b, which,**kwargsLine2D), none of them looks to be related to the data range.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Lucas
  • 1,166
  • 2
  • 14
  • 34

0 Answers0