5

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

4
  • You can't apply tight_layout on an axes, you ned to do it on a figure. Most often done using plt.tight_layout() Commented Nov 20, 2018 at 10:37
  • Hi David, thanks for the quick reply. I thought the way I do it, plot_it would be my figure. However, it seems that it isnt... (new to coding, sorry). How can I get it as my figure object so that tight_layout would work for me? Commented Nov 20, 2018 at 10:48
  • 1
    plot_it is the axes, not the figure. If you have done import matplotlib.pyplot as plt then you can simply do plt.tight_layout() Commented Nov 20, 2018 at 10:52
  • It works fine! Thanks for you help. Appreciate it! Commented Nov 20, 2018 at 10:57

1 Answer 1

8

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.