36

Python-matplotlib 学术散点图 EE 统计及绘制

 3 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzI1MTE2ODg4MA%3D%3D&%3Bmid=2650074767&%3Bidx=2&%3Bsn=ad37ab2b804053e6a1f3ce51055177f3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

腾讯课堂 | Python网络爬虫与文本分析

01. 引言

之前的绘制图文 Python-matplotlib 学术散点图完善 Python-matplotlib 学术型散点图绘制 教程中,对学术散点图已经进行了较为完善的绘制教程,但这几天的通过准备 论文图表再现计划  以及后台小伙伴的留言,发现在绘制的相关性散点图中,各个范围的  Expected Error (EE) 的统计个数没有在图表中进行展示 ,即下图中 左下角 的信息没有绘制。

vUJRBjZ.png!mobile

要完成上述的信息添加,只要涉及的知识点为 数据统计 的简单数据处理过程。下面就此问题进行详细的讲解。

02. 数据处理

要完成数据统计操作,首先要先进行三条拟合线的制作,具体如下:

#导入数据拟合函数
from scipy.stats import linregress
x2 = np.linspace(-10,10)
#制作最佳拟合线数据
y2=x2
#制作上拟合线数据
up_y2 = 1.15*x2 + 0.05
#制作下拟合线数据
down_y2 = 0.85*x2 - 0.05
#进行拟合
line_01 = linregress(x2,y2)
line_top = linregress(x2,up_y2)
line_bopptom = linregress(x2,down_y2)

其中,up_y2和down_y2 具体设置可以参考之前的推文 Python-matplotlib 学术散点图完善 ,linregress () 拟合的结果如下:

slope 为斜率,intercept 为截距,rvalue 为相关系数 ,pvalue 为p值,stderr 为标准误差。

而原始的数据集如下(部分):

eU3Ire6.png!mobile

接下来我们根据相同的x值构建对应拟合线的三个y值,具体代码如下:

data_select = data_select.copy()


data_select['true_y'] = data_select.true_data.values
data_select['top_y'] = data_select['true_data'].apply(lambda x : line_top[0]*x + line_top[1])
data_select['bottom_y'] = data_select['true_data'].apply(lambda x : line_bopptom[0]*x + line_bopptom[1])
data_select.head()

这里涉及到pandas 处理数据常用 的 apply() 函数,该方法对一般的数据处理步骤中经常使用,希望大家能够掌握。构建后的数据如下:

EvQjqq.png!mobile

而判断 各个 Expected Error  的依据就是根据所构建的 top_y 、bottom_y和 model01_estimated 。将三者进行对比分析即可。

统计个数

所需数据构建好后,就可根据pandas 的 数据选择操作 进行筛选,最后统计个数即可,具体代码如下:

#构建 选择条件
top_condi = (data_select['model01_estimated'] > data_select['top_y'])
bottom_condi = (data_select['model01_estimated'] < data_select['bottom_y'])
bottom_top = ((data_select['model01_estimated'] < data_select['top_y']) & \
(data_select['model01_estimated'] > data_select['bottom_y']))
all_data = len(data_select)
top_counts = len(data_select[top_condi])
bottom_counts = len(data_select[bottom_condi])
bottom_top_counts = len(data_select[bottom_top])

进而求出不同 Expected Error 内的数据个数,本实例结果如下:

all_data = 4348
top_counts = 1681
bottom_counts = 404
bottom_top_counts = 2263

03. 数据可视化

数据可视化的绘制相对就比较简单的,大都和之前的推文也都一样,唯一不同的就是添加新内容部分,具体代码如下:

label_font = {'size':'22','weight':'medium','color':'black'}
ax.text(.7,.25,s='Within EE = ' + '{:.0%}'.format(bottom_top_counts/all_data),transform = ax.transAxes,
ha='left', va='center',fontdict=text_font)
ax.text(.7,.18,s='Above EE = ' + '{:.0%}'.format(top_counts/all_data),transform = ax.transAxes,
ha='left', va='center',fontdict=text_font)
ax.text(.7,.11,s='Below EE = ' + '{:.0%}'.format(bottom_counts/all_data),transform = ax.transAxes,
ha='left', va='center',fontdict=text_font)

完整代码如下:

import pandas as pd
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error,r2_score
from matplotlib.pyplot import MultipleLocator
#统一修改字体
plt.rcParams['font.family'] = ['Arial']


N = len(test_data['true_data'])
x = test_data['true_data'].values.ravel() #真实值
y = test_data['model01_estimated'].values.ravel()#预测值
C=round(r2_score(x,y),4)
rmse = round(np.sqrt(mean_squared_error(x,y)),3)
#绘制拟合线
x2 = np.linspace(-10,10)
y2=x2
def f_1(x, A, B):
return A*x + B
A1, B1 = optimize.curve_fit(f_1, x, y)[0]
y3 = A1*x + B1
#开始绘图
fig, ax = plt.subplots(figsize=(7,5),dpi=200)
ax.scatter(x, y,edgecolor=None, c='k', s=12,marker='s')
ax.plot(x2,y2,color='k',linewidth=1.5,linestyle='-',zorder=2)
ax.plot(x,y3,color='r',linewidth=2,linestyle='-',zorder=2)


#添加上线和下线
ax.plot(x2,up_y2,color='k',lw=1.,ls='--',zorder=2,alpha=.8)
ax.plot(x2,down_y2,color='k',lw=1.,ls='--',zorder=2,alpha=.8)
fontdict1 = {"size":17,"color":"k",}
ax.set_xlabel("True Values", fontdict=fontdict1)
ax.set_ylabel("Estimated Values ", fontdict=fontdict1)
ax.grid(which='major',axis='y',ls='--',c='k',alpha=.7)
ax.set_axisbelow(True)
ax.set_xlim((0, 2.0))
ax.set_ylim((0, 2.0))
ax.set_xticks(np.arange(0, 2.2, step=0.2))
ax.set_yticks(np.arange(0, 2.2, step=0.2))


#设置刻度间隔
# x_major_locator=MultipleLocator(.5)
# #把x轴的刻度间隔设置为.5,并存在变量里
# y_major_locator=MultipleLocator(.5)
# ax.xaxis.set_major_locator(x_major_locator)
# #把x轴的主刻度设置为.5的倍数
# ax.yaxis.set_major_locator(y_major_locator)


for spine in ['top','left','right']:
ax.spines[spine].set_visible(None)
ax.spines['bottom'].set_color('k')
ax.tick_params(bottom=True,direction='out',labelsize=14,width=1.5,length=4,
left=False)
#ax.tick_params()
#添加题目
titlefontdict = {"size":20,"color":"k",}
ax.set_title('Scatter plot of True data and Model Estimated',titlefontdict,pad=20)
#ax.set_title()
fontdict = {"size":16,"color":"k",'weight':'bold'}
ax.text(0.1,1.8,r'$R^2=$'+str(round(C,3)),fontdict=fontdict)
ax.text(0.1,1.6,"RMSE="+str(rmse),fontdict=fontdict)
ax.text(0.1,1.4,r'$y=$'+str(round(A1,3))+'$x$'+" + "+str(round(B1,3)),fontdict=fontdict)
ax.text(0.1,1.2,r'$N=$'+ str(N),fontdict=fontdict)


#添加上下线的统计个数
text_font = {'size':'15','weight':'medium','color':'black'}
label_font = {'size':'22','weight':'medium','color':'black'}
ax.text(.9,.9,"(a)",transform = ax.transAxes,fontdict=text_font,zorder=4)


ax.text(.7,.25,s='Within EE = ' + '{:.0%}'.format(bottom_top_counts/all_data),transform = ax.transAxes,
ha='left', va='center',fontdict=text_font)
ax.text(.7,.18,s='Above EE = ' + '{:.0%}'.format(top_counts/all_data),transform = ax.transAxes,
ha='left', va='center',fontdict=text_font)
ax.text(.7,.11,s='Below EE = ' + '{:.0%}'.format(bottom_counts/all_data),transform = ax.transAxes,
ha='left', va='center',fontdict=text_font)


ax.text(.8,.056,'\nVisualization by DataCharm',transform = ax.transAxes,
ha='center', va='center',fontsize = 10,color='black')
# plt.savefig(r'E:\Data_resourses\DataCharm 公众号\Python\学术图表绘制\scatter_EE.png',
# width=7,height=4,dpi=900,bbox_inches='tight')
plt.show()

结果如下:

Vbm2aa3.png!mobile

04. 总结

本期的推文主要就是介绍 如何统计  Expected Error  个数及将结果展示在绘图中,涉及的知识点点都是比较基础的 数据条件筛选及统计个数。pandas 库在数据处理及统计分析这一块应用起来是比较简单的,但也要多练习,毕竟数据处理小技巧比较多也易忘。

近期文章

Python网络爬虫与文本数据分析

rpy2库 | 在jupyter中调用R语言代码

tidytext | 耳目一新的R-style文本分析库

reticulate包 | 在Rmarkdown中调用Python代码

plydata库 | 数据操作管道操作符>>

七夕礼物 | 全网最火的钉子绕线图制作教程

读完本文你就了解什么是文本分析

文本分析在经管领域中的应用概述

综述:文本分析在市场营销研究中的应用

plotnine: Python版的ggplot2作图库

小案例: Pandas的apply方法   

stylecloud:简洁易用的词云库  

用Python绘制近20年地方财政收入变迁史视频   

Wow~70G上市公司定期报告数据集

漂亮~pandas可以无缝衔接Bokeh

YelpDaset: 酒店管理类数据集10+G

分享 ”和“ 在看 ”是更好的支持!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK