代码简括:使用API对GitHub仓库中的项目进行数据可视化
import requests
from plotly.graph_objs import Bar
from plotly import offline
"""处理API响应"""
# 执行API调用并储存响应:
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
# 使用requests调用API,同时指定形参headers要求使用最新的GitHub API(最新的版本为第3版)
headers = {'Accept': 'application.com/vnd.github.v3+json'}
r = requests.get(url, headers=headers) # get():引起对象响应的方式,仅展示响应情况
print(f'状态码:{r.status_code}') # status_code:状态码,值为200时即请求成功
# 将API响应赋予一个变量:
resul1 = r.json() # API返回JSON格式的信息,因此用json()方法转换成Python字典
# 添加:表达请求成功,以示:请求成功的正确显示
if r.status_code == 200:
print("\n请求成功!")
print(f'{r}\n\n')
else:
print("\n请求失败!")
# 探索有关仓库的信息:
response_dicts = resul1['items'] # 多个包含单个Python仓库信息的字典
# #下行未改进之前:names, starts, labels = [], [], [] # labels是一处改进2
# 进行第三次改进后见下
links, starts, labels = [], [], []
for response_dict in response_dicts:
# 第三次改进前:
# names.append(response_dict['name'])
# 第三次改进后:
name = response_dict['name']
repo_url = response_dict['html_url']
link = f"{name}" # 指向项目的链接格式:{link_name}
links.append(repo_url)
starts.append(response_dict['stargazers_count'])
# 含改进2:补充
owner = response_dict['owner']['login'] # login:登录
description = response_dict['description']
label = f'{owner}
{description}' # plotly允许在文本元素中使用HTML代码,因此我们能在这两部分之间添加换行符:
labels.append(label)
# 可视化:
data = [{
'type': 'bar',
'x': links, # 改进3:此x轴可以互动,是一种超链接
'y': starts,
# 改进图表:
'hovertext': labels, # hover是css里用来定义, 当鼠标移到某个标签上时,这个标签显示的情况。
'marker': {
'color': 'rgb(60, 100, 150)',
'line': {'width': 1.5, 'color': 'rgb(25, 25, 25)'}, # 轮廓设置
}, # marker设置影响条形设计
'opacity': 0.6 # 条形的不透明度
}]
my_layout = {
# 含改进:
'title': 'GitHub上最受欢迎的项目',
'titlefont': {'size': 28},
'xaxis': {
'title': '仓库名',
'titlefont': {'size': 24}, # 改进处1
'tickfont': {'size': 14} # 刻度标签字号设置
},
'yaxis': {
'title': '星级',
'titlefont': {'size': 24}, # 改进处1
'tickfont': {'size': 14} # 刻度标签字号设置
},
}
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, 'Python仓库项目统计数据.html')