Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแสดงผลข้อมูลจาก API ด้วย Python และ Plotly

บทนำ

API ให้ข้อมูลสดล่าสุด ตัวอย่างใช้ GitHub API ค้นหา repository JavaScript ที่มีดาวมากที่สุด แล้วแสดงผลด้วย Plotly

ขั้นตอน

  1. ติดตั้ง: pip install requests plotly
  2. เรียก GitHub API:
    import requests
    site_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars'
    headers = {'Accept': 'application/vnd.github.v3+json'}
    response = requests.get(site_url, headers=headers)
    response_json = response.json()
  3. ดึงข้อมูล: total_count, items (รายการ repo)
  4. เตรียมข้อมูลสำหรับ Plotly: ชื่อ repo และจำนวนดาว
  5. สร้าง Bar chart ด้วย Plotly offline:
    from plotly.graph_objs import Bar
    from plotly import offline
    
    repo_names = [repo['name'] for repo in repositories]
    repo_stars = [repo['stargazers_count'] for repo in repositories]
    
    data_plots = [{'type': 'bar', 'x': repo_names, 'y': repo_stars}]
    layout = {'title': 'GitHub Most Popular JavaScript Projects',
              'xaxis': {'title': 'Repository'}, 'yaxis': {'title': 'Stars'}}
    fig = {'data': data_plots, 'layout': layout}
    offline.plot(fig, filename='Most_Popular_JavaScript_Repos.html')

ผลลัพธ์

ได้ไฟล์ HTML แบบโต้ตอบ แสดง Bar chart ของ JavaScript repositories ที่มีดาวมากที่สุด