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']}")

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/61350.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SpringBoot—日志

目录 日志使用日志日志级别设置日志级别设置分组指定日志文件路径日志切割归档使用第三方日志框架log4j2配置文件【分级存储】logback配置文件【分级存储】 实例代码 日志 使用日志 给controller添加日志信息 要给controller类上添加Slf4j注解&#xff0c;然后使用log.info(…

关于SAM中decomposed Relative Positional Embeddings的理解

关于SAM中decomposed Relative Positional Embeddings的理解。 relative positional embedding的一种实现方式是&#xff1a;先计算q和k的相对位置坐标&#xff0c;然后依据相对位置坐标从给定的table中取值。以q和k都是77为例&#xff0c;每个相对位置有两个索引对应x和y两个…

2023年信息安全管理与评估赛项参考答案-模块1任务一

根据网络拓扑图所示&#xff0c;按照IP 地址规划表&#xff0c;对防火墙的名称、各接口IP 地址进行配置。共8 分&#xff0c;每错1 处&#xff08;行&#xff09;扣1 分&#xff0c;扣完为止。地址、安全域、接口&#xff08;状态为UP&#xff09;、名称都正确。 2.根据网络拓扑…

QT注册界面练习(信号与槽实现页面跳转)

一、注册界面练习思路以及具体代码 在完成注册页面搭建的前提下&#xff0c;通过信号与槽机制实现多组件之间的相互通信&#xff0c;实现页面跳转。 基本步骤&#xff1a; 首先&#xff0c;将注册页面的登录按钮与成功登陆信号绑定&#xff0c;当用户名与密码均匹配时&#xf…

如何做一个H5弹窗组件复用?

关闭按钮在内部时 <template><div class"tipPop"><div class"tipPop-show"><div><img class"close" src"/assets/img/close.png" click.stop"handleClsoeData"/><slot></slot>&…

JDK的组成、作用

JDK&#xff1a;java development kit java的标准开发工具包 jre&#xff1a;java runtime environment 运行基于java语言编写的程序必不可少的运行环境用于解释和执行java的字节码文件&#xff08;.class文件&#xff09;普通用户&#xff08;无开发需求&#xff09;下载jre…

IDEA集成Git相关操作知识(pull、push、clone)

一&#xff1a;集成git 1&#xff1a;初始化git&#xff08;新版本默认初始化&#xff09; 老版本若没有&#xff0c;点击VCS&#xff0c;选中import into Version Controller中的Create git Repository(创建git仓库)&#xff0c;同理即可出现git符号。 也可查看源文件夹有没有…

Linux脚本-将当前文件夹下所有包含main函数的.c文件提取出来

实现一个Linux脚本&#xff0c;该脚本使用 for 循环遍历当前目录下的所有 .c 文件。 对于每个 .c 文件&#xff0c;使用 grep 命令来查找是否包含字符串 “main”。 如果该 .c 文件包含 “main”&#xff0c;则输出到/home/majn/llvm_project/extract_main目录下。 #!/bin/bas…

01_lwip_raw_udp_test

1.打开UDP的调试功能 &#xff08;1&#xff09;设置宏定义 &#xff08;2&#xff09;打开UDP的调试功能 &#xff08;3&#xff09;修改内容&#xff0c;串口助手打印的日志信息自动换行 2.电脑端连接 UDP发送一帧数据 3.电路板上发送一帧数据

Qt自定义标题栏

一、创建项目 最终项目文件结构如下 “iconfont.tff”的使用方式见如下博客&#xff0c;用于更改图标颜色Qt更改图标颜色_怎么追摩羯座的博客-CSDN博客 二、MyTitleBar.pro #------------------------------------------------- # # Project created by QtCreator 2023-08-2…

如何为你的公司选择正确的AIGC解决方案?

如何为你的公司选择正确的AIGC解决方案&#xff1f; 摘要引言词汇解释&#xff08;详细版本&#xff09;详细介绍1. 确定需求2. 考虑技术能力3. 评估可行性4. 比较不同供应商 代码快及其注释注意事项知识总结 博主 默语带您 Go to New World. ✍ 个人主页—— 默语 的博客&…

Linux centos7 bash编程(break和continue)

在学习shell知识时&#xff0c;简单编程要从格式入手。 首先学习好单行注释和多行注释。 先学习简单整数的打印输出&#xff0c;主要学习echo命令&#xff0c;学习选项-e -n的使用。 下面的练习是常用的两个分支跳转程序&#xff1a;break和continue。 #!/bin/bash # 这是单…

贪心算法总结篇

文章转自代码随想录 贪心算法总结篇 我刚刚开始讲解贪心系列的时候就说了&#xff0c;贪心系列并不打算严格的从简单到困难这么个顺序来讲解。 因为贪心的简单题可能往往过于简单甚至感觉不到贪心&#xff0c;如果我连续几天讲解简单的贪心&#xff0c;估计录友们一定会不耐…

matlab使用教程(29)—微分方程实例

此示例说明如何使用 MATLAB 构造几种不同类型的微分方程并求解。MATLAB 提供了多种数值算法来求解各种微分方程&#xff1a; 1.初始值问题 vanderpoldemo 是用于定义 van der Pol 方程的函数 type vanderpoldemo function dydt vanderpoldemo(t,y,Mu) %VANDERPOLDEMO Defin…

如何在不重新安装的情况下将操作系统迁移到新硬盘?

通常情况下&#xff0c;当你的硬盘损坏或文件过多时&#xff0c;电脑会变得缓慢且卡顿。这时&#xff0c;你可能会被建议更换为一块更好的新硬盘。 ​ 在比较HDD和SSD之后&#xff0c;许多用户更愿意选择SSD作为他们的新硬盘&#xff0c;因为SSD比HDD更稳定且运行更安…

双核和双路服务器的区别

服务器术语里&#xff0c;大家经常会听到1U、2U&#xff0c;单路、双路&#xff0c;机架式、塔式及刀片式等常用名词。其中&#xff0c;机架式、塔式及刀片式是 指服务器的外形&#xff0c;U是指服务器的高度&#xff0c;路是指服务器的处理器数量。 部分朋友会问&#xff0c;我…

Android 设置app深色、浅色、跟随系统

Android深色模式适配 我们需要再用户设置时候&#xff0c;记录下来&#xff0c;用户的设置&#xff0c;等app再次启动时候&#xff0c;获取之前设置&#xff0c;重新设置 public static void setThemeMode() {int themeModeType SpUtils.getThemeModeType();if (themeModeTyp…

环境安装:rpm安装jdk上线项目

Tomcat安装 解析域名 购买域名并配置 安装Docker yum 卸载以前装过的docker

Seaborn数据可视化(四)

目录 1.绘制箱线图 2.绘制小提琴图 3.绘制多面板图 4.绘制等高线图 5.绘制热力图 1.绘制箱线图 import seaborn as sns import matplotlib.pyplot as plt # 加载示例数据&#xff08;例如&#xff0c;使用seaborn自带的数据集&#xff09; tips sns.load_dataset("t…

算法通关村第十七关——柠檬水找零

贪心&#xff0c;顾名思义&#xff0c;就是挑价值最大的 如果直接挑价值最大的&#xff0c;这样不一定能够达到最优解&#xff0c;因为最终价值多少还要取决于背包容量。 贪心算法解决0-1背包问题的基本思路是&#xff1a;按照物品的单位价值&#xff08;即价值与重量的比值&…