I would like to change the aspect ratio of plots generated from the shap
library.
Minimal reproducble example plot below:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
import shap
boston = load_boston()
regr = pd.DataFrame(boston.data)
regr.columns = boston.feature_names
regr['MEDV'] = boston.target
X = regr.drop('MEDV', axis = 1)
Y = regr['MEDV']
fit = LinearRegression().fit(X, Y)
explainer = shap.LinearExplainer(fit, X, feature_dependence = 'independent')
shap_values = explainer.shap_values(X)
shap.summary_plot(shap_values, X)
I'm able to save the figure using this:
fig = shap.summary_plot(shap_values, X, show = False)
plt.savefig('fig_tes1.svg', bbox_inches='tight',dpi=100)
But I'm unable to change the aspect ratio, for example for it to be 4:3 width to height, for example.
I have read that I should be able to
plt.gcf()
but for me, that just creates a new, blank plot.
<Figure size 432x288 with 0 Axes>
CodePudding user response:
Update
Use plot_size
parameter:
shap.summary_plot(shap_values, X, plot_size=[8,6])
print(f'Size: {plt.gcf().get_size_inches()}')
# Output
Size: [8. 6.]
You can modify the size of the figure using set_size_inches
:
...
shap.summary_plot(shap_values, X)
# Add this code
print(f'Original size: {plt.gcf().get_size_inches()}')
w, _ = plt.gcf().get_size_inches()
plt.gcf().set_size_inches(w, w*3/4)
plt.tight_layout()
print(f'New size: {plt.gcf().get_size_inches()}')
plt.savefig('fig_tes1.svg', bbox_inches='tight',dpi=100)
Output:
Original size: [8. 6.7]
New size: [8. 6.]
Note: it's probably better to modify the width rather than the height:
_, h = plt.gcf().get_size_inches()
plt.gcf().set_size_inches(h*4/3, h)