在Python中使用Pygal进行交互可视化

开发 后端
我们需要处理、分析和探索的大量数据;随着技术的进步,这个数字只会越来越大。现在,想象一下必须盯着电子表格中的数千行数据,试图找到隐藏的模式并追踪数字的变化。

[[382336]]

本文转载自微信公众号「Python学会」,作者Huangwei AI。转载本文请联系Python学会公众号。  

1前言

我们需要处理、分析和探索的大量数据;随着技术的进步,这个数字只会越来越大。现在,想象一下必须盯着电子表格中的数千行数据,试图找到隐藏的模式并追踪数字的变化。这就是数据可视化的切入点。拥有可视化的信息摘要比浏览电子表格更容易识别模式和趋势。由于数据分析的目的是获得见解和发现模式,将数据可视化将使其更有价值,更容易探索。不同类型的图表和图表使交流数据发现更快和更有效。

可视化数据的重要性不仅仅是简化数据的解释。可视化数据有很多好处,比如:

  • 显示数据随时间的变化。
  • 确定相关事件发生的频率。
  • 指出不同事件之间的相关性。
  • 分析不同机会的价值和风险。

在本文中,我们将介绍一个Python库,它可以帮助我们创建引人注目的、令人惊叹的、交互式的可视化。它就是Pygal

2Pygal介绍

当使用Python可视化数据时,大多数数据科学家使用臭名昭著的Matplotlib、Seaborn或Bokeh。然而,一个经常被忽视的库是Pygal。Pygal允许用户创建漂亮的交互式图,这些图可以以最佳的分辨率转换成svg,以便使用Flask或Django打印或显示在网页上。

熟悉Pygal

Pygal提供了各种各样的图表,我们可以使用它们来可视化数据,确切地说,Pygal中有14种图表类别,比如柱状图、柱状图、饼状图、树形图、测量图等等。

要使用Pygal,我们得先安装它。

  1. $ pip install pygal 

我们来画第一张图。我们将从最简单的字符开始,一个条形图。要使用Pygal绘制条形图,我们需要创建一个图表对象,然后向其添加一些值。

  1. bar_chart = pygal.Bar() 

我们将绘制0到5的阶乘。在这里,我定义了一个简单的函数来计算一个数字的阶乘,然后使用它生成一个数字从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)] 

现在,我们可以使用它来创建我们的绘图

  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)))) 

这将生成一个漂亮的交互图

如果我们想要绘制不同类型的图表,我们将遵循相同的步骤。您可能已经注意到,用于将数据链接到图表的主要方法是add方法。

现在,让我们开始基于实际数据构建一些东西。

应用

接下来,我将使用美国COVID-19病例数据集来解释Pygal的不同方面。

首先,为了确保一切顺利进行,我们需要确保两件事:

  • Pandas和Pygal都装上了。
  • 在jupiter Notebook中,我们需要启用IPython显示和HTML选项。
  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. ""

现在我们已经设置好了,我们可以开始使用Pandas来探索我们的数据,然后使用不同类型的图表来操作和准备它。

  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"

该数据集包含基于日期、县和州的COVID-19病例和死亡信息。我们可以通过data.column看出这一点。列,以了解数据的形状。执行该命令将返回:

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

我们可以获得一个10行的样本来查看我们的数据帧是什么样子的。

  1. data.sample(10) 

条形图

让我们首先绘制一个柱状图,显示每个状态的案例数的平均值。为此,我们需要执行以下步骤:

将数据按状态分组,提取每个状态的案例号,然后计算每个状态的平均值。

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

开始构建数据并将其添加到条形图中。

  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)))) 

瞧,我们有一个条形图。我们可以通过从图例列表中取消选择来删除数据,也可以通过重新选择来重新添加数据。

柱状图的完整代码

  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

条形图有助于显示整体数据,但如果我们想要更具体,我们可以选择不同类型的char,即treemap。树图对于显示数据中的类别非常有用。例如,在我们的数据集中,我们有基于每个州每个县的病例数量。柱状图显示了每个州的均值,但我们看不到每个州每个县的病例分布。一种方法是使用树图。

假设我们想要查看案例数量最多的10个州的详细案例分布情况。然后,在绘制数据之前,我们需要先对数据进行操作。

我们需要根据案例对数据进行排序,然后按州进行分组。

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

使用排序列表来获得案例数量最多的前10个州。

  1. top_10_states = sort_by_cases[:10] 

使用这个子列表来创建我们的树图。

  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)))) 

然而,这个树图没有被标记,所以当我们悬停在方块上时,我们无法看到县名。我们将在该州的所有县街区上看到该州的名称。为了避免这种情况并将县名添加到我们的treemap中,我们需要标记向图表提供的数据。

  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)))) 

在此之前,我们的数据每天都会更新。因此,每个县将进行几次重复。因为我们关心每个县的病例总数,所以在将数据添加到树图之前,我们需要清理数据。

  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,并绘制它的标记版本。

  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)))) 

太棒了!现在我们的树形图被标记了。如果将鼠标悬停在这些块上,就可以看到县的名称、州和该县的病例数。

完整的代码

  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)))) 

饼状图

我们可以用另一种形式来展示这一信息,那就是用饼状图来展示案例数量最多的10个州。使用饼状图,我们可以看到一个州的案例数相对于其他州的百分比。

由于我们已经完成了所有的数据帧操作,我们可以使用它来立即创建饼图。

  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)))) 
 

 

责任编辑:武晓燕 来源: Python学会
相关推荐

2023-12-18 15:02:00

PyechartsPython数据可视化工具

2022-06-29 10:58:51

软件迁移学习

2022-08-26 09:15:58

Python可视化plotly

2017-05-08 15:47:06

2023-02-15 08:24:12

数据分析数据可视化

2021-11-09 08:15:18

Grafana 数据可视化运维

2024-04-01 11:53:42

PlotlyPython数据可视化

2011-06-13 18:54:12

2015-08-20 10:00:45

可视化

2020-03-11 14:39:26

数据可视化地图可视化地理信息

2021-10-11 08:04:22

Python数据行程

2020-06-30 20:55:17

PygalPython编程语言

2021-06-09 11:26:37

BokehPython可视化

2023-05-06 12:57:34

Python工具

2014-05-28 15:23:55

Rave

2020-07-16 15:20:37

MatplotlibPython可视化

2020-05-26 11:34:46

可视化WordCloud

2021-02-21 08:11:46

PythonDash工具

2022-02-23 09:50:52

PythonEchartspyecharts

2009-04-21 14:26:41

可视化监控IT管理摩卡
点赞
收藏

51CTO技术栈公众号