Python如何繪制日歷圖和熱力圖
本文以2019年全國(guó)各城市的空氣質(zhì)量觀測(cè)數(shù)據(jù)為例,利用matplotlib、calmap、pyecharts繪制日歷圖和熱力圖。在繪圖之前先利用pandas對(duì)空氣質(zhì)量數(shù)據(jù)進(jìn)行處理。
2019年全國(guó)各城市空氣質(zhì)量觀測(cè)數(shù)據(jù)來(lái)源于:https://beijingair.sinaapp.com。
數(shù)據(jù)處理
從網(wǎng)站下載的數(shù)據(jù)為逐小時(shí)數(shù)據(jù),每天一個(gè)文件。如果要繪制全年的日歷圖或者熱圖,首先要將所有的數(shù)據(jù)進(jìn)行合并處理。
下載好數(shù)據(jù)之后,將數(shù)據(jù)解壓到當(dāng)前目錄的2019文件夾內(nèi),然后處理數(shù)據(jù):
import globfrom datetime import datetime, timedeltaimport numpy as npimport pandas as pd
from matplotlib import cm, colorsimport matplotlib.dates as mdatesimport matplotlib.patches as mpatchesimport matplotlib.pyplot as plt
def format_aqi(filep, columns=None): files = glob.glob(filep)
df = pd.concat((pd.read_csv(f) for f in files)) df.index = pd.to_datetime(df.date.astype(np.str) + df.hour.apply(lambda x: '%02d'%x), format='%Y%m%d%H') # drop date and hour columns df.drop(['date', 'hour'], axis=1, inplace=True)
df = df.pivot_table(columns='type', index=df.index) df.columns.names = ['station', 'type'] df.index.names = ['date']
df = df.stack('station')
if columns is not None: df = df.loc[:, columns]
return df
filep = '2019/china*.csv' data = format_aqi(filep)data.csv('2019.csv') # 保存以便后續(xù)使用
合并完成數(shù)據(jù)后,讀取數(shù)據(jù)并進(jìn)一步處理:
data = pd.read_csv('2019.csv', index_col='date', parse_dates=True)data2 = data.pivot_table(index=data.index, columns=['station'])
time_range = pd.date_range(datetime(2019, 10, 1, 0), datetime(2019, 12, 31, 23), freq='1h')
idx = pd.IndexSliceaqi = data2.loc[:, idx['AQI', :]].xs('AQI', axis=1)aqi = aqi.reindex(time_range)
cities = ['北京', '天津', '石家莊', '邯鄲', '濟(jì)南', '鄭州', '菏澤', '亳州', '徐州', '駐馬店', '南京', '合肥', '馬鞍山', '武漢', '上海', '杭州', '長(zhǎng)沙', '南昌', '上饒', '溫州', '吉安', '贛州', '福州', '龍巖', '廈門(mén)', '泉州' ]
sub = aqi[cities[::-1]]
繪制熱力圖
因?yàn)榭諝赓|(zhì)量有專(zhuān)門(mén)的配色,首先設(shè)置對(duì)應(yīng)等級(jí)的colormap
colors_aqi = ['#009966', '#FFDE33', '#FF9A32', '#CC0033', '#660099']levels = [0, 50, 100, 150, 200, 300] cmap_aqi = colors.ListedColormap(colors_aqi) norm = colors.BoundaryNorm(levels, cmap_aqi.N)
然后,開(kāi)始繪圖:
fig, ax = plt.subplots(figsize=(16, 9))
con = ax.pcolormesh(sub.index.values, np.arange(0, sub.columns.shape[0]+1), sub.T, cmap=cmap_aqi, norm=norm, vmin=0, vmax=300 )
sdate = datetime(2019, 10, 1)edate = datetime(2019, 12, 31)xticks = pd.date_range(sdate, edate, freq='15d')
ax.set_xlim([sdate, edate])ax.set_xticks(xticks)ax.set_xticklabels([i.strftime('%m/%d') for i in xticks])ax.set_yticks(np.arange(0.5, len(cities)))_ = ax.set_yticklabels(sub.T.index.values, fontdict={'family': 'SimHei', 'fontsize': 16})
ytext = [i.get_text() for i in list(ax.get_yticklabels())]
cb = fig.colorbar(con, extend='max', pad=0.02, extendrect=True, extendfrac=0.2)cb.cmap.set_over('#7D0023')
cb.ax.tick_params(axis='both', direction='in', length=0)_ = cb.ax.set_ylabel('Air Quality Index(AQI)', fontdict={'family': 'Times New Roman'})

2019年10月-12月各城市的AQI日變化
繪制日歷圖
python中關(guān)于繪制日歷圖的工具相對(duì)較少,沒(méi)有特別有些的工具。下面分別使用calmap和pyecharts繪制日歷圖。
注意:calmap已經(jīng)放棄維護(hù)了,在使用過(guò)程中可能會(huì)存在問(wèn)題。本文fork了原來(lái)的源碼,解決了可能遇到的問(wèn)題??梢詮?a target="_blank" rel="external nofollow" >https://github.com/bugsuse/calmap下載源碼,然后執(zhí)行python setup.py install進(jìn)行安裝即可。
注意:本文為了簡(jiǎn)單起見(jiàn),利用AQI繪圖時(shí),直接對(duì)AQI求日均值,但是實(shí)際情況下是不能直接這樣計(jì)算的。
import calmap
dd = data[data.station == '北京'].AQI.resample('1d').mean()
fig, ax = plt.subplots(figsize=(18, 9))
cmp = calmap.yearplot(dd, how=None, year=2019, cmap=cmap_aqi, norm=norm, vmin=0, vmax=300, )
ax2 = fig.add_axes([0.94, 0.4, 0.015, 0.2])cb1 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap_aqi, ticks=levels, norm=norm, orientation='vertical', extend='max', extendrect=True, extendfrac=0.15)cb1.cmap.set_over('#7D0023')cb1.set_ticks([25, 75, 125, 175, 250])cb1.ax.set_yticklabels([u'優(yōu)', u'良', u'輕度污染', u'中度污染', u'重度污染'], fontdict={'fontsize': 16, 'family': 'SimHei'}) cb1.ax.yaxis.set_tick_params(length=0.01)ax2.text(1.13, 1.07, '嚴(yán)重污染', fontdict={'fontsize':16, 'family':'SimHei'})
ax.set_ylabel('2019', fontdict=dict(fontsize=26, color='grey'))

2019年北京市AQI日歷圖
下面利用pyecharts繪制2019年北京市AQI日歷圖。
from pyecharts import options as optsfrom pyecharts.charts import Calendar
begin = datetime(2019, 1, 1)end = datetime(2019, 12, 31)data = [ [str(begin + timedelta(days=i)), dd[i]] for i in range((end - begin).days + 1)]
c = ( Calendar() .add( "", data, calendar_opts=opts.CalendarOpts( range_='2019', daylabel_opts=opts.CalendarDayLabelOpts(name_map='cn'), monthlabel_opts=opts.CalendarMonthLabelOpts(name_map='cn'), ), ) .set_global_opts( title_opts=opts.TitleOpts(title='2019年北京市每日AQI(Air Quality Index)', pos_left='center'), visualmap_opts=opts.VisualMapOpts( max_=300, min_=0, range_size=[0, 50, 100, 150, 200, 300], pieces= [{'min': 0, 'max': 50}, {'min': 51, 'max': 100}, {'min': 101, 'max': 150}, {'min': 151, 'max': 200},

2019年北京市AQI日歷圖
繪制熱力圖也可以使用seaborn,不需要單獨(dú)碼很多代碼,而且功能要更多一些。python在繪制日歷圖方面不是非常友好,相比之下,pyecharts更有優(yōu)勢(shì)。但是pyecharts更適合線上可視化展示,不太適合制作用于發(fā)表論文的圖。
這次就說(shuō)到這了,感興趣的可以去嘗試一下。
以上就是Python如何繪制日歷圖和熱力圖的詳細(xì)內(nèi)容,更多關(guān)于Python繪制日歷圖和熱力圖的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實(shí)現(xiàn)的Google IP 可用性檢測(cè)腳本
這篇文章主要介紹了Python實(shí)現(xiàn)的Google IP 可用性檢測(cè)腳本,本文腳本需要Python 3.4+環(huán)境,需要的朋友可以參考下2015-04-04
python打開(kāi)windows應(yīng)用程序的實(shí)例
今天小編就為大家分享一篇python打開(kāi)windows應(yīng)用程序的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06
一個(gè)Python案例帶你掌握xpath數(shù)據(jù)解析方法
xpath解析是最常用且最便捷高效的一種解析方式,通用性強(qiáng)。本文將通過(guò)一個(gè)Python爬蟲(chóng)案例帶你詳細(xì)了解一下xpath數(shù)據(jù)解析方法,需要的可以參考一下2022-02-02
Python實(shí)現(xiàn)處理圖片水印的方法詳解
這篇文章主要為大家詳細(xì)介紹了如何利用Python實(shí)現(xiàn)處理圖片水印的相關(guān)資料,主要是實(shí)現(xiàn)圖片水印的去除效果,感興趣的小伙伴可以嘗試一下2022-11-11
Python 經(jīng)典面試題 21 道【不可錯(cuò)過(guò)】
這篇文章主要介紹了Python 經(jīng)典面試題 21 道,在python面試過(guò)程中這21道是經(jīng)常被問(wèn)到了,感興趣的朋友跟隨小編一起看看吧2018-09-09

