2

I've read through the following pages,

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:

the result

I.e., all my y-labels are cut off, and margins are too big. I've found how to tweak them here:

customizing subplot

But I'm wondering how to do them programmatically.

Thanks

xpt
  • 20,363
  • 37
  • 127
  • 216
  • does calling `plt.tight_layout()` before `plt.show` work for you? – johnchase Dec 15 '15 at 22:43
  • YEP! Super!! Strange I was clicking on that from the GUI before and ended up with very weird result before. Strange. Anyway, please answer, so I can mark. Thanks. – xpt Dec 15 '15 at 22:47
  • Oh, @johnchase, do you happen to know how to disable the y-grid lines as well? I found a `ax.yaxis.set_visible(False)`, but when I try it, my y-labels are gone as well. Thanks. – xpt Dec 16 '15 at 14:56
  • Got it, it is `ax.yaxis.grid(False)` – xpt Dec 16 '15 at 14:59

1 Answers1

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!

Community
  • 1
  • 1
johnchase
  • 13,155
  • 6
  • 38
  • 64