如何在Matplotlib子图中并排绘制SHAP summary_plot?
如何将SHAP的两种summary_plot合并到同一Matplotlib画布的子图中
SHAP的shap.summary_plot()默认会自动创建新的绘图窗口,且不支持直接传入ax参数指定子图,这导致你的代码会生成两个独立窗口。下面提供两种可行的解决方法:
方法1:使用SHAP的独立绘图函数(推荐,适用于SHAP 0.40+版本)
SHAP较新版本提供了shap.plots.bar()和shap.plots.beeswarm()两个独立函数,它们支持传入ax参数来指定绘图的子图轴对象,完美适配Matplotlib的subplot布局。
修改后的代码如下:
import pandas as pd import shap from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder mylabel = LabelEncoder() data = pd.read_csv("https://raw.githubusercontent.com/krishnaik06/Multiple-Linear-Regression/master/50_Startups.csv") data['State'] = mylabel.fit_transform(data['State']) model = RandomForestRegressor() y = data['Profit'] X = data.drop('Profit', axis=1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1) model.fit(X_train, y_train) explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(X_train) # 创建画布和子图 fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 15)) # 绘制条形图到ax1 shap.plots.bar(shap_values, feature_names=X.columns, ax=ax1) # 绘制蜂群图到ax2 shap.plots.beeswarm(shap_values, feature_names=X.columns, ax=ax2) plt.tight_layout() plt.show()
方法2:切换当前活动子图(兼容旧版SHAP)
如果你的SHAP版本较低,没有上述独立绘图函数,可以通过plt.sca()切换当前活动的子图轴,让shap.summary_plot()绘制到指定的子图中:
import pandas as pd import shap from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder mylabel = LabelEncoder() data = pd.read_csv("https://raw.githubusercontent.com/krishnaik06/Multiple-Linear-Regression/master/50_Startups.csv") data['State'] = mylabel.fit_transform(data['State']) model = RandomForestRegressor() y = data['Profit'] X = data.drop('Profit', axis=1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1) model.fit(X_train, y_train) explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(X_train) # 创建画布和子图 plt.figure(figsize=(12, 15)) # 切换到第一个子图,绘制条形图 ax1 = plt.subplot(2, 1, 1) plt.sca(ax1) shap.summary_plot(shap_values, X_train, feature_names=X.columns, plot_type="bar", show=False) # 切换到第二个子图,绘制蜂群图 ax2 = plt.subplot(2, 1, 2) plt.sca(ax2) shap.summary_plot(shap_values, X_train, feature_names=X.columns, show=False) plt.tight_layout() plt.show()
注意:此方法需要在调用shap.summary_plot()时加上show=False参数,避免提前显示绘图,最后统一用plt.show()展示整个画布。
内容的提问来源于stack exchange,提问作者user4356954
相关产品推荐
相关产品推荐

