-
使用python可以方便的实现数据可视化,下面是两个例子,这些例子是跟着《python编程:从入门到实践》做的,这其中的csv文件与json文件,下载地址。在该网址中点击右侧随书下载,然后下载源代码文件。csv文件:在源代码文件中,打开chapter_16->data->sitka_weather_2018_full.csv并将该csv文件放到代码所在目录中。
-
2018年阿拉斯加州锡特卡天气的可视化
效果图:
此案例需要的csv文件:在刚才下载的源代码文件中,打开chapter_16->data->sitka_weather_2018_full.csv并将该csv文件放到代码所在目录中。
代码如下:
"""用matplotlib实现阿拉斯加州锡特卡每日最低、最高气温的可视化"""
import csv
from datetime import datetime
import matplotlib.pyplot as plt
# 设置matplotlib防止中文显示乱码
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 打开文件并获取信息
filename = 'sitka_weather_2018_full.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# 获取不同数据的下标
for index, column_header in enumerate(header_row):
if column_header == 'DATE':
date_index = index
elif column_header == 'TMAX':
high_index = index
elif column_header == 'TMIN':
low_index = index
elif column_header == 'NAME':
city_index = index
# 将获取到的每一行数据中的最高气温、最低气温、日期、城市名称提取出来并添加到列表中
highs, lows, dates = [], [], []
for line in reader:
try:
high = int(int(line[high_index]))
low = int(line[low_index])
date = datetime.strptime(line[date_index], '%Y-%m-%d')
city = line[city_index]
except ValueError:
continue
else:
highs.append(high)
lows.append(low)
dates.append(date)
# 将数据可视化
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red', alpha=0.5)
ax.plot(dates, lows, c='blue', alpha=0.5)
ax.fill_between(dates, lows, highs, facecolor='blue', alpha=0.1)
ax.set_title(u'2018年{}每日最高温度'.format(city), fontsize=24)
ax.set_xlabel('', fontsize=16)
ax.set_ylabel(u'温度(F)', fontsize=16)
plt.show()
- 一段时间内地震散点图
json文件位于源代码文件->chapter_16->mapping_global_data_sets->data中,请下载对应的json文件。
效果图:
代码:
import json
import plotly.express as px
import pandas as pd
#打开文件并将数据写入到对象中
filename = 'eq_data_30_day_m1.json'
with open(filename) as f:
all_eq_data = json.load(f)
#从json处理得到的对象中提取震级、标题、经度、纬度
all_eq_dicts = all_eq_data['features']
mags,titles,lons,lats = [],[],[],[]
for eq_dict in all_eq_dicts:
try:
mag = eq_dict['properties']['mag']
title = eq_dict['properties']['title']
lon = eq_dict['geometry']['coordinates'][0]
lat = eq_dict['geometry']['coordinates'][1]
except ValueError:
continue
else:
mags.append(mag)
titles.append(title)
lons.append(lon)
lats.append(lat)
#封装数据,下面scatter中要用data,封装后data中的数据都可以键值对表示
data = pd.DataFrame(
data=zip(lons,lats,titles,mags),columns=['经度','纬度','位置','震级']
)
data.head()
#画图
fig = px.scatter(data_frame=data,x='经度',y='纬度',
range_x=[-200,200],range_y=[-90,90],width=800,height=800,
title='全球地震散点图',
size='震级',size_max=10,
color='震级',
hover_name='位置')
fig.write_html('global_erath.html')
fig.show()