6

I am struggling with saving the xgboost feature-importance plot to a file. I have created a model and plotted importance of features in my jupyter notebook-

xgb_model = xgboost.train(best_params, dtrain, num_round)
xgboost.plot_importance(xgb_model)

It shows me the feature importance plot but I am unable to save it to a file. I even looked for any save attribute in dir(xgboost.plot_importance(xgb_model)), but got nothing. Is there any way to do this?

Ankit Seth
  • 729
  • 1
  • 9
  • 23

2 Answers2

10

According the doc, xgboost.plot_importance(xgb_model) returns matplotlib Axes

therefore, you can just

ax = xgboost.plot_importance(xgb_model)
ax.figure.savefig('the-path-you-want-to-save.png')

Additional, if your loss the left and right margins for your figure, you can set the tight_layout

ax = xgboost.plot_importance(xgb_model)
ax.figure.tight_layout()
ax.figure.savefig('the-path-you-want-to-save.png')
Andrew Li
  • 539
  • 5
  • 11
0

From the documentation you see it is a matplotlib output. So you should be able to call savefig of matplotlib.

If you want to save the model, take a look at How to save & load xgboost model?.

Sparky05
  • 4,692
  • 1
  • 10
  • 27