当前位置: 首页 > news >正文

python-数据可视化-使用API

使用Web应用程序编程接口 (API)自动请求网站的特定信息而不是整个网页,再对这些信息进行可视化

使用Web API

Web API是网站的一部分,用于与使用具体URL请求特定信息的程序交互。这种请求称为API调用 。请求的数据将以易于处理的格式(如JSON或CSV)返回。依赖于外部数据源的大多数应用程序依赖于API调用,如集成社交媒体网站的应用程序

Git和GitHub

GitHub的名字源自Git,后者是一个分布式版本控制系统,帮助人们管理为项目所做的工作,避免一个人所做的修改影响其他人所做的修改。在项目中实现新功能时,Git跟踪你对每个文件所做的修改。确定代码可行后,你提交所做的修改,而Git将记录项目最新的状态。如果犯了错,想撤销所做的修改,你可以轻松地返回到以前的任何可行状态。(要更深入地了解如何使用Git进行版本控制,请参阅附录D。)GitHub上的项目都存储在仓库中,后者包含与项目相关联的一切:代码、项目参与者的信息、问题或bug报告,等等

在本章中,我们将编写一个程序,自动下载GitHub上星级最高的Python项目的信息,并对这些信息进行可视化

使用API调用请求数据

GitHub的API让你能够通过API调用来请求各种信息。要知道API调用是什么样的,请在浏览器的地址栏中输入如下地址
https://api.github.com/search/repositories?q=language:python&sort=star

https://api.github.com/search/repositories?q=language:python&sort=star

这个调用返回GitHub当前托管了多少个Python项目,以及有关最受欢迎的Python仓库的信息

https://api.github.com/ 将请求发送到GitHub网站中响应API调用的部分,接下来的search/repositories 让API搜索GitHub上的所有仓库

repositories 后面的问号指出需要传递一个实参。q 表示查询,而等号(= )让我们能够开始指定查询。我们使用language:python 指出只想获取主要语言为Python的仓库的信息。最后的&sort=stars 指定将项目按星级排序

在这里插入图片描述

安装requests

pip install requests

处理API响应

import requests
# 执行API调用并存储响应。
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
print(f"Status code: {r.status_code}")	# Status code: 200
# 将API响应赋给一个变量。
response_dict = r.json()
# 处理结果。
print(response_dict.keys())	# dict_keys(['total_count', 'incomplete_results', 'items'])

状态码200表示请求成功
方法json() 将这些信息转换为一个Python字典

处理响应字典

# 将API响应赋给一个变量。
response_dict = r.json()
print(f"Total repositories: {response_dict['total_count']}")	# 9420397	# 仓库总数
# 探索有关仓库的信息。
repo_dicts = response_dict['items']
print(f"Repositories returned: {len(repo_dicts)}")	# 30	# 返回30个仓库
# 研究第一个仓库。
repo_dict = repo_dicts[0]
print(f"\nKeys: {len(repo_dict)}")	# Keys: 80	# repo_dict 包含80个键
for key in sorted(repo_dict.keys()):print(key)

提取repo_dict 中与一些键相关联的值

print("\nSelected information about first repository:") # Selected information about first repository:
print(f"Name: {repo_dict['name']}")                     # Name: flask
print(f"Owner: {repo_dict['owner']['login']}")          # Owner: pallets
print(f"Stars: {repo_dict['stargazers_count']}")        # Stars: 63955
print(f"Repository: {repo_dict['html_url']}")           # Repository: https://github.com/pallets/flask
print(f"Created: {repo_dict['created_at']}")            # Created: 2010-04-06T11:11:59Z
print(f"Updated: {repo_dict['updated_at']}")            # Updated: 2023-08-27T04:37:37Z
print(f"Description: {repo_dict['description']}")       # Description: The Python micro framework for building web applications.

owner login 所有者登录名

概述最受欢迎的仓库

# 研究有关仓库的信息。
repo_dicts = response_dict['items']
print(f"Repositories returned: {len(repo_dicts)}")print("\nSelected information about each repository:")
for repo_dict in repo_dicts:print(f"\nName: {repo_dict['name']}")print(f"Owner: {repo_dict['owner']['login']}")print(f"Stars: {repo_dict['stargazers_count']}")print(f"Repository: {repo_dict['html_url']}")print(f"Description: {repo_dict['description']}")

代码结果如下:

Repositories returned: 30Selected information about each repository:Name: flask
Owner: pallets
Stars: 63955
Repository: https://github.com/pallets/flask
Description: The Python micro framework for building web applications.Name: langchain
Owner: langchain-ai
Stars: 60009
Repository: https://github.com/langchain-ai/langchain
Description: ⚡ Building applications with LLMs through composability ⚡Name: ailearning
Owner: apachecn
Stars: 36223
Repository: https://github.com/apachecn/ailearning
Description: AiLearning:数据分析+机器学习实战+线性代数+PyTorch+NLTK+TF2Name: linux-insides
Owner: 0xAX
Stars: 28546
Repository: https://github.com/0xAX/linux-insides
Description: A little bit about a linux kernel

监视API的速率限制

大多数API存在速率限制,也就是说,在特定时间内可执行的请求数存在限制

要获悉是否接近了GitHub的限制,请在浏览器中输入https://api.github.com/rate_limit,你将看到类似于下面的响应:https://api.github.com/rate_limit

在这里插入图片描述
注意:很多API要求注册获得API密钥后才能执行API调用

使用Plotly可视化仓库

import requests
from plotly.graph_objs import Bar
from plotly import offline# 执行API调用并存储响应。
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
print(f"Status code: {r.status_code}")# 处理结果。
response_dict = r.json()
repo_dicts = response_dict['items']
repo_names, stars = [], []
for repo_dict in repo_dicts:repo_names.append(repo_dict['name'])stars.append(repo_dict['stargazers_count'])# 可视化。
data = [{'type': 'bar','x': repo_names,'y': stars,
}]
my_layout = {'title': 'GitHub上最受欢迎的Python项目','xaxis': {'title': 'Repository'},'yaxis': {'title': 'Stars'},
}fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='python_repos.html')

在这里插入图片描述

改进Plotly图表 data my_layout

可在data 和my_layout 中以键值对的形式指定各种样式

data修改图表
my_layout修改字

data = [{'type': 'bar','x': repo_names,'y': stars,'marker': {'color': 'red','line': {'width': 1.5, 'color': 'rgb(25, 25, 25)'}},'opacity': 0.6,
}]
my_layout = {'title': 'GitHub上最受欢迎的Python项目','titlefont': {'size': 28},'xaxis': {'title': 'Repository','titlefont': {'size': 24},'tickfont': {'size': 14},},'yaxis': {'title': 'Stars','titlefont': {'size': 24},'tickfont': {'size': 14},},
}

在这里插入图片描述

添加自定义工具提示 hovertext

工具提示:将鼠标指向条形将显示其表示的信息

# 处理结果。
response_dict = r.json()
repo_dicts = response_dict['items']
repo_names, stars, labels = [], [], []
for repo_dict in repo_dicts:repo_names.append(repo_dict['name'])stars.append(repo_dict['stargazers_count'])owner = repo_dict['owner']['login']description = repo_dict['description']label = f"{owner}<br />{description}"labels.append(label)
# 可视化。
data = [{'type': 'bar','x': repo_names,'y': stars,'hovertext': labels,'marker': {'color': 'rgb(60, 100, 150)','line': {'width': 1.5, 'color': 'rgb(25, 25, 25)'}},'opacity': 0.6,
}]

Plotly允许在文本元素中使用HTML代码
在这里插入图片描述

在图表中添加可单击的链接

点击图表底端的项目名,可以访问项目在GitHub上的主页

# 处理结果。
response_dict = r.json()
repo_dicts = response_dict['items']
repo_links, stars, labels = [], [], []
for repo_dict in repo_dicts:repo_name = repo_dict['name']repo_url = repo_dict['html_url']repo_link = f"<a href='{repo_url}'>{repo_name}</a>"repo_links.append(repo_link)stars.append(repo_dict['stargazers_count'])owner = repo_dict['owner']['login']description = repo_dict['description']label = f"{owner}<br />{description}"labels.append(label)

将data里x的值改为repo_links

data = [{'x': repo_links,
}]

深入了解Plotly和GitHub API

想要深入了解如何生成Plotly图表,可以看Plotly User Guide in Python和Python Figure Reference

Hacker News API

Hacker News网站:Hacker News的API让你能够访问有关该网站所有文章和评论的信息,且不要求通过注册获得密钥

import requests
import json# 执行API调用并存储响应。
url = 'https://hacker-news.firebaseio.com/v0/item/19155826.json'
r = requests.get(url)
print(r.status_code)# 200# 探索数据的结构。
response_dict = r.json()
readable_file = 'readable_hn_data.json'
with open(readable_file, 'w') as f:json.dump(response_dict, f, indent=4)

在这里插入图片描述

下面的URL返回一个列表,其中包含Hacker News上当前排名靠前的文章的ID:

https://hacker-news.firebaseio.com/v0/topstories.json
from operator import itemgetter
import requests# 执行API调用并存储响应。
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
# print(f"Status code: {r.status_code}")# 处理有关每篇文章的信息。
submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:10]:# 对于每篇文章,都执行一个API调用。url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json"r = requests.get(url)# print(f"id: {submission_id}\tstatus: {r.status_code}")response_dict = r.json()# 对于每篇文章,都创建一个字典。submission_dict = {'title': response_dict['title'],'hn_link': f"http://news.ycombinator.com/item?id={submission_id}",'comments': response_dict['descendants'],}submission_dicts.append(submission_dict)submission_dicts = sorted(submission_dicts, key=itemgetter('comments'),reverse=True)for submission_dict in submission_dicts:print(f"\nTitle: {submission_dict['title']}")print(f"Discussion link: {submission_dict['hn_link']}")print(f"Comments: {submission_dict['comments']}")

在这里插入图片描述

相关文章:

python-数据可视化-使用API

使用Web应用程序编程接口 &#xff08;API&#xff09;自动请求网站的特定信息而不是整个网页&#xff0c;再对这些信息进行可视化 使用Web API Web API是网站的一部分&#xff0c;用于与使用具体URL请求特定信息的程序交互。这种请求称为API调用 。请求的数据将以易于处理的…...

窗口看门狗

从下往上看: 1. 时钟设置 RCC_APB1PeriphClockCmd(RCC_APB1Periph_WWDG,ENABLE);//使能独立看门狗时钟 WWDG_SetPrescaler(WWDG_Prescaler_8);//看门狗预分频器WWDG counter clock (PCLK1/4096)/8 2.设置窗口值 实际就是设置WWDG_CR的低七位值, 但是这个值要大于0x40(也就是…...

开发新能源的好处

风能无论是总装机容量还是新增装机容量&#xff0c;全球都保持着较快的发展速度&#xff0c;风能将迎来发展高峰。风电上网电价高于火电&#xff0c;期待价格理顺促进发展。生物质能有望在农业资源丰富的热带和亚热带普及&#xff0c;主要问题是降低制造成本&#xff0c;生物乙…...

error: can‘t find Rust compiler

操作系统 win11 pip install -r requirements.txt 报错如下 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/56/fc/a3c13ded7b3057680c8ae95a9b6cc83e63657c38e0005c400a5d018a33a7/pyreadline3-3.4.1-py3-none-any.whl (95 kB) Building wheels for collected p…...

全面解析MES系统中的车间退料管理

一、车间退料管理的定义&#xff1a; 车间退料是指在生产过程中&#xff0c;将不合格或多余的物料、半成品或成品从车间环节返还到供应链的过程。车间退料管理则是指对这一退料过程进行规范化、系统化的管理和跟踪。 二、车间退料管理的流程&#xff1a; 1. 退料申请&#xf…...

探究finally代码块是否执行

情况一&#xff1a;try代码块正常执行&#xff0c;无异常&#xff0c;finally代码块无retrun&#xff1b; 代码演示 public class Test38 {public static void main(String[] args) {int foo foo();System.out.println("foo:" foo);}public static int foo() {tr…...

leetcode刷题(字符串相加、包含每个查询的最小区间、模拟行走机器人、环形子数组的最大和、满足不等式的最大值、四数之和、树中距离之和)

目录 1、字符串相加 2、包含每个查询的最小区间 3、模拟行走机器人 4、环形子数组的最大和 5、满足不等式的最大值 6、四数之和 7、 树中距离之和 1、字符串相加 class Solution:def addStrings(self, num1: str, num2: str) -> str:i len(num1) - 1 # num1的末…...

Grafana reporter定时报表踩坑记录

前言:本以为测试grafana reporter功能能很顺利,但按照网上大佬分享的记录进行操作,屡屡报错,不知是因为我的grafana部署在k8s中之前由低版本升级到高版本导致的,还是其他原因,在grafana中安装Grafana Image Renderer 一直报错。 Github地址:https://github.com/IzakMar…...

Flutter 状态管理引子

1、为了更好地了解状态管理&#xff0c;先看看什么是状态。 在类似Flutter这样的响应式编程框架中&#xff0c;我们可以认为U相关的开发就是对数据进行封装&#xff0c;将之转换为具体的U1布局或者组件。借用Flutter官网的一张图&#xff0c;可以把我们在第二部分做的所有开发…...

CFC编程入门_【10分钟学会】

什么是CFC&#xff1a; 【差不多10分钟全学会】 CFC是图形化编程&#xff0c; 跟单片机的连线一样&#xff0c; 唯一的区别&#xff1a;功能块右侧是【只能输出】引脚。 只有左侧引脚可以输入输出。 有哪些控件&#xff1a; 指针&#xff1a;用于拖动功能块。 控制点&#xf…...

golang无需创建新切片

在 Go 语言中&#xff0c;append(b, 0)[:len(b)] 是一种常见的用法&#xff0c;用于在切片 b 后追加一个元素&#xff0c;并返回旧切片的前 len(b) 个元素。 这种用法的目的是将一个新元素追加到切片中&#xff0c;并确保切片的长度保持不变。具体步骤如下&#xff1a; 1. ap…...

Django基础5——ORM中间程序

文章目录 一、基本了解二、ORM基本操作2.1 连接数据库2.1.1 使用sqlite数据库2.1.2 使用MySQL数据库 2.2 对数据库操作2.2.1 增&#xff08;前端数据——>数据库&#xff09;2.2.2 查&#xff08;数据库——>前端展示&#xff09;2.2.3 改&#xff08;修改数据&#xff0…...

SpringAOP详解(上)

当需要在方法前后做一些操作就需要借助动态代理来实现 一、动态代理实现方法 1、jdk自带实现方式 jdk实现代理是被代理类实现接口的方式 public interface UserInterface {void test(); }public class UserService implements UserInterface {public void test() {System.o…...

C++ 存储类

存储类定义 C 程序中变量/函数的范围&#xff08;可见性&#xff09;和生命周期。这些说明符放置在它们所修饰的类型之前。下面列出 C 程序中可用的存储类&#xff1a; autoregisterstaticexternmutablethread_local (C11) 从 C 17 开始&#xff0c;auto 关键字不再是 C 存储…...

【教程分享】Docker搭建Zipkin,实现数据持久化到MySQL、ES

1 拉取镜像 指定版本&#xff0c;在git查看相应版本&#xff0c;参考&#xff1a; https://github.com/openzipkin/zipkin 如2.21.7 docker pull openzipkin/zipkin:2.21.7 2 启动 Zipkin默认端口为9411。启动时通过-e server.portxxxx设置指定端口 docker run --name zi…...

数据库——MySQL高性能优化规范

文章目录 数据库命令规范数据库基本设计规范1. 所有表必须使用 Innodb 存储引擎2. 数据库和表的字符集统一使用 UTF83. 所有表和字段都需要添加注释4. 尽量控制单表数据量的大小,建议控制在 500 万以内。5. 谨慎使用 MySQL 分区表6.尽量做到冷热数据分离,减小表的宽度7. 禁止在…...

openapi中job提交

openapi中job提交 简介创建job查看job查看job 的描述查看job 的日志 镜像地址&#xff1a; https://www.jianshu.com/p/fcb3094f8c48?v1693020692471 简介 这里使用微软OpenPAI, 在nvidia的GPU设备上进行job测试。 创建job protocolVersion: 2 name: lenet_gpu_pytorch112_…...

Spring Boot 整合 分布式搜索引擎 Elastic Search 实现 数据聚合

文章目录 ⛄引言一、数据聚合⛅简介⚡聚合的分类 二、DSL实现数据聚合⏰Bucket聚合⚡Metric聚合 三、RestAPI实现数据聚合⌚业务需求⏰业务代码实现 ✅效果图⛵小结 ⛄引言 本文参考黑马 分布式Elastic search Elasticsearch是一款非常强大的开源搜索引擎&#xff0c;具备非常…...

深入探讨代理技术:保障网络安全与爬虫效率

在当今数字化时代&#xff0c;代理技术在网络安全与爬虫领域扮演着重要角色。从Socks5代理、IP代理&#xff0c;到网络安全和爬虫应用&#xff0c;本文将深入探讨这些关键概念&#xff0c;揭示它们如何相互关联以提高网络安全性和爬虫效率。 1. 代理技术简介 代理技术是一种允…...

【云原生】Docker私有仓库 RegistryHabor

目录 1.Docker私有仓库&#xff08;Registry&#xff09; 1.1 Registry的介绍 1.2 Registry的部署 步骤一&#xff1a;拉取相关的镜像 步骤二&#xff1a;进行 Registry的相关yml文件配置&#xff08;docker-compose&#xff09; 步骤三&#xff1a;镜像的推送 2. Regist…...

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…...

树莓派超全系列教程文档--(62)使用rpicam-app通过网络流式传输视频

使用rpicam-app通过网络流式传输视频 使用 rpicam-app 通过网络流式传输视频UDPTCPRTSPlibavGStreamerRTPlibcamerasrc GStreamer 元素 文章来源&#xff1a; http://raspberry.dns8844.cn/documentation 原文网址 使用 rpicam-app 通过网络流式传输视频 本节介绍来自 rpica…...

中南大学无人机智能体的全面评估!BEDI:用于评估无人机上具身智能体的综合性基准测试

作者&#xff1a;Mingning Guo, Mengwei Wu, Jiarun He, Shaoxian Li, Haifeng Li, Chao Tao单位&#xff1a;中南大学地球科学与信息物理学院论文标题&#xff1a;BEDI: A Comprehensive Benchmark for Evaluating Embodied Agents on UAVs论文链接&#xff1a;https://arxiv.…...

【网络安全产品大调研系列】2. 体验漏洞扫描

前言 2023 年漏洞扫描服务市场规模预计为 3.06&#xff08;十亿美元&#xff09;。漏洞扫描服务市场行业预计将从 2024 年的 3.48&#xff08;十亿美元&#xff09;增长到 2032 年的 9.54&#xff08;十亿美元&#xff09;。预测期内漏洞扫描服务市场 CAGR&#xff08;增长率&…...

RNN避坑指南:从数学推导到LSTM/GRU工业级部署实战流程

本文较长&#xff0c;建议点赞收藏&#xff0c;以免遗失。更多AI大模型应用开发学习视频及资料&#xff0c;尽在聚客AI学院。 本文全面剖析RNN核心原理&#xff0c;深入讲解梯度消失/爆炸问题&#xff0c;并通过LSTM/GRU结构实现解决方案&#xff0c;提供时间序列预测和文本生成…...

JS设计模式(4):观察者模式

JS设计模式(4):观察者模式 一、引入 在开发中&#xff0c;我们经常会遇到这样的场景&#xff1a;一个对象的状态变化需要自动通知其他对象&#xff0c;比如&#xff1a; 电商平台中&#xff0c;商品库存变化时需要通知所有订阅该商品的用户&#xff1b;新闻网站中&#xff0…...

AI+无人机如何守护濒危物种?YOLOv8实现95%精准识别

【导读】 野生动物监测在理解和保护生态系统中发挥着至关重要的作用。然而&#xff0c;传统的野生动物观察方法往往耗时耗力、成本高昂且范围有限。无人机的出现为野生动物监测提供了有前景的替代方案&#xff0c;能够实现大范围覆盖并远程采集数据。尽管具备这些优势&#xf…...

Go语言多线程问题

打印零与奇偶数&#xff08;leetcode 1116&#xff09; 方法1&#xff1a;使用互斥锁和条件变量 package mainimport ("fmt""sync" )type ZeroEvenOdd struct {n intzeroMutex sync.MutexevenMutex sync.MutexoddMutex sync.Mutexcurrent int…...

并发编程 - go版

1.并发编程基础概念 进程和线程 A. 进程是程序在操作系统中的一次执行过程&#xff0c;系统进行资源分配和调度的一个独立单位。B. 线程是进程的一个执行实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。C.一个进程可以创建和撤销多个线程;同一个进程中…...

第八部分:阶段项目 6:构建 React 前端应用

现在&#xff0c;是时候将你学到的 React 基础知识付诸实践&#xff0c;构建一个简单的前端应用来模拟与后端 API 的交互了。在这个阶段&#xff0c;你可以先使用模拟数据&#xff0c;或者如果你的后端 API&#xff08;阶段项目 5&#xff09;已经搭建好&#xff0c;可以直接连…...