多个Seaborn pointplot绘制时图例颜色与设定值不匹配问题
问题原因
每次调用sns.pointplot()时,会在坐标轴上生成多个绘图对象(包括点、连线、误差线等),直接调用ax.legend()时会默认按顺序读取前3个绘图对象匹配标签,而非对应你三次绘图的主线条,因此出现颜色和标签不匹配的问题。
解决方案1:最小改动现有代码
手动指定图例对应每个绘图的主线条即可,修改后代码如下:
fig, ax = plt.subplots() sns.pointplot(x=l[1:], y = np.exp(model_m.params[1:]), label = 'factor', ax = ax, color = 'green') line1 = ax.lines[0] sns.pointplot(x=l[1:], y = np.exp(model_m.conf_int()[1:][:,1]), ax = ax, label = 'conf_int+', color = 'red') line2 = ax.lines[2] sns.pointplot(x=l[1:], y = np.exp(model_m.conf_int()[1:][:,0]), ax = ax, label = 'conf_int-', color = 'blue') line3 = ax.lines[4] plt.title('Model M Discrete') ax.legend(handles=[line1, line2, line3], labels = ['factor', 'conf_int+', 'conf_int-'], title = 'legend') plt.show()
解决方案2:符合Seaborn推荐规范的写法
将数据转换为长格式(tidy data),使用hue参数一次性绘图,自动生成正确匹配的图例,无需手动调整:
import pandas as pd # 构造长格式数据集 df = pd.DataFrame({ "x": l[1:], "factor": np.exp(model_m.params[1:]), "conf_int+": np.exp(model_m.conf_int()[1:][:,1]), "conf_int-": np.exp(model_m.conf_int()[1:][:,0]) }).melt(id_vars="x", var_name="指标", value_name="y") # 单次绘图自动匹配颜色和图例 fig, ax = plt.subplots() sns.pointplot( data=df, x="x", y="y", hue="指标", palette=["green", "red", "blue"], ax=ax ) plt.title('Model M Discrete') plt.show()
内容的提问来源于stack exchange,提问作者Jordan
相关产品推荐
相关产品推荐

