如何使用Pygal对存储库进行可视化

225 阅读6分钟

使用Pygal实现存储库的可视化

Pygal允许我们创建一系列的图形和图表。在这篇文章中,你将学习如何构建一个可视化,显示GitHub上Pythons的突出作品的对比。

简介

我们将创建一个交互式条形图,每个条形图的高度将代表该项目获得的星星总数。通过点击条形图,你会被送到项目的GitHub页面。

前提条件

读者需要具备以下条件才能跟上。

  • 一些Python的知识。
  • 关于Web APIs的知识。
  • 安装好[Pip]。

安装Pygal

要安装Pygal,请运行下面的命令。

pip install pygal

Pygal图库

Pygal图库是Pygal可以生成的图表的集合。

此外,你还可以通过探究每个图表的源代码来检查可视化的创建过程。

储存库的可视化

由于我们想在我们的可视化中加入一个以上的资源库。让我们设计一个循环,显示由API查询获得的每个存储库的特定数据,这样我们就可以把它们全部纳入到可视化中。

为了达到这个目的,运行下面的代码。

import requests
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' # Initiate an API request.
request = requests.get(url)
print("Status code:", request.status_code)
respons_dict = request.json()  # In a variable, save the API response.
print("Total repos:", respons_dict['total_count'])
# Examine the repository's details.
repos_dicts = respons_dict['items']
print("Repos found:", len(repos_dicts))
print("\nSelected info about each repository:")
for repos_dict in repos_dicts:   #go through all the dictionaries in repos_dicts.
    print('name-:', repos_dict['name'])  #write the name of the project
    print('owner-:', repos_dict['owner']['login']) #show the owner of the project
    print('stars-:', repos_dict['stargazers_count'])#print the number of stars the project has
    print('repo-:', repos_dict['html_url'])  # print the link to the project's repository
    print('Description-:', repos_dict['description']) # print the description of the project
   

我们在循环中打印每个项目的所有者、名称、拥有的星数、项目的描述以及它的GitHub URL。

既然我们有了一些相关的数据,那么我们就来构建一个GitHub上当前Python作品受欢迎程度的可视化表示。我们将创建一个柱状图。它将显示项目所获得的星星总数将由每个条形图的高度来表示。

为了完成这个任务,你可以运行下面的代码。

import requests
import pygal
from pygal.style import LightColorizedStyle as LCSe, LightenStyle as LSe
#  Start an API request.
url = 'https://api.github.com/search/repositories?q=language:python&sort=star'
request = requests.get(url)
print("Status  code:", request.status_code)
# In a variable, save the API response.
response_dictionary = request.json()
print("Total-repos:", response_dictionary['total_count'])
# Investigate the repository's contents.
repos_dicts = response_dictionary['items']
names, stars = [], []
for repos_dict in repos_dicts:
    names.append(repos_dict['name'])
    stars.append(repos_dict['stargazers_count'])
# Construct a visual picture
our_style = LSe('#333366', base_style=LCSe)
chart = pygal.Bar(style=our_style, x_label_rotation=45, show_legend=False)
chart.title = 'Python Works with the Most Stars on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('py_repos.svg')

首先,我们import pygal ,以及图表所需的Pygal styles 。我们将不断打印API请求返回的状态以及检测到的存储库的总量,以了解API调用是否成功。

我们需要生成两个空白列表来存放图表中要用到的数据。我们将使用每个项目的名称,以及星星的数量来分别标注和确定条形图的高度。每个作品的名称,以及它的星级数量,都被添加到循环内的这些列表中。

接下来,我们使用LightenStyle(alias LSe) ,创建一个基于蓝颜色色调的样式。为了使用LightColorizedStyle class(alias LCSe),我们另外给出了基本样式参数。之后,我们用Bar()创建一个简单的图表并提供给它our_style。

我们进一步给出两个额外的样式参数:我们将标签沿X轴旋转45度(x label rotation=45),并隐藏图例,因为我们只是在图表上显示一个系列(show legend=False)。x labels 属性被分配给列表名称,并给图形一个标题。

一旦我们加载数据,我们就给标签一个空字符串,因为我们不要求这个数据系列被标记。

下面我们可以看到结果的图表。

Python Works with the Most Stars on GitHub

完善Pygal图表

让我们微调一下我们的图表的外观。让我们首先通过建立一个配置对象来重新组织代码,其中包括我们所有的调整,以传递给Bar()

import requests
import pygal
from pygal.style import LightColorizedStyle as LCSe, LightenStyle as LSe
#  Start an API request.
url = 'https://api.github.com/search/repositories?q=language:python&sort=star'
request = requests.get(url)
print("Status  code:", request.status_code)
# In a variable, save the API response.
response_dictionary =request.json()
print("Total-repos:", response_dictionary['total_count'])
# Investigate the repository's contents.
repos_dicts = response_dictionary['items']
names, stars = [], []
for repos_dict in repos_dicts:
    names.append(repos_dict['name'])
    stars.append(repos_dict['stargazers_count'])
# Construct a visual picture
our_style = LSe('#333366', base_style=LCSe)
myconfig = pygal.Config()   # make an instance of Pygal’s Config class
myconfig.x_label_rotation = 45    # set the  attribute x_label_rotation to 45
myconfig.show_legend = False    #set the attribute show_legend to false
myconfig.title_font_size = 23   #choose the text size for the heading of the chart
myconfig.label_font_size = 13   # choose the text size for the minor label (The minor labels are the project names along the x-axis)   
myconfig.major_label_font_size = 17 #set the text size for the major label(The major labels are just the labels on the y-axis)
myconfig.truncate_label = 15  #To reduce the length of long project names to 15 characters, employ truncate label.
myconfig.show_y_guides = False  #set show_y_guides to False hide the horizontal lines on the graph
myconfig.width = 1000   #Choose a custom width for the graph so that it takes up maximum browser area
chart = pygal.Bar(myconfig, style=our_style)  #make an instance of Bar, and pass myconfig and style as arguments, respectively
chart.title = 'Python Projects with the Most Stars on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('py_repos.svg')

重新设计的图表如下所示。

The styling for the chart has been refined.

定制工具提示

将鼠标漂浮在一个单一的条形图上会显示它所代表的数据。这被称为工具提示,它通常显示一个项目所拥有的星星的总数。让我们做一个自定义工具提示来显示每个项目的描述。

让我们来看看一个例子,它使用了前三个项目,为每个条形图加上了自定义标签。我们将用下面的代码传递一个字典的列表,而不是将一个值的列表传递给add() ,。

import pygal
from pygal.style import LightColorizedStyle as LCSe, LightenStyle as LSe
our_style = LSe('#333366', base_style=LCSe)
chart = pygal.Bar(style=our_style, x_label_rotation=45, show_legend=False)
chart.title = 'Projects in Python '
chart.x_labels = ['public-apis', 'system-design-primer', 'Python']
plot_dictoinaries = [
 {'value': 144904, 'label': 'Description of public-apis.'},
 {'value': 139818, 'label': 'Description of system-design-primer.'},
 {'value': 113616, 'label': 'Description of Python.'},
 ]
chart.add('', plot_dictoinaries)
chart.render_to_file('bar_desc.svg')

列表plot_dictionaries 由三个字典组成,分别是public_apis 工作、system_design_primer 工作,最后是python 工作。每个字典中都有两个键:valuelabel

Pygal使用与value 链接的数字计算每个条形图的高度,并使用与label 链接的字符串为每个条形图创建工具提示

例如,第一个字典将产生一个表示项目的条形图,上面有144904 星,工具提示是"Description of public-apis."

add() 函数需要一个字符串和一个列表。我们将包含条形图的字典列表(plot dictionaries)传递给add() 。Pygal有一个默认的工具提示,除了我们给它定制的工具提示外,还包含星星的数量。

其中一个工具提示如下图所示。

Adding Custom Tooltips.

在我们的图表中包括可点击的链接

由于Pygal的存在,图表中的每个条形图也可以作为一个网页的重定向。我们只需在代码中添加一行代码就可以启用这一功能,利用我们为每个项目建立的字典。

我们为每个项目的plot_dictionary 创建一个新的key-value 对,使用键xlink

import requests
import pygal
from pygal.style import LightColorizedStyle as LCSe, LightenStyle as LSe
#  Initiate an API request
url = 'https://api.github.com/search/repositories?q=language:python&sort=star'
request = requests.get(url)
print("Status-code:", request.status_code)
# In a variable, save the API response.
response_dictionary = request.json()
print("Total repos:", response_dictionary['total_count'])
# Investigate the repository's contents.
repository_dicts = response_dictionary['items']
names, plot_dictionaries = [], []
for repository_dict in repository_dicts:
   names.append(repository_dict['name'])
   plot_dictionary = {
   'value': repository_dict['stargazers_count'],
   'label': repository_dict['description'],
   'xlink': repository_dict['html_url'],
   }
plot_dictionaries.append( plot_dictionary)
# Construct a visual picture
our_style = LSe('#333366', base_style=LCSe)
chart = pygal.Bar(style=our_style, x_label_rotation=45, show_legend=False)
chart.title = 'Most-Starred Python Works on GitHub'
chart.x_labels = names
chart.add('',  plot_dictionaries)
chart.render_to_file('py_rs.svg')

下面是上述代码的输出。

Adding Clickable Links to Our Graph

Pygal通过使用与'xlink.' 连接的URL,将每个条形图转换为活动链接,图表中的任何条形图都可以点击,在浏览器的单独标签中查看该项目的GitHub网站。

总结

在本教程中,我们已经看到了如何。

  • 安装Pygal。
  • 储存库的可视化。
  • 完善Pygal图表。
  • 添加自定义工具提示。
  • 为我们的图表添加可点击链接。