Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hướng dẫn trực quan hóa kết quả API với Python (GitHub + Plotly)

Giới thiệu

API cho phép truy xuất dữ liệu thời gian thực. Ví dụ: tìm top repository JavaScript trên GitHub theo số sao (stars) và trực quan hóa bằng biểu đồ. Sử dụng requests gọi API, plotly vẽ biểu đồ tương tác.

Cài đặt

pip install requests plotly

Gọi GitHub Search API

import requests

url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}

response = requests.get(url, headers=headers)
print(f'Status: {response.status_code}')  # 200 = OK

data = response.json()
print(f'Keys: {data.keys()}')              # dict_keys(['total_count', 'incomplete_results', 'items'])
print(f'Total JS repos: {data["total_count"]}')  # ~11 triệu

Trích xuất thông tin repository

repos = data['items']
first = repos[0]
print(f'Keys per repo: {len(first)}')  # 74 fields

print(f"Top repo: {first['name']}")
print(f"Owner: {first['owner']['login']}")
print(f"Stars: {first['stargazers_count']}")
print(f"Watchers: {first['watchers_count']}")
print(f"Description: {first['description']}")

Thu thập dữ liệu cho biểu đồ

repo_names = []
repo_stars = []

for repo in repos:
    repo_names.append(repo['name'])
    repo_stars.append(repo['stargazers_count'])

print(repo_names[:5])   # ['freeCodeCamp', 'vue', 'react', 'd3', 'axios']
print(repo_stars[:5])   # [316079, 170000+, ...]

Vẽ biểu đồ với Plotly

from plotly.graph_objs import Bar
from plotly import offline

# Dữ liệu bar chart
data_plots = [{
    'type': 'bar',
    'x': repo_names,
    'y': repo_stars,
    'marker': {'color': 'rgb(60, 100, 150)'},
    'opacity': 0.7
}]

# Layout
layout = {
    'title': 'GitHub Most Popular JavaScript Projects',
    'xaxis': {'title': 'Repository'},
    'yaxis': {'title': 'Stars'},
    'hovermode': 'closest'
}

# Tạo figure và plot
fig = {'data': data_plots, 'layout': layout}
offline.plot(fig, filename='Most_Popular_JavaScript_Repos.html')

Kết quả

  • File Most_Popular_JavaScript_Repos.html được tạo.
  • Mở file trong trình duyệt: biểu đồ cột tương tác (zoom, hover xem chi tiết, pan).
  • Top repo: freeCodeCamp (~316k stars), vue, react, d3, axios...

Code hoàn chỉnh

import requests
from plotly.graph_objs import Bar
from plotly import offline

# 1. Gọi API
url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
resp = requests.get(url, headers=headers)
data = resp.json()

# 2. Trích xuất dữ liệu
repos = data['items']
names = [r['name'] for r in repos]
stars = [r['stargazers_count'] for r in repos]

# 3. Cấu hình biểu đồ
data_plots = [{'type': 'bar', 'x': names, 'y': stars,
               'marker': {'color': 'rgb(60,100,150)'}, 'opacity': 0.7}]
layout = {'title': 'GitHub Most Popular JavaScript Projects',
          'xaxis': {'title': 'Repository'},
          'yaxis': {'title': 'Stars'}}

# 4. Xuất HTML tương tác
offline.plot({'data': data_plots, 'layout': layout},
             filename='Most_Popular_JavaScript_Repos.html')

Mở rộng

  • Thêm filter: q=language:python&sort=stars&order=desc
  • Phân trang: tham số &page=2&per_page=100
  • Authentication: thêm header Authorization: token YOUR_TOKEN để tăng rate limit.
  • Dùng plotly.express cho code ngắn hơn: px.bar(x=names, y=stars)

Lưu ý

GitHub API không yêu cầu key cho public data nhưng giới hạn 60 requests/giờ/IP. Dùng token cá nhân để tăng lên 5000 requests/giờ.