Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tight_Layout: Attribute Error . 'AxesSubplot' object has no attribute 'tight_layout'

I want to plot a stacked-bar graph with data coming from two separate dataframes in pandas (My_means and My_stds). I am using Python 3.7.

The plotting call works fine, however, the labels are cut-off. Setting tight_layout does not help me and generates an "Attribute Error: 'AxesSubplot' object has no attribute 'tight_layout'". What does this mean and how do I overcome this?

I haven´t found any problems related to this error, so I assume I am doing something rather stupid...

Here is my code:

My_means= ratios.pivot_table('Data', 'Sample ID', 'User ID', aggfunc= np.mean)
My_stds= ratios.pivot_table('Data', 'Sample ID', 'User ID', aggfunc= np.std)
plot_it = My_means.plot(kind='bar', color=stack_cols, stacked=True, yerr=My_stds, capsize=3, title='Just some graph')
plot_it.tight_layout()

Thanks for your help! Jazz

like image 979
JazzyJazz Avatar asked Jan 28 '23 03:01

JazzyJazz


1 Answers

My_means.plot(…) returns an axes object. Whereas tight_layout requires a figure object. There are a number of different approaches you can use:

Perhaps the simplest one would be to use plt.tight_layout() which works on the current figure:

import matplotlib.pyplot as plt
# Your plotting code here
plt.tight_layout()

Alternatively, you can create the figure and axes beforehand, pass the axes as an argument to plot and then use tight_layout on the figure object:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
plot_it = My_means.plot(kind='bar', ax=ax, …)

fig.tight_layout()
like image 167
DavidG Avatar answered Feb 17 '23 09:02

DavidG