本文地址https://blog.csdn.net/sidens/article/details/80721379,转载请说明
使用web API来完成网络信息可视化
以下代码实现从github提取stars数最高的Python项目
import requests
import pygal
import json
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS
filename = 'data.json'
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
def get_data_from_API():
"""从API获取数据"""
#执行API调用并存储响应
r = requests.get(url)
print("Status code:",r.status_code)
#将API调用存储在一个变量中
response_dict = r.json()
with open(filename,'w') as f_write:
json.dump(response_dict,f_write)
def get_data_from_file():
"""若已从API获取过信息,则直接从文件中读取数据"""
try:
with open(filename,'r') as f_read:
reponse_dict = json.load(f_read)
except IOError:
get_data_from_API()
with open(filename,'r') as f_read:
reponse_dict = json.load(f_read)
return reponse_dict
def set_config():
"""设置图表属性"""
my_config = pygal.Config()
my_config.style = LS('#333366',base_style=LCS)
my_config.x_label_rotation = 75
my_config.show_legend = False#设置图例不可见
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 28
my_config.truncate_label = 15#x轴刻度最大15个字符
my_config.show_y_guides = False#y轴水平线不可见
my_config.width = 1000
return my_config
def get_plot_data(names,click_infos):
"""得到绘图需要的数据"""
reponse_dict = get_data_from_file()
repo_dicts = reponse_dict['items']
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
if repo_dict['description']:#防止description出现None
click_info = {
'value':repo_dict['stargazers_count'],
'label':repo_dict['description'],
'xlink':repo_dict['html_url']#可以点击柱状图进入对应的页面
}#key值必须是这三个以便编译器识别
else:
click_info = {
'value':repo_dict['stargazers_count'],
'label':'None',
'xlink':repo_dict['html_url']
}#key值必须是这三个以便编译器识别
click_infos.append(click_info)
if __name__ == '__main__':
names,click_infos = [],[]
get_plot_data(names, click_infos)
#使用pygal完成可视化
my_config = set_config()
hist = pygal.Bar(my_config)
hist.title = 'Python Project in GitHub'
hist.x_labels = names
hist.add('',click_infos)
hist.render_to_file('Python Project in GitHub.svg')
代码编写过程中出现一个小问题,利用get_plot_data()函数添加自定义提示工具时,由于部分项目缺少描述,导致字典的label键缺少对应的值,参考此文解决https://blog.csdn.net/waiwai3/article/details/77847783
由于GitHub API限制了访问量,为方便程序的运行和调试,本文选择第一次从API获取数据后将数据存储在本地磁盘以加快响应速度。
运行结果如下图所示:
由于在click_infos字典中添加了xlink键值对,图形具有良好的交互功能,点击项目对应的直方图,即可进入对应项目的GitHub网页。