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
  • 30,962
  • 25
  • 85
  • 135
tyasird
  • 926
  • 1
  • 12
  • 29

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)
Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
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
  • 926
  • 1
  • 12
  • 29
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
  • 4,979
  • 2
  • 15
  • 31