Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

python - How to save a seaborn plot as svg or png

Hi all I have been trying to save my output chart with "plt.savefig("coeff.png")" as svg or png but what I get is only a blank picture.

Is there anyway I could get my plots exported as a picture format?

Below is my code.

# These are the (standardized) coefficients found
# when it refit using that best alpha
list(zip(X.columns, LGBMR.feature_importances_))

#Now let's make it more presentable in Pandas DataFrame and also in standard form for numbers
df_LGBM_model_coefficients = pd.DataFrame(list(zip(X_train.columns, LGBMR.feature_importances_)))
df_LGBM_model_coefficients.rename(columns={0:'Features', 1: 'Coefficients'}, inplace=True)

df_LGBM_model_coefficients = df_LGBM_model_coefficients.iloc[1:]
df_LGBM_model_coefficients = df_LGBM_model_coefficients.sort_values(by = 'Coefficients', ascending = False)

#only retain the important ones.
df_LGBM_model_coefficients_top_10 = df_LGBM_model_coefficients.head(10)



plt.figure(figsize=(12,12))
sns.set_style('whitegrid')
sns.set(font_scale=0.8)

ax = sns.barplot(x = 'Coefficients',y='Features', data = df_LGBM_model_coefficients_top_10)
ax.set_title("LGBMR Top 10 Features and their coefficients")

for p in ax.patches:
    ax.annotate("%.1f" % p.get_width(), (p.get_x() + p.get_width(), p.get_y() + 0.8), xytext=(5, 10), textcoords='offset pixels')
plt.show()
plt.savefig("coeff.png")
question from:https://stackoverflow.com/questions/65896805/how-to-save-a-seaborn-plot-as-svg-or-png

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Swap the last two lines of your code. Place the plt.savefig("coeff.png") line before plt.show() line.

plt.savefig("coeff.png")
plt.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...