python 图表_Python入门学习系列——使用Python调用Web API实现图表统计
使用Python調用Web API實現圖表統計
Web API:Web應用編程接口,用于URL請求特定信息的程序交互,請求的數據大多以非常易于處理的格式返回,比如JSON或CSV等。
本文將使用Python中的requests包實現Web API的調用,API接口來自于GitHub提供的公用API,最后使用圖表對API調用的結果進行圖表統計顯示。
API地址為:https://api.github.com/search/repositories?q=language:python&sort=stars,該調用返回GitHub當前托管了多少個Python項目,包括最受歡迎的Python倉庫的信息,結果如下:
{
"total_count": 3114636,
"incomplete_results": false,
"items": [
{
"id": 21289110,
"node_id": "MDEwOlJlcG9zaXRvcnkyMTI4OTExMA==",
"name": "awesome-python",
"full_name": "vinta/awesome-python",
"private": false,
"owner": {
"login": "vinta",
"id": 652070,
"node_id": "MDQ6VXNlcjY1MjA3MA==",
"avatar_url": "https://avatars2.githubusercontent.com/u/652070?v=4",
...
使用Web API
如果想要Python調用Web API,需要使用requests包,該包用于處理網絡請求和返回響應信息。可以使用pip工具輸入以下命令進行安裝:
$ pip install --user requests
使用requests處理API響應
import requests
#執行API調用并存儲響應
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
# 調用url,將響應對象存儲在變量r中
r=requests.get(url)
# 查看請求返回的http 狀態碼,200表示請求成功
print("Stauts Code",r.status_code)
# 使用json()將API的響應信息(json格式)轉換為一個Python字典或JSON對象
response_dict=r.json()
#處理結果
print(response_dict.keys())
執行后,輸出結果如下:
Stauts Code 200
dict_keys(['total_count', 'incomplete_results', 'items'])
對返回的結果進行深度處理
針對上述API返回的結果,進一步的進行解析,返回每一個倉庫的詳細信息。具體見代碼注釋說明:
import requests
#執行API調用并存儲響應
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
# 調用url,將響應對象存儲在變量r中
r=requests.get(url)
# 查看請求返回的http 狀態碼,200表示請求成功
print("Stauts Code",r.status_code)
# 使用json()將API的響應信息(json格式)轉換為一個Python字典或JSON對象
response_dict=r.json()
# 獲取GitHub包含的Python庫數量
print("Total repositories:",response_dict["total_count"])
#探索有關倉庫的信息,items是由多個字典組成的列表,每一個字典包含一個倉庫信息
repo_dicts=response_dict['items']
print("Repositories returned:",len(repo_dicts))
##研究第一個倉庫
#repo_dict=repo_dicts[0]
#print("\nKeys:",len(repo_dict))
#for key in sorted(repo_dict.keys()):
# print(key)
print("\nSelected information about each repository:")
# 循環遍歷獲取每一個倉庫的詳細信息
for repo_dict in repo_dicts:
# 項目名稱
print('\nName:', repo_dict['name'])
# 鍵owner來訪問表示所有者的字典,再使用鍵key來獲取所有者的登錄名。
print('Owner:', repo_dict['owner']['login'])
print('Stars:', repo_dict['stargazers_count'])
print('Repository:', repo_dict['html_url'])
print('Created:', repo_dict['created_at'])
print('Updated:', repo_dict['updated_at'])
print('Description:', repo_dict['description'])
上述代碼返回的結果如下:
Stauts Code 200
Total repositories: 3114623
Repositories returned: 30
Selected information about each repository:
Name: awesome-python
Owner: vinta
Stars: 56507
Repository: https://github.com/vinta/awesome-python
Created: 2014-06-27T21:00:06Z
Updated: 2018-10-21T22:26:31Z
Description: A curated list of awesome Python frameworks, libraries, software an
d resources
Name: system-design-primer
Owner: donnemartin
Stars: 50650
Repository: https://github.com/donnemartin/system-design-primer
Created: 2017-02-26T16:15:28Z
Updated: 2018-10-21T22:02:07Z
Description: Learn how to design large-scale systems. Prep for the system design
interview. Includes Anki flashcards.
Name: models
....
注意:大多數API都存在速率限制,即你在特定時間內可執行的請求數存在限制。要獲悉你是否接近了GitHub的限制,請在瀏覽器中輸入https://api.github.com/rate_limit,你將看到類似于下面的響應:
通過結果可以指定,極限為每分鐘10個請求。
使用Pygal對分析的結果進行可視化
完整代碼如下所示,具體說明見代碼中的詳細注釋:
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'
# 調用url,將響應對象存儲在變量r中
r=requests.get(url)
# 查看請求返回的http 狀態碼,200表示請求成功
print("Stauts Code",r.status_code)
# 使用json()將API的響應信息(json格式)轉換為一個Python字典或JSON對象
response_dict=r.json()
# 獲取GitHub包含的Python庫數量
print("Total repositories:",response_dict["total_count"])
#探索有關倉庫的信息,items是由多個字典組成的列表,每一個字典包含一個倉庫信息
repo_dicts=response_dict['items']
#print("Repositories returned:",len(repo_dicts))
## 創建兩個空列表存儲包含在圖表中的信息,名稱用于條形圖表的標簽,星的數量用于確定條形圖表的高度
#names,stars=[],[]
# plot_dicts用于添加自定義工具提示
names,plot_dicts=[],[]
for repo_dict in repo_dicts:
names.append(repo_dict["name"])
# 并不是每個節點一定有description,所以加if判斷
if repo_dict["description"]:
plot_dict={
# Pygal根據與鍵'value'相關聯的數字來確定條形的高度
'value':int(repo_dict["stargazers_count"]),
# 使用與'label'相關聯的字符串給條形創建工具提示
'label':repo_dict["description"],
# 為條形圖表添加可點擊的鏈接
'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)
#可視化,定義樣式,將其基色設置為深藍色,并傳入LightColorizedStyle
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 = 14
# 主標簽字體大小,y軸上為5000整數倍的刻度
my_config.major_label_font_size = 18
# 將較長的項目名縮短為15個字符
my_config.truncate_label = 15
# 隱藏圖表中的水平線
my_config.show_y_guides = False
# 設置了自定義寬度
my_config.width = 1000
# 使用Bar()創建一個簡單的條形圖
# x_label_rotation=45:表示讓標簽繞x軸旋轉45度
# show_legend=False:表示隱藏了圖例
# chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
# 將上述的配置進行改進,分裝為一個my_config對象
# 傳遞配置設置
chart=pygal.Bar(my_config,style=my_style)
chart.title="Most-Starred Python Projects on GitHub"
chart.x_labels=names
# 暫不需要添加標簽
#chart.add('',stars)
# 添加工具提示需要的字典列表
chart.add('',plot_dicts)
chart.render_to_file("python_repos.svg")
#print("\nSelected information about each repository:")
## 循環遍歷獲取每一個倉庫的詳細信息
#for repo_dict in repo_dicts:
# # 項目名稱
# print('\nName:', repo_dict['name'])
# # 鍵owner來訪問表示所有者的字典,再使用鍵key來獲取所有者的登錄名。
# print('Owner:', repo_dict['owner']['login'])
# print('Stars:', repo_dict['stargazers_count'])
# print('Repository:', repo_dict['html_url'])
# print('Created:', repo_dict['created_at'])
# print('Updated:', repo_dict['updated_at'])
# print('Description:', repo_dict['description'])
上述代碼中,使用了pygal.Bar()方法創建一個簡單的條形圖,并向它傳遞了my_style。同時還傳遞了另外兩個樣式實參:讓標簽繞x軸旋轉45度(x_label_rotation=45),并隱藏了圖例(show_legend=False),因為只在圖表中繪制一個數據系列。
執行代碼顯示結果如下圖所示:
參考資源
《Python編程:從入門到實踐》
本文后續會隨著知識的積累不斷補充和更新,內容如有錯誤,歡迎指正。
最后一次更新時間:2018-10-23
總結
以上是生活随笔為你收集整理的python 图表_Python入门学习系列——使用Python调用Web API实现图表统计的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: “巧未能胜拙”下一句是什么
- 下一篇: 求一个90后的女生微信网名
