0

I use pandas DataFrame to show feature importance plot.

However some features doesn't fit to ylabel due to their long names.

data = pd.DataFrame({'feature': feature,'importance': importance}).sort_values(by='importance', ascending=False)[0:10]
ax = data.plot(kind='barh', x='feature', y='importance')
ax.figure.savefig(filename)

enter image description here

Dharman
  • 26,923
  • 21
  • 73
  • 125
tyasird
  • 828
  • 1
  • 11
  • 26

4 Answers4

1

You can adjust the left parameter with matplotlib.pyplot.subplots_adjust:

from matplotlib import pyplot as plt

ax = data.plot(kind='barh', x='feature', y='importance')
plt.subplots_adjust(left=0.3)  # call after drawn the plot, but before showing or saving
ax.figure.savefig(filename)
np8
  • 20,899
  • 9
  • 73
  • 87
0

Use plt.tight_layout() before saving, but after plotting, as follows:

import matplotlib.pyplot as plt

ax = data.plot(kind='barh', x='feature', y='importance')

plt.tight_layout()

ax.figure.savefig(filename)

More details in another thread: https://stackoverflow.com/a/17390833/13240220

0

I found the solution: bbox_inches

ax.figure.savefig(filename, bbox_inches='tight')

enter image description here

tyasird
  • 828
  • 1
  • 11
  • 26
0

Use constrained_layout; it is similar to tight_layout, but more flexible:

fig, ax = plt.subplots(constrained_layout=True)
data.plot(kind='barh', x='feature', y='importance', ax=ax)
Jody Klymak
  • 3,769
  • 2
  • 13
  • 25