#!/usr/bin/env python # coding: utf-8 # ### 透视表与热力图 # # 如果想查看论坛用户在各个地区的行业分布情况,或者说在不同行业的地区分布情况,就需要用到透视表 # # 开头的代码都是差不多的 # In[1]: from model import Users, Provs, Industry import pandas as pd import numpy as np import matplotlib.pyplot as plt # In[2]: u = (Users.select(Users.id, Provs.prov, Industry.industry) .join(Provs, on=(Users.prov==Provs.id)) .join(Industry, on=(Users.industry==Industry.id))) df = pd.DataFrame(list(u.dicts())) df = df.drop(df.index[df['prov']=='350000']) # In[3]: df.head() # 这里`groupby`完成后直接用了`count()`来计算数量(之前用的是`size()`,两者其实有很大差别,不再赘述) # In[4]: gdf = df.groupby(['prov', 'industry']).count().rename({'id': 'x'}, axis=1)#.sort_values('x', ascending=False) gdf.head() # 下面调用`pivot_table`后就能生成透视表了,最主要参数有4个:`index`,`columns`,`values`,`aggfunc`,这里就不做解释了,因为解释起来太复杂,我这智商只能看懂,不足以说清楚-_-||| # In[5]: locind = pd.pivot_table(gdf, index=['prov'], columns=['industry'], values=['x'], aggfunc=np.mean) locind.T # 透视表固然很好,但是上面这个38×34的大表就很不直观了,不过只要转换成热力图,就能够一目了然了 # # 这里用`seaborn`来生成热力图,`seaborn`对`matplotlib`进行了一次封装,提供了更方便的API。 # In[6]: import seaborn as sns sns.set(font="Microsoft YaHei") f, ax = plt.subplots(figsize=(40, 20)) plt.subplots_adjust(top=0.85) f.suptitle('地区-行业 热力图', fontsize=16) sns.heatmap(locind.fillna(0), annot=True, cmap='Reds', fmt='.0f', linewidths=.5, ax=ax) ax.set_xlabel('行业') ax.xaxis.set_label_position('top') ax.set_ylabel('地区') ax.yaxis.set_label_position('left') xticks = ['%s' % xt.get_text().strip('x-') for xt in ax.get_xticklabels()] ax.set_xticklabels(xticks, rotation=90) ax.xaxis.tick_top() plt.show() # > 不过,画个图还真是费劲呐