来源:《Python编程:从入门到实践》
python_repos.py
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 执行API调用并存储响应
URL = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(URL)
print("Status code:", r.status_code)
# 将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
# 探索有关仓库的信息
repo_dicts = response_dict['items']
names, stars = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
stars.append(repo_dict['stargazers_count'])
# 可视化
my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('python_repos.svg')
pygal以及要应用于图表的Pygal样式
使用LightenStyle类(别名LS)定义一种样式,并将其基色设置为深蓝色;还传递了实参base_style,已使用LightColorizedStyle类(别名LCS)
使用Bar()创建一个简单的条形图,并向它传递了my_style;还传递了两个样式实参:让标签绕x轴旋转45度(x_label_rotation=45),并隐藏了图例(show_legend=False)
python_repos.py
--snip--
# 可视化
my_style = LS('#333366', base_style=LCS)
my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000
chart = pygal.Bar(my_config, style=my_style)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('python_repos.svg')
truncate_label
将较长的项目名缩短为15个字符(如果将鼠标指向被截短的项目名,将显示完整的项目名)bar_descriptions.py
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = 'Python Projects'
chart.x_labels = ['awesome-python', 'system-design-primer', 'public-apis']
plot_dicts = [
{'value': 72145, 'label': 'Description of awesome-python'},
{'value': 71890, 'label': 'Description of system-design-primer'},
{'value': 60522, 'label': 'Description of public-apis'},
]
chart.add('', plot_dicts)
chart.render_to_file('bar_descriptions.svg')
python_repos.py
--snip--
# 探索有关仓库的信息
repo_dicts = response_dict['items']
names, plot_dicts = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'],
}
plot_dicts.append(plot_dict)
# 可视化
my_style = LS('#333366', base_style=LCS)
--snip--
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')
python_repos.py
--snip--
names, plot_dicts = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'],
'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)
--snip--