使用多重回归图Python更改每个回归线样式

问题描述

我目前正在尝试为我的数据绘制两条回归线,并按类别属性(自由度或幸福度得分)进行划分。我目前的疑虑是我需要颜色来编码图形中的另一个单独的分类属性(GNI /人均括号)。混合颜色似乎令人困惑,因此我决定使用不同的标记来区分数据点。但是,我很难将回归线之一更改为虚线,因为它们是相同的。我什至不想考虑如何为所有这些创建一个图例。如果您认为这是一个丑陋的图形,我同意,但是在某些情况下,我必须在单个图形中编码四个属性。顺便说一句,如果有任何建议,欢迎公开提出任何更好的建议。下面是我当前图表的一个示例,希望对您有所帮助!

sns.lmplot(data=combined_indicators,x='x',y='y',hue='Indicator',palette=["#000620"],markers=['x','.'],ci=None)
plt.axvspan(0,1025,alpha=0.5,color='#de425b',zorder=-1)
plt.axvspan(1025,4035,color='#fbb862',zorder=-1)
plt.axvspan(4035,12475,color ='#afd17c',zorder=-1)
plt.axvspan(12475,100000,color='#00876c',zorder=-1)
plt.title("HFI & Happiness Regressed on GNI/capita")
plt.xlabel("GNI/Capita by Purchasing Power Parity (2017 International $)")
plt.ylabel("Standard Indicator score (0-10)")

My current figure rears its ugly head

解决方法

据我所知,没有简单的方法来更改lmplot中回归线的样式。但是,如果您使用regplot而不是lmplot,则可以实现自己的目标,缺点是必须手动实现hue拆分

x_col = 'total_bill'
y_col = 'tip'
hue_col = 'smoker'
df = sns.load_dataset('tips')

markers = ['x','.']
colors = ["#000620","#000620"]
linestyles = ['-','--']

plt.figure()
for (hue,gr),m,c,ls in zip(df.groupby(hue_col),markers,colors,linestyles):
    sns.regplot(data=gr,x=x_col,y=y_col,marker=m,color=c,line_kws={'ls':ls},ci=None,label=f'{hue_col}={hue}')
ax.legend()

enter image description here

,

只需添加,如果以后有人偶然发现此帖子,则可以使用Line2D手动为此混乱创建一个图例。对于我来说看起来像这样:

from matplotlib.patches import Patch
from matplotlib.lines import Line2D

legend_elements = [Line2D([0],[0],color='#000620',lw=2,label='Freedom',linestyle='--'),Line2D([0],label='Happiness'),marker='x',markerfacecolor='#000620',markersize=15),marker='.',label='Happiness',Patch(facecolor='#de425b',label='Low-Income'),Patch(facecolor='#fbb862',label='Lower Middle-Income'),Patch(facecolor='#afd17c',label='Upper Middle-Income'),Patch(facecolor='#00876c',label='High-Income')]

最终结果如下: Graph with custom legend