Python学习之路(13)下载数据【项目2 数据可视化】

茴香豆 Lv5

在本章中,你将从网上下载数据,并对这些数据进行可视化。

1.CSV文件

要在文本文件中存储数据,最简单的方式是将数据作为一系列以逗号分隔 的值(CSV)写入文件。这样的文件称为CSV文件。下面是一行CSV格式的天气数据:

1
"USW00025333","SITKA AIRPORT, AK US","2018-01-01","13.87"," 0023","0.45",,,"48","38","  110","  110","31.1","38.0",

1.1读取csv文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import csv
filename = './data/sitka_weather_07-2018_simple.csv'
#读取文件头
with open(filename) as f:
reader = csv.reader(f)#创建一个与该文件关联的阅读器(reader)对象
header_row = next(reader)#next 返回文件中的下一行
for index, column_header in enumerate(header_row):
print(index, column_header)
#output:
0 STATION
1 NAME
2 DATE
3 PRCP
4 TAVG
5 TMAX
6 TMIN
#提取数据,最高温
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
highs = []
for row in reader:
highs.append(int(row[5]))
print(highs)
#output:
[62, 58, 70, 70, 67, 59, 58, 62, 66, 59, 56, 63, 65, 58, 56, 59, 64, 60, 60, 61, 65, 65, 63, 59, 64, 65, 68, 66, 64, 67, 65]

1.2绘制气温图表

为可视化这些气温数据,我们首先使用matplotlib创建一个显示每日最高气 温的简单图形。

实参 含义
%A 星期的名称,如Monday
%B 月份名,如January
%m 用数字表示的月份(01~12)
%d 用数字表示月份中的一天(01~31)
%Y 四位的年份,如2015
%y 两位的年份,如15
%H 24小时制的小时数(00~23)
%I 12小时制的小时数(01~12)
%p am或pm
%M 分钟数(00~59)
%S 秒数(00~61)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from matplotlib import pyplot as plt
from datetime import datetime
import csv
filename = './data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
dates, highs, lows = [], [], []
for row in reader:
try:
#如果有缺失数据,就会引发ValueError错误
dates.append(datetime.strptime(row[2], "%Y-%m-%d"))
highs.append(int(row[5]))
lows.append(int(row[6]))
except ValueError:
print('missing data')
# 根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red')
plt.plot(dates, lows, c='blue')
# 用阴影填充两条折线间的空间
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# 设置图形的格式
plt.title("Daily high temperatures, July 2018", fontsize=24)
plt.xlabel('', fontsize=16)
fig.autofmt_xdate()# 绘制斜的日期标签
plt.ylabel('Temperature(F)', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.show()

1.3绘制世界人口地图:JSON格式

plotly提供了一个适合初学者使用的地图创建工具,你将使用它来对地震数据进行可视化,以探索地震的分布情况。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#提取数据
import json
#将数据加载到一个列表中
filename = './global_data/eq_data_1_day_m1.json'
with open(filename) as f:
all_eq_data = json.load(f)
all_eq_dicts = all_eq_data['features']
#打印震级,经度,纬度,标题
mags, lons, lats, hover_texts = [], [], [], []
for eq_dict in all_eq_dicts:
mag = eq_dict['properties']['mag']
lon = eq_dict['geometry']['coordinates'][0]
lat = eq_dict['geometry']['coordinates'][1]
title = eq_dict['properties']['title']
mags.append(mag)
lons.append(lon)
lats.append(lat)
hover_texts.append(title)
print(mags[:10])
print(lons[:5])
print(lats[:5])
#output:
[0.96, 1.2, 4.3, 3.6, 2.1, 4, 1.06, 2.3, 4.9, 1.8]
[-116.7941667, -148.9865, -74.2343, -161.6801, -118.5316667]
[33.4863333, 64.6673, -12.1025, 54.2232, 35.3098333]
#绘制地震地图
from plotly.graph_objs import Scattergeo, Layout
from plotly import offline
data = [{
'type': 'scattergeo',
'lon': lons,
'lat': lats,
'text': hover_texts,
'marker': {
'size': [5*mag for mag in mags],
'color': mags,
'colorscale': 'Viridis',
'reversescale': True,
'colorbar': {'title': 'Magnitude'},
},
}]
my_layout = Layout(title='Global Earthquakes')
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='global_earthquakes.html')
  • Title: Python学习之路(13)下载数据【项目2 数据可视化】
  • Author: 茴香豆
  • Created at : 2022-10-10 10:21:03
  • Updated at : 2022-10-11 10:26:52
  • Link: https://hxiangdou.github.io/2022/10/10/Python_13/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Python学习之路(13)下载数据【项目2 数据可视化】