Lucas Churchman
Lucas Churchman

Reputation: 1

module 'matplotlib.pyplot' has no attribute 'tight_layout'

For some reason the tight_layout() function from pyplot stopped working on machine. I've been using it in one of my programs for months and its decided to stop working out of the blue (I realize I probably made an accidental change somewhere that's caused this but I don't know where it would be). Any other matplotlib or pyplot function works a-okay, but whenever I call tight_layout I get

module 'matplotlib.pyplot' has no attribute 'tight_layout'

Which is obviously not true.

For example, even this code coming from the offical tight_layout guide (https://matplotlib.org/users/tight_layout_guide.html)

from matplotlib import pyplot as plt

plt.rcParams['savefig.facecolor'] = "0.8"

def example_plot(ax, fontsize=12):
     ax.plot([1, 2])
     ax.locator_params(nbins=3)
 ax.set_xlabel('x-label', fontsize=fontsize)
 ax.set_ylabel('y-label', fontsize=fontsize)
 ax.set_title('Title', fontsize=fontsize)

plt.close('all')
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
plt.tight_layout()

will produce the error.

I've reinstalled the matplotlib package a couple times and reinstalled my IDE (Spyder) to no avail. I'm pretty clueless at this point so any input would be great.

Upvotes: 0

Views: 2666

Answers (2)

Hoang 6494
Hoang 6494

Reputation: 1

When you attempt to import Matplotlib and use tight_layout like a function, this error occurs. So you can fix your error by changing your import Matplotlib as plt to import Matplotlib.pyplot as plt.

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339220

I don't think some module will suddenly loose its methods. You may check for the method being in the code,

import matplotlib.pyplot as plt
with open(plt.__file__[:-1],"r") as f:
    for line in f:
        if "tight_layout" in line:
            print(line)

This should result in two lines being printed.

def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None):
# and 
fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)

If this is not the case, check when the file was last changed

import os
from datetime import datetime

f = datetime.fromtimestamp(os.path.getmtime(plt.__file__[:-1]))
print("Modification time: {}".format(f))

and compare to any actions you took, installing, uninstalling, modifying code etc.

Upvotes: 2

Related Questions