自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

在Python中使用Pygal進(jìn)行交互可視化

開發(fā) 后端
我們需要處理、分析和探索的大量數(shù)據(jù);隨著技術(shù)的進(jìn)步,這個(gè)數(shù)字只會越來越大?,F(xiàn)在,想象一下必須盯著電子表格中的數(shù)千行數(shù)據(jù),試圖找到隱藏的模式并追蹤數(shù)字的變化。

[[382336]]

本文轉(zhuǎn)載自微信公眾號「Python學(xué)會」,作者Huangwei AI。轉(zhuǎn)載本文請聯(lián)系Python學(xué)會公眾號。  

1前言

我們需要處理、分析和探索的大量數(shù)據(jù);隨著技術(shù)的進(jìn)步,這個(gè)數(shù)字只會越來越大?,F(xiàn)在,想象一下必須盯著電子表格中的數(shù)千行數(shù)據(jù),試圖找到隱藏的模式并追蹤數(shù)字的變化。這就是數(shù)據(jù)可視化的切入點(diǎn)。擁有可視化的信息摘要比瀏覽電子表格更容易識別模式和趨勢。由于數(shù)據(jù)分析的目的是獲得見解和發(fā)現(xiàn)模式,將數(shù)據(jù)可視化將使其更有價(jià)值,更容易探索。不同類型的圖表和圖表使交流數(shù)據(jù)發(fā)現(xiàn)更快和更有效。

可視化數(shù)據(jù)的重要性不僅僅是簡化數(shù)據(jù)的解釋??梢暬瘮?shù)據(jù)有很多好處,比如:

  • 顯示數(shù)據(jù)隨時(shí)間的變化。
  • 確定相關(guān)事件發(fā)生的頻率。
  • 指出不同事件之間的相關(guān)性。
  • 分析不同機(jī)會的價(jià)值和風(fēng)險(xiǎn)。

在本文中,我們將介紹一個(gè)Python庫,它可以幫助我們創(chuàng)建引人注目的、令人驚嘆的、交互式的可視化。它就是Pygal

2Pygal介紹

當(dāng)使用Python可視化數(shù)據(jù)時(shí),大多數(shù)數(shù)據(jù)科學(xué)家使用臭名昭著的Matplotlib、Seaborn或Bokeh。然而,一個(gè)經(jīng)常被忽視的庫是Pygal。Pygal允許用戶創(chuàng)建漂亮的交互式圖,這些圖可以以最佳的分辨率轉(zhuǎn)換成svg,以便使用Flask或Django打印或顯示在網(wǎng)頁上。

熟悉Pygal

Pygal提供了各種各樣的圖表,我們可以使用它們來可視化數(shù)據(jù),確切地說,Pygal中有14種圖表類別,比如柱狀圖、柱狀圖、餅狀圖、樹形圖、測量圖等等。

要使用Pygal,我們得先安裝它。

  1. $ pip install pygal 

我們來畫第一張圖。我們將從最簡單的字符開始,一個(gè)條形圖。要使用Pygal繪制條形圖,我們需要創(chuàng)建一個(gè)圖表對象,然后向其添加一些值。

  1. bar_chart = pygal.Bar() 

我們將繪制0到5的階乘。在這里,我定義了一個(gè)簡單的函數(shù)來計(jì)算一個(gè)數(shù)字的階乘,然后使用它生成一個(gè)數(shù)字從0到5的階乘列表。

  1. def factorial(n): 
  2.     if n == 1 or n == 0: 
  3.         return 1 
  4.     else
  5.         return n * factorial(n-1) 
  6. fact_list = [factorial(i) for i in range(11)] 

現(xiàn)在,我們可以使用它來創(chuàng)建我們的繪圖

  1. bar_chart = pygal.Bar(height=400) 
  2. bar_chart.add('Factorial', fact_list) 
  3. display(HTML(base_html.format(rendered_chart=bar_chart.render(is_unicode=True)))) 

這將生成一個(gè)漂亮的交互圖

如果我們想要繪制不同類型的圖表,我們將遵循相同的步驟。您可能已經(jīng)注意到,用于將數(shù)據(jù)鏈接到圖表的主要方法是add方法。

現(xiàn)在,讓我們開始基于實(shí)際數(shù)據(jù)構(gòu)建一些東西。

應(yīng)用

接下來,我將使用美國COVID-19病例數(shù)據(jù)集來解釋Pygal的不同方面。

首先,為了確保一切順利進(jìn)行,我們需要確保兩件事:

  • Pandas和Pygal都裝上了。
  • 在jupiter Notebook中,我們需要啟用IPython顯示和HTML選項(xiàng)。
  1. from IPython.display import display, HTML 
  2. base_html = ""
  3. <!DOCTYPE html> 
  4. <html> 
  5.   <head> 
  6.   <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/svg.jquery.js"></script> 
  7.   <script type="text/javascript" src="https://kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js""></script> 
  8.   </head> 
  9.   <body> 
  10.     <figure> 
  11.       {rendered_chart} 
  12.     </figure> 
  13.   </body> 
  14. </html> 
  15. ""

現(xiàn)在我們已經(jīng)設(shè)置好了,我們可以開始使用Pandas來探索我們的數(shù)據(jù),然后使用不同類型的圖表來操作和準(zhǔn)備它。

  1. import pygal 
  2. import pandas as pd 
  3. data = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv"

該數(shù)據(jù)集包含基于日期、縣和州的COVID-19病例和死亡信息。我們可以通過data.column看出這一點(diǎn)。列,以了解數(shù)據(jù)的形狀。執(zhí)行該命令將返回:

  1. Index(['date''county''state''fips''cases''deaths'], dtype='object'

我們可以獲得一個(gè)10行的樣本來查看我們的數(shù)據(jù)幀是什么樣子的。

  1. data.sample(10) 

條形圖

讓我們首先繪制一個(gè)柱狀圖,顯示每個(gè)狀態(tài)的案例數(shù)的平均值。為此,我們需要執(zhí)行以下步驟:

將數(shù)據(jù)按狀態(tài)分組,提取每個(gè)狀態(tài)的案例號,然后計(jì)算每個(gè)狀態(tài)的平均值。

  1. mean_per_state = data.groupby('state')['cases'].mean() 

開始構(gòu)建數(shù)據(jù)并將其添加到條形圖中。

  1. barChart = pygal.Bar(height=400) 
  2. [barChart.add(x[0], x[1]) for x in mean_per_state.items()] 
  3. display(HTML(base_html.format(rendered_chart=barChart.render(is_unicode=True)))) 

瞧,我們有一個(gè)條形圖。我們可以通過從圖例列表中取消選擇來刪除數(shù)據(jù),也可以通過重新選擇來重新添加數(shù)據(jù)。

柱狀圖的完整代碼

  1. #Import needed libraries 
  2. import pygal 
  3. import pandas as pd 
  4. #Parse the dataframe 
  5. data = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv")  
  6. #Get the mean number of cases per states 
  7. mean_per_state = data.groupby('state')['cases'].mean() 
  8. #Draw the bar chart 
  9. barChart = pygal.Bar(height=400) 
  10. [barChart.add(x[0], x[1]) for x in mean_per_state.items()] 
  11. display(HTML(base_html.format(rendered_chart=barChart.render(is_unicode=True)))) 

Treemap

條形圖有助于顯示整體數(shù)據(jù),但如果我們想要更具體,我們可以選擇不同類型的char,即treemap。樹圖對于顯示數(shù)據(jù)中的類別非常有用。例如,在我們的數(shù)據(jù)集中,我們有基于每個(gè)州每個(gè)縣的病例數(shù)量。柱狀圖顯示了每個(gè)州的均值,但我們看不到每個(gè)州每個(gè)縣的病例分布。一種方法是使用樹圖。

假設(shè)我們想要查看案例數(shù)量最多的10個(gè)州的詳細(xì)案例分布情況。然后,在繪制數(shù)據(jù)之前,我們需要先對數(shù)據(jù)進(jìn)行操作。

我們需要根據(jù)案例對數(shù)據(jù)進(jìn)行排序,然后按州進(jìn)行分組。

  1. sort_by_cases = data.sort_values(by=['cases'],ascending=False).groupby(['state'])['cases'].apply(list) 

使用排序列表來獲得案例數(shù)量最多的前10個(gè)州。

  1. top_10_states = sort_by_cases[:10] 

使用這個(gè)子列表來創(chuàng)建我們的樹圖。

  1. treemap = pygal.Treemap(height=400) 
  2. [treemap.add(x[0], x[1][:10]) for x in top_10_states.items()] 
  3. display(HTML(base_html.format(rendered_chart=treemap.render(is_unicode=True)))) 

然而,這個(gè)樹圖沒有被標(biāo)記,所以當(dāng)我們懸停在方塊上時(shí),我們無法看到縣名。我們將在該州的所有縣街區(qū)上看到該州的名稱。為了避免這種情況并將縣名添加到我們的treemap中,我們需要標(biāo)記向圖表提供的數(shù)據(jù)。

  1. #Import needed libraries 
  2. import pygal 
  3. import pandas as pd 
  4. #Parse the dataframe 
  5. data = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv")  
  6. #Sort states by cases count 
  7. sort_by_cases = data.sort_values(by=['cases'],ascending=False).groupby(['state'])['cases'].apply(list) 
  8. #Get the top 10 states with the highest number of cases 
  9. top_10_states = sort_by_cases[:10] 
  10. #Draw the treemap 
  11. treemap = pygal.Treemap(height=400) 
  12. [treemap.add(x[0], x[1][:10]) for x in top_10_states.items()] 
  13. display(HTML(base_html.format(rendered_chart=treemap.render(is_unicode=True)))) 

在此之前,我們的數(shù)據(jù)每天都會更新。因此,每個(gè)縣將進(jìn)行幾次重復(fù)。因?yàn)槲覀冴P(guān)心每個(gè)縣的病例總數(shù),所以在將數(shù)據(jù)添加到樹圖之前,我們需要清理數(shù)據(jù)。

  1. #Get the cases by county for all states 
  2. cases_by_county = data.sort_values(by=['cases'],ascending=False).groupby(['state'], axis=0).apply( 
  3.     lambda x : [{"value" : l, "label" : c } for l, c in zip(x['cases'], x['county'])]) 
  4. cases_by_county= cases_by_county[:10] 
  5. #Create a new dictionary that contains the cleaned up version of the data 
  6. clean_dict = {} 
  7. start_dict= cases_by_county.to_dict() 
  8. for key in start_dict.keys(): 
  9.     values = [] 
  10.     labels = [] 
  11.     county = [] 
  12.     for item in start_dict[key]: 
  13.         if item['label'not in labels: 
  14.             labels.append(item['label']) 
  15.             values.append(item['value']) 
  16.         else
  17.             i = labels.index(item['label']) 
  18.             values[i] += item['value'
  19.      
  20.     for l,v in zip(labels, values): 
  21.         county.append({'value':v, 'label':l}) 
  22.     clean_dict[key] = county 
  23. #Convert the data to Pandas series to add it to the treemap 
  24. new_series = pd.Series(clean_dict) 

然后,我們可以將該系列添加到treemap,并繪制它的標(biāo)記版本。

  1. treemap = pygal.Treemap(height=200) 
  2. [treemap.add(x[0], x[1][:10]) for x in new_series.iteritems()] 
  3. display(HTML(base_html.format(rendered_chart=treemap.render(is_unicode=True)))) 

太棒了!現(xiàn)在我們的樹形圖被標(biāo)記了。如果將鼠標(biāo)懸停在這些塊上,就可以看到縣的名稱、州和該縣的病例數(shù)。

完整的代碼

  1. #Import needed libraries 
  2. import pygal 
  3. import pandas as pd 
  4. #Parse the dataframe 
  5. data = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv")  
  6. #Get the cases by county for all states 
  7. cases_by_county = data.sort_values(by=['cases'],ascending=False).groupby(['state'], axis=0).apply( 
  8.     lambda x : [{"value" : l, "label" : c } for l, c in zip(x['cases'], x['county'])]) 
  9. cases_by_county= cases_by_county[:10] 
  10. #Create a new dictionary that contains the cleaned up version of the data 
  11. clean_dict = {} 
  12. start_dict= cases_by_county.to_dict() 
  13. for key in start_dict.keys(): 
  14.     values = [] 
  15.     labels = [] 
  16.     county = [] 
  17.     for item in start_dict[key]: 
  18.         if item['label'not in labels: 
  19.             labels.append(item['label']) 
  20.             values.append(item['value']) 
  21.         else
  22.             i = labels.index(item['label']) 
  23.             values[i] += item['value'
  24.      
  25.     for l,v in zip(labels, values): 
  26.         county.append({'value':v, 'label':l}) 
  27.     clean_dict[key] = county 
  28. #Convert the data to Pandas series to add it to the treemap 
  29. new_series = pd.Series(clean_dict) 
  30. #Draw the treemap 
  31. treemap = pygal.Treemap(height=200) 
  32. [treemap.add(x[0], x[1][:10]) for x in new_series.iteritems()] 
  33. display(HTML(base_html.format(rendered_chart=treemap.render(is_unicode=True)))) 

餅狀圖

我們可以用另一種形式來展示這一信息,那就是用餅狀圖來展示案例數(shù)量最多的10個(gè)州。使用餅狀圖,我們可以看到一個(gè)州的案例數(shù)相對于其他州的百分比。

由于我們已經(jīng)完成了所有的數(shù)據(jù)幀操作,我們可以使用它來立即創(chuàng)建餅圖。

  1. first10 = list(sort_by_cases.items())[:10] 
  2. [pi_chart.add(x[0], x[1]) for x in first10] 
  3. display(HTML(base_html.format(rendered_chart=pi_chart.render(is_unicode=True)))) 

餅狀圖的完整代碼

  1. #Import needed libraries 
  2. import pygal 
  3. import pandas as pd 
  4. #Parse the dataframe 
  5. data = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv")  
  6. #Get the mean number of cases per states 
  7. sort_by_cases = data.sort_values(by=['cases'],ascending=False).groupby(['state'])['cases'].apply(list) 
  8. #Draw the bar chart 
  9. pi_chart = pygal.Pie(height=400) 
  10. #Get the top 10 states 
  11. first10 = list(sort_by_cases.items())[:10] 
  12. [pi_chart.add(x[0], x[1]) for x in first10] 
  13. display(HTML(base_html.format(rendered_chart=pi_chart.render(is_unicode=True)))) 
 

 

責(zé)任編輯:武曉燕 來源: Python學(xué)會
相關(guān)推薦

2022-08-26 09:15:58

Python可視化plotly

2023-12-18 15:02:00

PyechartsPython數(shù)據(jù)可視化工具

2022-06-29 10:58:51

軟件遷移學(xué)習(xí)

2025-04-02 07:37:29

2017-05-08 15:47:06

2023-02-15 08:24:12

數(shù)據(jù)分析數(shù)據(jù)可視化

2021-11-09 08:15:18

Grafana 數(shù)據(jù)可視化運(yùn)維

2024-08-02 10:30:39

StreamlitPython庫數(shù)據(jù)驅(qū)動

2024-12-24 12:00:00

Matplotlib可視化分析Python

2024-04-01 11:53:42

PlotlyPython數(shù)據(jù)可視化

2024-12-24 07:30:00

Seaborn可視化Python

2020-03-11 14:39:26

數(shù)據(jù)可視化地圖可視化地理信息

2011-06-13 18:54:12

2015-08-20 10:00:45

可視化

2021-10-11 08:04:22

Python數(shù)據(jù)行程

2020-06-30 20:55:17

PygalPython編程語言

2021-06-09 11:26:37

BokehPython可視化

2014-05-28 15:23:55

Rave

2023-05-06 12:57:34

Python工具

2017-10-14 13:54:26

數(shù)據(jù)可視化數(shù)據(jù)信息可視化
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號