<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          北京空氣質(zhì)量真的很差嗎?Python繪制熱力圖一目了然

          共 20071字,需瀏覽 41分鐘

           ·

          2021-05-16 00:41


          大家好,歡迎來到 Crossin的編程教室 !

          今年3月北京時(shí)6再次遭遇沙塵暴,大家一起被迫吃土!上次沙塵暴出現(xiàn)還是在2015年4月15日

          記得那天早上起床,打開手機(jī)看到好多盆友發(fā)來的詢問關(guān)懷“聽說北京沙塵暴了,注意安全哦”,比心 ! 隨后拉開窗簾,果然是漫天黃沙還伴隨著大風(fēng),打開朋友圈滿屏的銀翼殺手末日的關(guān)鍵字。

          其實(shí),我們看看北京最近15個(gè)月空氣質(zhì)量熱力圖發(fā)現(xiàn),大部分的時(shí)間空氣質(zhì)量還是不錯(cuò)的,良好與優(yōu)秀居多

          注意:綠色(50以下) 表示優(yōu)秀,黃色(50-100)表示良好,橙色及其他屬于污染。

          北京最近15個(gè)月空氣質(zhì)量熱力圖

          上面這張熱力圖是用Python繪制的,今天就來講一講是如何做出來的。

          目錄:

          • 0. 圖賞

          • 1. 空氣質(zhì)量數(shù)據(jù)獲取

          • 2. 數(shù)據(jù)預(yù)處理

          • 3. 熱力圖繪制

            • 3.1. seaborn的heatmap熱力圖

            • 3.2. plotly的熱力圖繪制

          • 4. 附

          0. 圖賞

          鳥巢:

          鳥巢

          故宮角樓:

          故宮角樓

          大褲衩:

          大褲衩

          銀翼殺手:

          銀翼殺手

          我上班路上:

          202103月15日早上10點(diǎn)上班路上

          1. 空氣質(zhì)量數(shù)據(jù)獲取

          這里我們從akshare庫的接口直接獲取北京市歷史空氣質(zhì)量數(shù)據(jù)

          import akshare as ak

          air_quality_hist_df = ak.air_quality_hist(city="北京", period="day", start_date="2020-01-01", end_date="2021-03-15")
          air_quality_hist_df.head()
          請(qǐng)求的數(shù)據(jù)預(yù)覽

          2. 數(shù)據(jù)預(yù)處理

          由于繪制熱力圖x軸是日期(1-31),y軸是年月。因此我們需要對(duì)原數(shù)據(jù)進(jìn)行寬表轉(zhuǎn)化和一些簡單的預(yù)處理。

          注意:處理過程詳情代碼注釋說明。

          import pandas as pd

          # 拷貝并進(jìn)行索引重置
          df = air_quality_hist_df[['aqi']].copy()
          df.reset_index(inplace=True)
          # 將time字段改為時(shí)間格式
          df.time = pd.to_datetime(df.time)
          # 新增年月字段,內(nèi)容為 x年x月,如2021年3月,為字符串格式
          df['年月'] = df.time.apply(lambda x:x.strftime('%Y{y}%m{m}').format(y="年",m="月"))
          # 新增日期字段,內(nèi)容為 1-31
          df['日期'] = df['time'].dt.day

          # 做透視處理,將長表轉(zhuǎn)化為寬表
          data = pd.pivot(df,
                          values='aqi',
                          index='年月',
                          columns='日期')
          # 轉(zhuǎn)化后部分月份不存在部分日期默認(rèn)為nan值,需要轉(zhuǎn)化為數(shù)字格式 float(無法轉(zhuǎn)化為int)
          data = data.astype('float')
          # 按照 索引年月倒序排序
          data.sort_index(ascending=False,inplace=True)

          data.head()
          處理后數(shù)據(jù)預(yù)覽


          3. 熱力圖繪制

          這里我們介紹兩種熱力圖繪制手法,其一是sns.heatmap(),其二是plotlyff.create_annotated_heatmap()

          3.1. seaborn的heatmap熱力圖

          import matplotlib.pyplot as plt
          import matplotlib.colors as mcolors
          import seaborn as sns

          #設(shè)置全局默認(rèn)字體 為 雅黑
          plt.rcParams['font.family'] = ['Microsoft YaHei'
          # 設(shè)置全局軸標(biāo)簽字典大小
          plt.rcParams["axes.labelsize"] = 14  
          # 設(shè)置背景
          sns.set_style("darkgrid",{"font.family":['Microsoft YaHei''SimHei']})  
          # 設(shè)置畫布長寬 和 dpi
          plt.figure(figsize=(18,8),dpi=100)
          # 自定義色卡
          cmap = mcolors.LinearSegmentedColormap.from_list("n",['#95B359','#D3CF63','#E0991D','#D96161','#A257D0','#7B1216']) 
          # 繪制熱力圖
          ax = sns.heatmap( data, cmap=cmap, vmax=300
                           annot=True# 熱力圖上顯示數(shù)值
                           fmt='0.f'# 數(shù)值格式
                           linewidths=0.5,) 
          ax.set_title( label='北京最近15個(gè)月空氣質(zhì)量AQI',fontdict = {'fontsize'16})
          # 將x軸刻度放在最上面
          ax.xaxis.set_ticks_position('top'
          效果

          3.2. plotly的熱力圖繪制

          對(duì)于plotly來說,plotly.express可以直接將滿足條件格式的dataframe數(shù)據(jù)用px.imshow()繪制,不過試了很久暫時(shí)沒學(xué)會(huì)怎么方便的將數(shù)值顯示在熱力圖上。找了半天發(fā)現(xiàn)plotly提供另外一種方式create_annotated_heatmap,專門用來顯示數(shù)值。

          px.imshow方法:

          import plotly.express as px
          # import plotly.graph_objs as go

          fig = px.imshow(data,
                         color_continuous_scale='Temps'
                         color_continuous_midpoint= 75 ,
                         range_color = [0,300],
                         title = '北京最近15個(gè)月空氣質(zhì)量AQI',
                         width=1200,
                         height=711,
                         )
          fig.update_layout(xaxis=dict(tickmode='linear'), # x軸全部顯示
                           )
          fig.show()
          px.imshow方法

          create_annotated_heatmap方法:

          以下重點(diǎn)介紹該方法

          • 由于繪圖的時(shí)候 順序和之前是反的,所以需要先進(jìn)行順序逆序調(diào)整;
          • 為了更好的根據(jù)aqi數(shù)值進(jìn)行顏色分配,我們可以對(duì)數(shù)據(jù)進(jìn)行分箱操作;
          • 為了讓顏色和空氣質(zhì)量指數(shù)級(jí)別色卡一致,我們可以自定義顏色色卡;
          • 為了更好的在熱力圖上顯示數(shù)值,需要將原來的float轉(zhuǎn)化為int,nan轉(zhuǎn)化為空字符。
          # 數(shù)據(jù)分箱操作
          data.sort_index(ascending=True,inplace=True)
          bins = [0,50,100,150,200,300,999]
          groups = [.1,.2,.3,.4,.5,.6]
          data1 = data.apply(lambda x: pd.cut(x,bins,labels=groups))
          data1.head()
          數(shù)據(jù)預(yù)覽
          import plotly.figure_factory as ff
          import numpy as np

          x = list(data.columns)
          y = list(data.index)
          z = data1.values.tolist()
          z_text = data3.fillna('').values.tolist() # data3 為初始未進(jìn)行格式轉(zhuǎn)化的透視寬表
          # 自定義色卡
          colorscale=[[0.0'rgb(0,153,102)'], [.1'rgb(211, 207, 99)'],
                      [.3'rgb(255, 153, 51)'], [.4'rgb(204, 97, 51)'],
                      [.5'rgb(102, 0, 153)'],[1.0'rgb(126, 0, 35)']]

          fig = ff.create_annotated_heatmap(z, x=x, y=y, 
                                            annotation_text=z_text, 
                                            colorscale=colorscale,
                                           )
          fig.update_layout(title ='北京最近15個(gè)月空氣質(zhì)量AQI',
                             width=1200,
                             height=711,
                           )
          # 將x軸刻度放在最上面
          fig.update_xaxes(side="top")
          fig.show()
          北京最近15個(gè)月空氣質(zhì)量AQI

          4. 附

          空氣質(zhì)量指數(shù)色卡對(duì)照表:

          空氣質(zhì)量評(píng)級(jí)

          matplotlib 熱力圖繪制參考

          https://matplotlib.org/stable/gallery/images_contours_and_fields/image_annotated_heatmap.html

          plotly元素周期表繪制案例:

          元素周期表
          # Add Periodic Table Data
          symbol = [['H''''''''''''''''''''''''''''''''''He'],
                   ['Li''Be''''''''''''''''''''''B''C''N''O''F''Ne'],
                   ['Na''Mg''''''''''''''''''''''Al''Si''P''S''Cl''Ar'],
                   ['K''Ca''Sc''Ti''V''Cr''Mn''Fe''Co''Ni''Cu''Zn''Ga''Ge''As''Se''Br''Kr'],
                   ['Rb ''Sr''Y''Zr''Nb''Mo''Tc''Ru''Rh''Pd''Ag''Cd''In''Sn''Sb''Te''I''Xe' ],
                   ['Cs''Ba''''Hf''Ta''W''Re''Os''Ir''Pt''Au''Hg''Tl''Pb''Bi''Po''At''Rn' ],
                   ['Fr''Ra''''Rf''Db''Sg''Bh''Hs''Mt''Ds''Rg''Cn''Uut''Fl''Uup''Lv''Uus''Uuo'],
                   ['''''La''Ce''Pr''Nd''Pm''Sm''Eu''Gd''Tb''Dy''Ho''Er''Tm''Yb''Lu'''],
                   ['''''Ac''Th''Pa''U''Np''Pu''Am''Cm''Bk''Cf''Es''Fm''Md''No''Lr''' ],
                   [''''''''''''''''''''''''''''''''''''],
                   ['''Alkali Metal''''''Transition Metal''''''Actinide''''''Semimetal''''''Halogen'''''''''],
                   ['''Alkaline Metal''''''Lanthanide''''''Basic Metal''''''Nonmetal''''''Noble Gas''''''''']]

          element = [['Hydrogen''''''''''''''''''''''''''''''''''Helium'],
                     ['Lithium''Beryllium''''''''''''''''''''''Boron''Carbon''Nitrogen''Oxygen''Fluorine''Neon'],
                     ['Sodium''Magnesium''''''''''''''''''''''Aluminium''Silicon''Phosphorus''Sulfur''Chlorine'' Argon'],
                     ['Potassium'' Calcium'' Scandium'' Titanium'' Vanadium'' Chromium',  'Manganese''Iron''Cobalt''Nickel''Copper''Zinc''Gallium''Germanium''Arsenic''Selenium''Bromine''Krypton'],
                     ['Rubidium''Strontium''Yttrium''Zirconium''Niobium''Molybdenum''Technetium''Ruthenium''Rhodium''Palladium''Silver''Cadmium''Indium''Tin''Antimony''Tellurium''Iodine''Xenon'],
                     [' Cesium'' Barium''',  'Hafnium''Tantalum''Tungsten''Rhenium''Osmium''Iridium''Platinum''Gold''Mercury''Thallium''Lead''Bismuth''Polonium''Astatine''Radon'],
                     [' Francium'' Radium''''Rutherfordium','Dubnium','Seaborgium','Bohrium','Hassium','Meitnerium','Darmstadtium','Roentgenium','Copernicium','Ununtrium','Ununquadium','Ununpentium','Ununhexium','Ununseptium','Ununoctium'],
                     ['''',  'Lanthanum''Cerium''Praseodymium''Neodymium''Promethium''Samarium''Europium''Gadolinium''Terbium''Dysprosium''Holmium''Erbium''Thulium''Ytterbium''Lutetium'''],
                     ['''''Actinium''Thorium''Protactinium''Uranium''Neptunium''Plutonium''Americium''Curium''Berkelium''Californium''Einsteinium','Fermium' ,'Mendelevium''Nobelium''Lawrencium''' ],
                     [''''''''''''''''''''''''''''''''''''],
                     [''''''''''''''''''''''''''''''''''''],
                     ['''''''''''''''''''''''''''''''''''']]

          atomic_mass = [[ 1.00794.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0,  4.002602],
               [ 6.9419.012182.0.0.0.0.0.0.0.0.0.0,  10.81112.010714.006715.999418.998403220.1797],
               [ 22.9897692824.3050.0.0.0.0.0.0.0.0.0.0,  26.981538628.085530.97376232.06535.45339.948],
               [ 39.098340.07844.95591247.86750.941551.996154.93804555.84558.93319558.693463.54665.3869.72372.6474.9216078.9679.90483.798],
               [ 85.467887.6288.9058591.22492.9063895.9698101.07102.90550106.42107.8682112.411114.818118.710121.760127.60126.90447131.293],
               [ 132.9054519137.327.0178.49180.94788183.84186.207190.23192.217195.084196.966569200.59204.3833207.2208.98040209210222],
               [223226.0267268271272270276281280285284289288293'unknown'294],
               [.0.0138.90547140.116140.90765144.242145150.36151.964157.25158.92535162.500164.93032167.259168.93421173.054174.9668.0],
               [.0.0227232.03806231.03588238.02891237244243247247251252257258259262.0],
               [.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0],
               [.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0],
               [.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0]]

          z = [[.8.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.01.],
               [.1.2.0.0.0.0.0.0.0.0.0.0.7.8.8.8.91.],
               [.1.2.0.0.0.0.0.0.0.0.0.0.6.7.8.8.91],
               [.1.2.3.3.3.3.3.3.3.3.3.3.6.7.8.8.91.],
               [.1.2.3.3.3.3.3.3.3.3.3.3.6.6.7.7.91.],
               [.1.2.4.3.3.3.3.3.3.3.3.3.6.6.6.7.91.],
               [.1.2.5.3.3.3.3.3.3.3.3.3.6.6.6.6.91.],
               [.0.0.4.4.4.4.4.4.4.4.4.4.4.4.4.4.4.0],
               [.0.0.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.0],
               [.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0],
               [.1.1.1.3.3.3.5.5.5.7.7.7.9.9.9.0.0.0],
               [.2.2.2.4.4.4.6.6.6.8.8.81.1.1..0.0.0]]

          # Display element name and atomic mass on hover
          hover=[]
          for x in range(len(symbol)):
              hover.append([i + '<br>' + 'Atomic Mass: ' + str(j)
                                for i, j in zip(element[x], atomic_mass[x])])

          # Invert Matrices
          symbol = symbol[::-1]
          hover = hover[::-1]
          z = z[::-1]

          # Set Colorscale
          colorscale=[[0.0'rgb(255,255,255)'], [.2'rgb(255, 255, 153)'],
                      [.4'rgb(153, 255, 204)'], [.6'rgb(179, 217, 255)'],
                      [.8'rgb(240, 179, 255)'],[1.0'rgb(255, 77, 148)']]

          # Make Annotated Heatmap
          fig = ff.create_annotated_heatmap(z, annotation_text=symbol, text=hover,
                                           colorscale=colorscale, font_colors=['black'], hoverinfo='text')
          fig.update_layout(title_text='Periodic Table')
          fig.show()
          以上就是本次全部內(nèi)容,演示代碼 ipynb 文件:
          https://pan.baidu.com/s/1iR8E8OAJ0KCm5Cw840Ellg 
          提取碼:0316
          如果文章對(duì)你有幫助,歡迎轉(zhuǎn)發(fā)/點(diǎn)贊/收藏~

          作者:可以叫我才哥

          來源:以叫我才哥


          _往期文章推薦_

          北京全年天氣狀況分析




          如需了解付費(fèi)精品課程教學(xué)答疑服務(wù)
          請(qǐng)?jiān)?strong style="max-width: 100%;overflow-wrap: break-word !important;box-sizing: border-box !important;">Crossin的編程教室內(nèi)回復(fù): 666

          瀏覽 34
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  不卡在线视频 | 久热中文在线 | 欧美影院屄 | 999欠欠欠兔费精品产 | 国产骚比|