Python Seaborn economist's classic chart imitation

DataCharm 2021-02-22 23:07:44
python seaborn economist classic chart


The last original tweet used R-ggplot2 The realization of the economist's classic chart imitation R-ggplot2 The classic economist's chart imitates , So what about this issue , We just use Python-seaborn To reproduce this classic economist chart . The main knowledge points involved are as follows :

  • Python-seaborn regplot Regression linear fitting graph drawing
  • matplotlib Customized drawing of drawing legend
  • adjustText Library to avoid adding text

Python-seaborn Draw a fitting line graph

First , Let's preview the data ( part ):

among Region_new Columns are new columns that are changed according to relevant requirements , Mapping is also based on secondary data .

Use seaborn By drawing the fitting line, you can avoid making your own wheels , Now let's go straight to the basics ( Without any embellishment ), The code is as follows :

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')

The visualization is as follows :

The main parameters needed here are as follows :

  1. logx : Used to plot logarithmic fit curves , The default is False, That is to draw a linear fitting line .
  2. ci : That is to draw the confidence interval of fitting curve , It can be (0~100) The integer of , Can also be set to False, That is, no confidence interval is drawn .
  3. {scatter,line}_kws : Dictionary type , You can customize the drawing properties of points and lines , Including color 、 size 、 The thickness etc.

At present, only these ( Because drawing needs ), For more details, please refer to the corresponding official website :seaborn.regplot

Let's just put in the visual code that we're drawing , And then explain it separately , The code is as follows :

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))
adjust_text(texts,only_move={'text': 'xy','objects':'x','point':'y'})
#adjust_text(texts,only_move={'text': 'xy'})
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))
# Grid settings
ax.grid(which='major',axis='y',ls='-',c='gray',)
ax.set_axisbelow(True)
# Axis ridge setting
for spine in ['top','left','right']:
ax.spines[spine].set_visible(None) # Remove the axial ridge
ax.spines['bottom'].set_color('k') # Set up bottom Color
# Scale setting , Display only bottom The scale of , And the direction is outward , Long 、 Width is also set
ax.tick_params(bottom=True,direction='in',labelsize=12,width=1,length=3,
left=False)
# Add legend
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')

「 Knowledge point 」

  • Construction of color dictionary , Easy to assign scatter colors
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']]
# stay regplot() Call the following
scatter_kws={"s":50,"fc":"white",
"ec":color,
"lw":1.5,
"alpha":1}
  • adjust_text() Method add ax.annotate attribute
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))
adjust_text(texts,only_move={'text': 'xy','objects':'x','point':'y'})
  • matplotlib Customized legend settings
# Add legend
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))

The final visualization is as follows :

summary

In this issue, we've launched Python-seaborn The classic visualization of tweets , Although there are still problems in the final result ( Of course , You can customize the specific location to solve ), But its main purpose is to let you learn drawing skills , Especially the drawing of fitting curve ( If you have wheels, you can use them directly , Don't think about reinventing yourself ).

This article is from WeChat official account. - DataCharm(shujumeili) , author : Ning Haitao

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2020-11-22

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[DataCharm]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210222130146246A.html

  1. 使用Python开发DeFi项目
  2. python 函数详解
  3. Python工程师是做什么的?前景如何?
  4. Python - zip() 函数
  5. 30 周年生日,Python 先驱是怎么评价这门语言的?
  6. python将excel自适应导入数据库
  7. 从小白到大师,这里有一份Pandas入门指南
  8. [Python] 茎叶图和复合饼图的画法
  9. [Python interface automation] - regular use case parameterization
  10. Translation: practical Python Programming 02_ 02_ Containers
  11. Two years of Java, to write Python and go
  12. Translation: practical Python Programming 02_ 02_ Containers
  13. Two years of Java, to write Python and go
  14. Python-geoplot 空间核密度估计图绘制
  15. Python-seaborn 经济学人经典图表仿制
  16. python空间绘图- regionmask掩膜操作示例
  17. Python 空间绘图 - Cartopy 经纬度添加
  18. Python-pykrige包-克里金(Kriging)插值计算及可视化绘制
  19. Python 批量重采样、掩膜、坡度提取
  20. python - 多种交通方式可达圈分析
  21. Python 空间绘图 - 房价气泡图绘制
  22. Translation: practical Python Programming 02_ 02_ Containers
  23. Research on Portfolio Optimization Based on particle swarm optimization
  24. Ubuntu deploying Django project
  25. Two years of Java, write Python and go without byte beating
  26. Translation: practical Python Programming 02_ 02_ Containers
  27. So learn python, grandfather learned! Introduction to super simple Python
  28. python3 多线程 与 mongo亿级消费日志数据 新鲜demo 【优化第一版】
  29. Summary of Chinese word segmentation based on Jieba
  30. I've heard it n times, but I'm not impressed. After reading this, you'll understand
  31. Summary of Chinese word segmentation based on Jieba
  32. From movie art to Python code to realize God's reverse thinking mode
  33. Summary of Chinese word segmentation based on Jieba
  34. ARIMA模型预测CO2浓度时间序列-python实现
  35. Python belongs to back-end development or front-end development? Introduction to Python!
  36. python isinstance()
  37. I've heard it n times, but I'm not impressed. After reading this, you'll understand
  38. This article will familiarize you with the transformation process of Python - & gt; cafe - & gt; om model
  39. 如何用Python一键修改上万个文件名
  40. One day quick start to Python
  41. Python 学习笔记: List
  42. 翻译:《实用的Python编程》02_03_Formatting
  43. Is there any age requirement for learning Python? Is 30 OK?
  44. Professor Tsinghua! The most complete Python tutorial in 12 hours (free sharing at the end of the article)
  45. Using Python to develop defi project
  46. Detailed explanation of Python function
  47. Python 可变类型作为函数默认参数时的副作用
  48. What do Python engineers do? What's their future?
  49. 这是我见过最好的Python教程:十分钟带你认识Python
  50. Python欢喜冤家:爬虫与反爬虫带着处理方案来给大家拜年了
  51. Python - zip() function
  52. 写Python会遇到如下的错误:ModuleNotFoundError: No module named 'email.mime'; 'email' is not a package
  53. Python类的调用以及私有和公有属性方法的调用
  54. Python类的专有方法
  55. Python基础之:数字字符串和列表
  56. How did Python pioneers evaluate this language on their 30th birthday?
  57. Python基础之:数字字符串和列表
  58. Python基础之:数字字符串和列表
  59. 窥探未来不是梦,python数据分析轻松实现
  60. This article will familiarize you with the transformation process of Python - & gt; cafe - & gt; om model