## Python-seaborn 经济学人经典图表仿制

DataCharm 2021-02-22 13:02:22
Python 经济学 seaborn 经济 python-seaborn

• Python-seaborn regplot回归线性拟合图绘制
• matplotlib 绘图图例的定制化绘制

## Python-seaborn 绘制拟合线图

```fig,ax = plt.subplots(figsize=(8,4.5),dpi=200,facecolor='white',edgecolor='white')
ax.set_facecolor("white")
fit_line = sns.regplot(data=test_data,x="CPI",y="HDI",logx=True,ax=ax)
ax.text(.85,-.07,'\nVisualization by DataCharm',transform = ax.transAxes,
ha='center', va='center',fontsize = 8,color='black')
```

1. logx ：用于绘制对数拟合曲线，默认为False,即绘制线性拟合线。
2. ci ：即绘制拟合曲线的置信区间，可以是(0~100)的整数，也可以设置为False,即不绘制置信区间。
3. {scatter,line}_kws ： 字典类型，即可定制化设置点和线的绘图属性，包括颜色、大小、粗细等

```fig,ax = plt.subplots(figsize=(8,4.5),dpi=200,facecolor='white',edgecolor='white')
ax.set_facecolor("white")
color = [region_color[i] for i in test_data['Region_new']]
fit_line = sns.regplot(data=test_data,x="CPI",y="HDI",logx=True,ci=False,
line_kws={"color":"red",
"label":r"\$R^2\$=56%",
"lw":1.5},
scatter_kws={"s":50,"fc":"white",
"ec":color,
"lw":1.5,
"alpha":1},
ax=ax)
texts = []
for i, j ,t in zip(data_text["CPI"],data_text["HDI"],data_text["Country"]):
texts.append(ax.annotate(t,xy=(i, j),xytext=(i-.8,j),
arrowprops=dict(arrowstyle="-", color="black",lw=.5),
color='black',size=9))
ax.set_xlabel("Corruption Perceptions Index, 2011 (10=least corrupt)",fontstyle="italic",
fontsize=8)
ax.set_ylabel("Human Development Index, 2011 (1=best)",fontstyle="italic",fontsize=8)
ax.set_xlim((.5, 10.2))
ax.set_ylim((.2, 1))
ax.set_xticks(np.arange(1, 10.3, step=1))
ax.set_yticks(np.arange(0.2, 1.05, step=0.1))
#网格设置
ax.grid(which='major',axis='y',ls='-',c='gray',)
ax.set_axisbelow(True)
#轴脊设置
for spine in ['top','left','right']:
ax.spines[spine].set_visible(None) #隐去轴脊
ax.spines['bottom'].set_color('k') #设置bottom颜色
#刻度设置，只显示bottom的刻度，且方向向外，长、宽也进行设置
ax.tick_params(bottom=True,direction='in',labelsize=12,width=1,length=3,
left=False)
#添加图例
ax.scatter([], [], ec='#01344A', fc="white",label='OECD', lw=1.5)
ax.scatter([], [], ec='#228DBD', fc="white",label='Americas', lw=1.5)
ax.scatter([], [], ec='#6DBBD8', fc="white",label='Asia & \nOceania', lw=1.5)
ax.scatter([], [], ec='#1B6E64', fc="white",label='Central & \nEastern Europe', lw=1.5)
ax.scatter([], [], ec='#D24131', fc="white",label='Middle East & \nnorth Africa', lw=1.5)
ax.scatter([], [], ec='#621107', fc="white",label='Sub-Saharan \nAfrica', lw=1.5)
ax.legend(loc="upper center",frameon=False,ncol=7,fontsize=6.5,bbox_to_anchor=(0.5, 1.1))
ax.text(.5,1.19,"Corruption and human development",transform = ax.transAxes,ha='center',
va='center',fontweight="bold",fontsize=16)
ax.text(.5,1.12, "Base Charts:Scatter Exercise in Python",
transform = ax.transAxes,ha='center', va='center',fontsize = 12,color='black')
ax.text(.9,.05,'\nVisualization by DataCharm',transform = ax.transAxes,
ha='center', va='center',fontsize = 8,color='black')
```

「知识点」

• 颜色字典构建，方便赋值散点颜色
```color = ('#01344A','#228DBD','#6DBBD8','#1B6E64','#D24131','#621107')
region =("OECD","Americas","Asia & \nOceania","Central & \nEastern Europe",
"Middle East & \nnorth Africa", "Sub-Saharan \nAfrica")
region_color = dict(zip(region,color))
color = [region_color[i] for i in test_data['Region_new']]
#在regplot()调用如下
scatter_kws={"s":50,"fc":"white",
"ec":color,
"lw":1.5,
"alpha":1}
```
```texts = []
for i, j ,t in zip(data_text["CPI"],data_text["HDI"],data_text["Country"]):
texts.append(ax.annotate(t,xy=(i, j),xytext=(i-.8,j),
arrowprops=dict(arrowstyle="-", color="black",lw=.5),
color='black',size=9))
```
• matplotlib 定制化图例设置
```#添加图例
ax.scatter([], [], ec='#01344A', fc="white",label='OECD', lw=1.5)
ax.scatter([], [], ec='#228DBD', fc="white",label='Americas', lw=1.5)
ax.scatter([], [], ec='#6DBBD8', fc="white",label='Asia & \nOceania', lw=1.5)
ax.scatter([], [], ec='#1B6E64', fc="white",label='Central & \nEastern Europe', lw=1.5)
ax.scatter([], [], ec='#D24131', fc="white",label='Middle East & \nnorth Africa', lw=1.5)
ax.scatter([], [], ec='#621107', fc="white",label='Sub-Saharan \nAfrica', lw=1.5)
ax.legend(loc="upper center",frameon=False,ncol=7,fontsize=6.5,bbox_to_anchor=(0.5, 1.1))
```

## 总结

https://cloud.tencent.com/developer/article/1790271