数据可视化训练第7天(json文件读取国家人口数据,找出前10和后10)

数据可以在这里下载
https://github.com/harkbox/DataAnalyseStudy

数据

https://restcountries.com/v3.1/all;建议下载下来,并不是很大

import numpy as np
import matplotlib.pyplot as plt
import requests
import json
#由于访问url过于慢;将数据下载到本地是json数据
#url='https://restcountries.com/v3.1/all'

#r=requests.get(url)
#r.json()获得文件数据
#statuscode判断是否成功访问

filename='/Users/oommnn/Desktop/学习笔记/数据可视化30天项目/all.json'

try:
    with open(filename) as f:
        data=json.load(f)
    
except FileNotFoundError:
    print(f"{filename}找不到")
    

#这是姓名的数组print(data[0]['name'])
#这是人口的消息print(data[0]['population'])

results=[]
#250个国家print(len(data))
for i in range(len(data)):
    result={'name':data[i]['name']['common'],'population':int(data[i]['population'])}
    results.append(result)
print(results[:2])

arr_results=np.array(results)
#列表的排序
results=sorted(results,key=lambda x: x['population'],reverse=True)
#np数组的排序;没有直接的方法



#可视化过程;使用matplotlib
x_values=[result['name'] for result in results]
y_values=[result['population'] for result in results]

fig,axs=plt.subplot_mosaic([['left_top','left_top'],['left_bottom','left_bottom']],figsize=(20,15),facecolor='gray')

axs['left_top'].bar(x_values[:10],y_values[:10])
axs['left_top'].set_title("Max Population about country")
axs['left_top'].set_xlabel('Country')
axs['left_top'].set_ylabel('Number/a hundred million')
axs['left_top'].set_xticks(x_values[:10],x_values[:10],rotation=45,fontsize=13)

axs['left_bottom'].bar(x_values[-10:],y_values[-10:])
axs['left_bottom'].set_title("Min Population about country")
axs['left_bottom'].set_xlabel('Country')
axs['left_bottom'].set_ylabel('Number/people')
axs['left_bottom'].set_xticks(x_values[-10:],x_values[-10:],rotation=45,fontsize=13)


plt.show()

在这里插入图片描述

总结

  • 关于数组的字典排序,属于lambda内置排序函数
  • set_xticks设置刻度和字体翻转;第一个参数是需要多少个刻度ticks,数值型代表数,字符串代表本身,第二个参数是一一对应刻度的标签labels
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Python爬虫获取JSON数据并进行可视化的示例代码: ```python import requests import matplotlib.pyplot as plt # 发起请求获取JSON数据 url = 'https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=statisGradeCityDetail,diseaseh5Shelf' response = requests.get(url, verify=False) json_data = response.json()['data'] china_data = json_data['diseaseh5Shelf']['areaTree'][0]['children'] # 解析数据 data_set = [] for i in china_data: data_dict = {} data_dict['province'] = i['name'] data_dict['nowConfirm'] = i['total']['nowConfirm'] data_dict['dead'] = i['total']['dead'] data_dict['heal'] = i['total']['heal'] data_set.append(data_dict) # 可视化数据 provinces = [data['province'] for data in data_set] now_confirms = [data['nowConfirm'] for data in data_set] deaths = [data['dead'] for data in data_set] recoveries = [data['heal'] for data in data_set] plt.figure(figsize=(10, 6)) plt.bar(provinces, now_confirms, label='Now Confirmed') plt.bar(provinces, deaths, label='Deaths', bottom=now_confirms) plt.bar(provinces, recoveries, label='Recoveries', bottom=[now + death for now, death in zip(now_confirms, deaths)]) plt.xlabel('Provinces') plt.ylabel('Number of Cases') plt.title('COVID-19 Statistics in China') plt.legend() plt.xticks(rotation=90) plt.show() ``` 这段代码首先使用`requests`库发起请求获取JSON数据,然后解析数据并将需要的信息存入一个列表中。接下来,使用`matplotlib`库进行可视化,通过条形图展示各个省份的现存确诊、死亡和治愈人数。最后,使用`plt.show()`显示图表。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值