Pandas高级数据分析快速入门之四——数据可视化篇
Posted 肖永威
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pandas高级数据分析快速入门之四——数据可视化篇相关的知识,希望对你有一定的参考价值。
Pandas高级数据分析快速入门之一——Python开发环境篇
Pandas高级数据分析快速入门之二——基础篇
Pandas高级数据分析快速入门之三——数据挖掘与统计分析篇
Pandas高级数据分析快速入门之四——数据可视化篇
Pandas高级数据分析快速入门之五——机器学习特征工程篇
Pandas高级数据分析快速入门之六——机器学习预测分析篇
1. 关于Matlibplot
Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats # 科学计算包
def stats_linear_regression(df):
user_df = df.loc[df['carduser_id']== 2085603 ].reset_index(drop=True)
Days = user_df['days'].values
Days = Days[1:]
k = []
for i in range(len(Days)):
k.append(i)
#Days = Days.reshape(-1,1)
x = np.array(k)
y = Days
# 科学计算包中统计方法,用于计算散点回归线趋势的斜率、截距
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
print('slope is ' + str(slope))
# 画图
plt.rcParams['figure.figsize']= 10,5 #设置图例尺寸
plt.rcParams['font.sans-serif']=['SimHei'] #设置为中文黑体,如果设置楷体则为 KaiTi
plt.rcParams['axes.unicode_minus']=False
plt.scatter(x, y, color='b',label='间隔时间')
plt.plot(x, slope*x + intercept, color='r',label='趋势回归线')
plt.legend() #绘制图例,右上角标识图
plt.show() #显示图形
# plt.savefig("temp.png")
数据及代码,接上文[1]。
其中,绘图通用、基本部分为设置图片尺寸和中文兼容设置,详见代码中的注释。
提示:示例代码中plt.savefig(“temp.png”),很容易的把图像保存到文件中,如果直接生产文件时,可以不使用plt.show()函数(界面不显示)。
stats_linear_regression(trade_df)
slope is -0.11791958041958041
2. Pandas绘图
Pandas绘图是基于Matlibplot和Numpy,二次封装,以实现简化绘图工作。
2.1. 画直方图
plt.rcParams['figure.figsize']= 12,6
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签 KaiTi
plt.rcParams['axes.unicode_minus']=False
df=trade_df[['balance','recharge','volumn','amount']] # 交易数据来自上篇文章内容
df.hist()
plt.show()
2.2. 画密度图曲线图
接续上一锻炼“2.1”代码。
df.plot(kind='density',subplots=True,layout=(2,2),sharex=False,fontsize=8)
plt.show()
2.3. 画折线图
使用上篇文章[1]的月份交易汇聚数据,详见其代码顺序执行即可。
user_df = ms_df.loc[ms_df['carduser_id']==2085603].reset_index(drop=True)
# 月份转序列化
user_df[['年月']] = user_df['yearmonth'].apply(lambda x: str(x)[0:4] + '-' + str(x)[4:6])
df = user_df[['balance','recharge','amount','年月']]
df = df.set_index('年月')
df.plot()
注:代码中,额外增加把年月转换为字符串后,做为横坐标的序列,而不是原有数字,避免为直接数值大小的使用。
2.4. 画柱状图
user_df = ms_df.loc[ms_df['carduser_id']==2085603].reset_index(drop=True)
# 月份转序列化
user_df[['年月']] = user_df['yearmonth'].apply(lambda x: str(x)[0:4] + '-' + str(x)[4:6])
df = user_df[['balance','recharge','amount','年月']]
df = df.set_index('年月')
df.plot.bar()
2.5. 画饼状图
user_df = ms_df.loc[(ms_df['carduser_id']==2085603) & (ms_df['year']==2021)].reset_index(drop=True)
# 月份转序列化
user_df[['年月']] = user_df['yearmonth'].apply(lambda x: str(x)[0:4] + '-' + str(x)[4:6])
df = user_df[['balance','recharge','amount','年月']]
df = df.set_index('年月')
df.plot.pie(subplots=True,figsize=(10, 8),autopct='%.2f%%',radius = 1.2,startangle = 250,legend=False,colormap='viridis')
2.6. 画条形图
user_df = ms_df.loc[(ms_df['carduser_id']==2085603) & (ms_df['year']==2021)].reset_index(drop=True)
# 月份转序列化
user_df[['年月']] = user_df['yearmonth'].apply(lambda x: str(x)[0:4] + '-' + str(x)[4:6])
df = user_df[['balance','recharge','amount','年月']]
df = df.set_index('年月')
df.plot.barh()
3. 复杂图形
3.1. 热力图(皮尔逊相关)
import matplotlib.pyplot as plt
cols_name = ['carduser_id','yearmonth','sumamount','recharge','amount','goods','volumn','tradecount','balance','month','year']
cols_name.remove('carduser_id') #客户号不参与相关计算,没有意义
correlations = ms_df[cols_name].corr(method='pearson',min_periods=1) #计算变量之间的相关系数矩阵
plt.rcParams['figure.figsize']= 12,10
fig = plt.figure() #调用figure创建一个绘图对象
ax = fig.add_subplot(111)
cax = ax.matshow(correlations,cmap = 'viridis', vmin=-1, vmax=1) #绘制热力图,从-1到1
fig.colorbar(cax) #将matshow生成热力图设置为颜色渐变条
ticks = np.arange(0,len(correlations),1) #生成0-9,步长为1
ax.set_xticks(ticks) #生成刻度
ax.set_yticks(ticks)
ax.set_xticklabels(cols_name) #生成x轴标签
ax.set_yticklabels(cols_name)
plt.show()
3.2. 雷达图
import numpy as np
import matplotlib.pyplot as plt
# 用于正常显示中文
plt.rcParams['font.sans-serif'] = 'SimHei'
#用于正常显示符号
plt.rcParams['axes.unicode_minus'] = False
# 使用ggplot的绘图风格,这个类似于美化了,可以通过plt.style.available查看可选值,你会发现其它的风格真的丑。。。
plt.style.use('ggplot')
# 构造数据
user_df = ms_df.loc[(ms_df['carduser_id']==1313943) & (ms_df['yearmonth']==201909)].reset_index(drop=True)
# 转换数据在雷达范围 0,5
df = user_df[['balance','recharge','amount','volumn','goods']].apply(lambda x:x/15000)
df = df.rename(columns={'balance':'余额','recharge':'充值','amount':'金额','volumn':'加油量','goods':'非油消费'})
print(df)
feature = df.columns.tolist()
print(feature)
values = df.values.tolist()[0]
print(values)
# 设置每个数据点的显示位置,在雷达图上用角度表示
angles=np.linspace(0, 2*np.pi,len(values), endpoint=False)
# 拼接数据首尾,使图形中线条封闭
values=np.concatenate((values,[values[0]]))
print(values)
angles=np.concatenate((angles,[angles[0]]))
print(angles)
# 绘图
fig=plt.figure()
# 设置为极坐标格式
ax = fig.add_subplot(111, polar=True)
# 绘制折线图
ax.plot(angles, values, 'o-', linewidth=2)
# 填充颜色
ax.fill(angles, values, alpha=0.25)
# 设置图标上的角度划分刻度,为每个数据点处添加标签
ax.set_thetagrids(angles * 180/np.pi, feature)
# 设置雷达图的范围
ax.set_ylim(0,5)
# 添加标题
plt.title('客户月消费情况')
# 添加网格线
ax.grid(True)
plt.show()
源代码参考[3]。
参考:
[1]. 肖永威 . Pandas高级数据分析快速入门之三——数据挖掘与统计分析篇 ,CSDN博客 ,2021-08
[2]. hgz_dm .利用matlibplot绘制雷达图, 博客园 ,2019-05
[3]. 肖永威 . Python Matplotlib绘制渐变色柱状图(bar)并加边框和配置渐变颜色条(colorbar) ,CSDN博客 ,2020-09
以上是关于Pandas高级数据分析快速入门之四——数据可视化篇的主要内容,如果未能解决你的问题,请参考以下文章