pythonmatplotlib

How to reduce horizontal padding in this matplotlib plot?


I'm trying to eliminate horizontal padding of a Matplotlib plot. Here is the script:

import numpy as np, matplotlib.pyplot as plt

a = np.random.rand(100)
plt.figure(figsize=(12, 6), dpi=100)
plt.tight_layout()
plt.plot(a)
plt.show()

The result contains a lot of horizontal padding between the plot and the window:

enter image description here

I tried this alternative, but the result was the same:

import numpy as np, matplotlib.pyplot as plt

a = np.random.rand(100)
fig, ax = plt.subplots()
fig.set_dpi(100)
fig.set_size_inches(12, 6)
ax.autoscale_view('tight')
ax.plot(a)
plt.show()

Is there a simple solution to this problem?


Solution

  • Please add after ax.plot(a).

    To remove horizontal padding

    ax.margins(x=0)

    To remove padding in both x and y

    ax.margins(0)

    Or to remove horizontal padding

    ax.set_xlim(0, len(a)-1)

    To shrink margins, please use before plt.show()

    fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.05)

    Or replace fig, ax = plt.subplots(figsize=(12, 6), dpi=100)

    fig, ax = plt.subplots(figsize=(12,6), dpi=100, constrained_layout=True)

    Output:

    enter image description here