3

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
  • 587
  • 7
  • 22

2 Answers2

6

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
  • 469
  • 5
  • 7
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,179
  • 1
  • 7
  • 26