《Python编程:从入门到实践》袁国忠译 , 第16章 第318页
运行该页的代码得到的图形和书上的图不一样,可能和matplotlib的版本有关。
书上的图是这样:
而直接运行该页程序得到的图是这样:
这时候需要加上设定x轴范围的语句:plt.xlim(dates[0] , dates[-1] )。
整个程序如下:
import csv
import matplotlib.pyplot as plt
from datetime import datetime
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
reader0 = csv.reader(f)
head = next(reader0)
#print ( head )
highs = []
dates = []
for row in reader0:
highs.append( int( row[1]) )
date = datetime.strptime ( row[0] , "%Y-%m-%d" )
dates.append( date )
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.xlim(dates[0] , dates[-1] )
#plt.show()
plt.savefig('fig/july.png', bbox_inches='tight')