import csv
import matplotlib.pyplot as plt
from datetime import datetime
# 从文件中获取最高气温
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) # next()返回文件的下一行,只调用了next()一次,则得到的是文件的第一行
for index, column_header in enumerate(header_row):
print(index, column_header)
dates, highs = [], []
for row in reader:
highs.append(int(row[1]))
current_date = datetime.strptime(row[0], '%Y-%m-%d') # 使用strptime()将字符串日期转化为标准显示日期
dates.append(current_date)
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red')
# 设置图形格式
plt.title("Daily high temperature, July 2014", fontsize=24)
plt.xlabel('', fontsize=14)
fig.autofmt_xdate() # 让x轴标签斜着打印避免拥挤
plt.ylabel('Temperature(F)', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
利用 fig.autofmt_xdate() # 让x轴标签斜着打印避免拥挤