Python学习之: 使用web API 分析数据,通过pygal库实现可视化,生成svg文件(可通过浏览器打开)

#import sys
#import io
#改变标准输出的默认编码,解决 gbk 报错问题
#sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') 

import requests

import pygal
#pygal是一个SVG图表库。一种矢量图格式。
#全称Scalable Vector Graphics -- 可缩放矢量图形。
#导入样式
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
#打印http 状态码:200 表示成功, 404 地址不存在或请求错误
print("Status code:", r.status_code)

#返回数据保存入变量中
response_dict = r.json()
#打印字典的 ‘total_count’键
print("Total repositories:", response_dict['total_count'])
repo_dicts = response_dict['items']
print("Repositories returned: ", len(repo_dicts))

names, plot_dicts = [], []
#提取仓库中的元素
for repo_dict in repo_dicts:
	names.append(repo_dict['name'])
	plot_dict = {
		'value': repo_dict['stargazers_count'],
		'lalel': repo_dict['description'],
		'xlink': repo_dict['html_url'],
	} 
	plot_dicts.append(plot_dict)


''' 数据可视化 '''
#样式设置, 基色为 '#333366'深蓝色
my_style = LS('#333366', base_style=LCS)

#设置配置
my_config = pygal.Config()
# x坐标旋转45度
my_config.x_label_rotation = 45
# 隐藏左上角图例
my_config.show_legend = False
#标题
my_config.title_font_size = 24
#副标签,包括x轴和y轴大部分
my_config.label_font_size = 15
#主标签是y轴某数倍数,相当于一个特殊的刻度,让关键数据点更醒目
my_config.major_label_font_size = 50
# x轴标签显示项目名称长度设置为15个字符,如果你将鼠标指向屏幕上被截短的标签,将显示完整
my_config.truncate_label = 15
#隐藏水平虚线
my_config.show_y_guides = False
#设置图表宽度
my_config.width = 1000
#my_config.height = 300

#Bar 柱状图
chart = pygal.Bar(my_config,style = my_style)
#设置标题
chart.title = 'Most-Starred Python Projects on GitHub'

chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')

你可能感兴趣的:(Python)