如何调整Yellowbrick生成的学习曲线的图例位置?
调整Yellowbrick学习曲线的图例位置
你遇到的问题是因为提前调用了plt.legend(),此时还没有绘制学习曲线的图例元素,自然不会生效;另外Yellowbrick的可视化组件会创建自己的Axes对象,直接用全局plt方法可能无法正确定位到目标绘图区域。
以下是两种可行的修正方案:
方案一:获取学习曲线返回的Axes对象调整图例
调用learning_curve时会返回对应的Axes实例,直接对这个实例操作即可修改图例位置:
from yellowbrick.model_selection import learning_curve import matplotlib.pyplot as plt import numpy as np plt.rcParams['figure.figsize'] = [10, 5] # 调用learning_curve并接收返回的Axes对象 ax = learning_curve( estimator=mlp_new, X=x_train, y=y_train, cv=4, train_sizes=np.linspace(0.1,1.0,5), n_jobs=1, random_state=0, scoring='r2', ) # 对返回的Axes设置图例位置 ax.legend(loc="upper left") # 后续保存和展示操作 fig2 = plt.gcf() plt.show() fig2.savefig('for DNN.jpeg',bbox_inches='tight', dpi=600)
方案二:先创建Axes再传递给learning_curve
如果需要更精细的绘图控制,可以先创建自定义Axes,再传递给learning_curve的ax参数,之后调整图例:
from yellowbrick.model_selection import learning_curve import matplotlib.pyplot as plt import numpy as np plt.rcParams['figure.figsize'] = [10, 5] # 创建自定义Axes fig, ax = plt.subplots() # 将Axes传递给learning_curve learning_curve( estimator=mlp_new, X=x_train, y=y_train, cv=4, train_sizes=np.linspace(0.1,1.0,5), n_jobs=1, random_state=0, scoring='r2', ax=ax # 指定使用自定义Axes ) # 调整图例位置 ax.legend(loc="upper left") plt.show() fig.savefig('for DNN.jpeg',bbox_inches='tight', dpi=600)
注意:删除原来代码中提前调用的plt.legend(loc="upper left"),那行代码在绘图前执行,没有实际作用。
内容的提问来源于stack exchange,提问作者z987
相关产品推荐
相关产品推荐

