Python(自学笔记3--数据可视化与使用API)

十、数据可视化

先安装matplotlib包

安装后,可以输入import matplotlib来测试是否安装成功

测试:

import matplotlib.pyplot as plt

s = [1, 4, 9, 16, 25]
plt.plot(s)
plt.show()

先导入模块pyplot,指定别名为plt

定义列表s将列表传递给函数plot

plt.show()打开matplotlib查看器,先是绘制的图形

🔥 设置格式

import matplotlib.pyplot as plt

s = [1, 4, 9, 16, 25]
plt.plot(s, linewidth=5)
plt.title("first test")
plt.xlabel("x")
plt.ylabel("x^2")

plt.tick_params(axis='both', labelsize=14)
plt.show()
  • linewidth设置粗细
  • title标题
  • xlabel横坐标
  • ylabel纵坐标

设置参数,可以给相同维度的点来绘制连线

s = [1, 4, 9, 16, 25]
m = [1, 2, 3, 4, 5]
plt.plot(m, s, linewidth=5)

scatter函数绘制散点

将plot换成scatter试试也是一样的

当然,也可以由算法生成数据只要十相同维度

plt.axis([0,1100,0,1100000])–用来指定范围

🔥 样式与颜色

  • 可使用edgecolor=‘none’来取消轮廓
  • 也可以根据c=‘red’来改变颜色
  • 也可以用RGB来定义颜色c=[0,0,0,8]

颜色映射

x = list(range(1, 1001))                   
y = [x_1 ** 2 for x_1 in x]                
# plt.scatter(m, s, edgecolor='none', c='re
plt.scatter(x, y, c=y,  edgecolors='none') 
plt.title("first test")                    
plt.xlabel("x")                            
plt.ylabel("x^2")                          
                                           
plt.tick_params(axis='both', labelsize=14) 
plt.show()                                 

🔥自动保存图表

plt.show改为plt.savefig('test.png', bb_inches='tight')

第一个参数为以什么样的文件名保存,第二个参数为减裁掉多余的空白区

image-20210315151950629

十一、使用API

Web应用编程接口(API)自动请求网站的特定信息而不是整个网站,这样的程序始终使用最新的的数据来生成可视化,因此即使数据瞬息万变,它呈现的信息也是最新的。

使用GitHub的API来请求有关该网站中Python项目的信息然后用Pygal生成交互式可视化,呈现这些项目的受欢迎程度。

自动现在GitHub上星级最高的Python项目的信息,并对信息进行可视化

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

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

https://api.github.com/将请求发送至GitHub网站,响应API调用的部分,search/repositories让API搜索GitHub上上所有仓库。?指出我们传递的实参,通过使用language:python,指出只是想获取主要语言为Python的仓库的信息最后一部分sort=stars获得的星级进行排序:

{
  "total_count": 6871203,
  "incomplete_results": false,
  "items": [
    {
      "id": 83222441,
      "node_id": "MDEwOlJlcG9zaXRvcnk4MzIyMjQ0MQ==",
      "name": "system-design-primer",
      "full_name": "donnemartin/system-design-primer",
....

此时git公用6871203个Python项目,请求成功,

在pycharm中安装requests包

import requests

# 执行API并调用存储响应
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code:", r.status_code)

# 将API响应存储在一个变量中
response_dict = r.json()
# 处理结果
print(response_dict.keys())

第二句存储API调用的URL,用request来执行调用,调用get()传递给它

响应对象包含一个status_code的属性,看看它就知道成功与否,200成功

返回的是json格式,转换为一个Python字典,打印键值就可

处理响应词典:

# 处理响应词典
print("总 repositories:", response_dict['total_count'])

# 搜索仓库有关信息
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)

第一句,GitHub多少个Python仓库

与items相关的是个列表,包含很多字典,每个字典都包含了一个仓库信息。

第二句,把字典列表存储在repo_dicts中,打印长度,获取多少个仓库信息

第三句,提取第一个字典,打印字典包含的键数,看其中多少信息。

第五句,打印字典的所有键值,看其中有那些信息

结果:

总 repositories: 6858426
Repositories returned: 30

Keys: 74
archive_url
archived
assignees_url
blobs_url
branches_url
clone_url
collaborators_url
comments_url

。。。。

🔥 取得键值相关联的值

print("关于第一个仓库的信息(最受欢迎的信息)")
print("名字:", repo_dict['name'])
print("拥有者:", repo_dict['owner']['login'])
print("星数:", repo_dict['stargazers_count'])
print("html_url", repo_dict['html_url'])
print("创建时间:", repo_dict['created_at'])
print("更新时间:", repo_dict['updated_at'])
print("描述:", repo_dict['description'])

结果:

关于第一个仓库的信息(最受欢迎的信息)
名字: system-design-primer
拥有者: donnemartin
星数: 123928
html_url https://github.com/donnemartin/system-design-primer
创建时间: 2017-02-26T16:15:28Z
更新时间: 2021-03-16T06:41:39Z
描述: Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.(了解如何设计大型系统。 准备进行系统设计面试。 包括Anki抽认卡。)

🔥 循环打印

print("打印API所返回的每个仓库的特定信息:\n")
for repo_dict in repo_dicts:
    print("名字:", repo_dict['name'])
    print("拥有者:", repo_dict['owner']['login'])
    print("星数:", repo_dict['stargazers_count'])
    print("库地址:", repo_dict['html_url'])
    print("描述:", repo_dict['description'])
    print("\n")
    print("-----------------------------------------------------------")

结果:

打印API所返回的每个仓库的特定信息:

名字: system-design-primer
拥有者: donnemartin
星数: 123928
库地址: https://github.com/donnemartin/system-design-primer
描述: Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.


名字: public-apis
拥有者: public-apis
星数: 112970
库地址: https://github.com/public-apis/public-apis
描述: A collective list of free APIs for use in software and web development.


名字: Python
拥有者: TheAlgorithms
星数: 101068
库地址: https://github.com/TheAlgorithms/Python
描述: All Algorithms implemented in Python


名字: Python-100-Days
拥有者: jackfrued
星数: 100641
库地址: https://github.com/jackfrued/Python-100-Days
描述: Python - 100天从新手到大师


名字: awesome-python
拥有者: vinta
星数: 94928
库地址: https://github.com/vinta/awesome-python
描述: A curated list of awesome Python frameworks, libraries, software and resources


🔥 监视API的速率限制

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

要知道你是否收到了GitHub的限制,可以在浏览器中输入https://api.github.com/rate_limit

{"resources":{"core":{"limit":60,"remaining":60,"reset":1615953307,"used":0},"graphql":{"limit":0,"remaining":0,"reset":1615953307,"used":0},"integration_manifest":{"limit":5000,"remaining":5000,"reset":1615953307,"used":0},"search":{"limit":10,"remaining":10,"reset":1615949767,"used":0}},"rate":{"limit":60,"remaining":60,"reset":1615953307,"used":0}}

我得到了如上响应,

search:可以看到请求为每分钟极限为10个,这一分钟内我还可以请求8次

reset指配额将重置的Unix时间或新纪元时间,用完配额后收到简单响应,表示已经达到API上线

🔥 使用Pygal可视化仓库

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("状态标志:", r.status_code)
res1_dict = r.json()
print("总共存储库:", res1_dict['total_count'])
res_dicts = res1_dict['items']
names, stars = [], []
for res_dict in res_dicts:
    names.append(res_dict['name'])
    stars.append(res_dict['stargazers_count'])
my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = "GitHub上最多星的仓库"
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('python_repos.svg')

  • 获取响应并且存储到r,打印出状态标志。
  • 将API响应存储在变量res1_dict中。
  • 创建names和stars两个空列表存储图标中信息,用于给条形图加标签,并且获得多少星。确定高度
  • 用LightenStyle定义了一种样式,设置为深蓝
  • 用Bar创建了一个简单的条形图。还传递样式,标签旋转45度,隐藏图列
  • 接下来标签,命名

结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值