python爬虫数据可视化文件json
时间: 2024-01-30 18:11:26 浏览: 137
以下是使用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()`显示图表。
阅读全文