问题
I've read through the following pages,
- http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html
- http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.barh
- http://matplotlib.org/users/customizing.html
- http://matplotlib.org/users/configuration.html
But I'm still having difficulties customizing the detailed settings of my graph.
For a simple code as,
#%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
df = pd.DataFrame({
'person':[x*16 for x in list('ABCDEF')],
'score1':np.random.randn(6),
'score2':np.random.randn(6),
'score3':np.random.randn(6),
'score4':np.random.randn(6),
'score5':np.random.randn(6)
})
print(df)
plt.close('all') # close all open figures
fig, ax = plt.subplots()
# X: pd.options.display.mpl_style = 'default' # cause system freeze
df.set_index(['person']).plot(kind='barh', ax = ax, width=0.85, fontsize=8)
ax.invert_yaxis()
plt.show()
This is what the result look like:
I.e., all my y-labels are cut off, and margins are too big. I've found how to tweak them here:
But I'm wondering how to do them programmatically.
Thanks
回答1:
Matplotlib creates an axes subplot object independently from your figure object. Often your subplot will not be "fit" correctly on your figure and you will need to manually adjust your subplot axes. Matplotlib now has a function plt.tight_layout()
that attempts to do this for you. More info here.
Adding the following line of code before displaying your plot should do it for you
plt.tight_layout()
plt.show()
Also you should look at this SO answer as this is a fairly similar question. Good luck!
来源:https://stackoverflow.com/questions/34300060/pandas-bar-chart-settings-customization