highs_lows.py 1.2 KB
Newer Older
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
import csv
from datetime import datetime

from matplotlib import pyplot as plt

# 从文件中获取每天的最高温度
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
	reader = csv.reader(f)
	# next(reader)函数是返回reader阅读器的下一行,目前只调用了一次,所以是头行
	header_row = next(reader)
	# 打印头行,header_row它是一个列表
	# print(header_row)
	# enumerate() 获取每个元素的索引及其值
	for index, column_header in enumerate(header_row):
		print(index, column_header)

	# 第二列每天的最高温度
	dates, highs = [], []
	for row in reader:
		current_date = datetime.strptime(row[0], '%Y-%m-%d')
		print(current_date)
		dates.append(current_date)
		high = int(row[1])
		highs.append(high)

	print(dates)
	print(highs)

	# 根据数据绘制图形
	fig = plt.figure(dpi=128, figsize=(10, 6))
	plt.plot(dates, highs, c='red')

	# 设置图形的格式
	plt.title("Daily high temperatures, July 2014", 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()