【关于《Python从入门到实践》书中第16章的作图问题】python使用matplotlib作图:如何合理设置x轴日期格式

xiaoxiao2021-03-01  13

       本人是Python语言初学者。因在阅读《Python从入门到实践》一书的第十六章的实践过程中,发现按书中示例代码所做的图形与书中所示图形不符:X轴的日期显示不符(fig.autofmt_xdate()无法实现合理设置X轴日期格式)。

       故有此文。

书中代码所得的图形。

       百度找到一种方法,通过fig.add_subplot(1,1,1)在图形原位置重新编辑设置X轴的格式。

       索引:Matplotlib绘图双纵坐标轴设置及控制设置时间格式

       本方法除书中用到的csv和datetime库,还需要下面的:

import matplotlib.pyplot as plt import matplotlib.dates as mdate import pandas as pd

       首先在原位值设置一个新的图形(变量名不一定ax):

fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(1,1,1)

       然后,设置x轴的格式为[%b:月份英文缩写] [%Y:年份]:

plt.xlabel(' ',fontsize=16) ax.xaxis.set_major_formatter(mdate.DateFormatter('%b %Y'))

       之后,设置x轴刻度范围,这里要用到pandas库(简写pd):

plt.xlabel(' ',fontsize=16) ax.xaxis.set_major_formatter(mdate.DateFormatter('%b %Y')) plt.xticks(pd.date_range('2014-01','2014-12',freq='MS'),rotation=30) # freq='MS',设置刻度格式为每月的开始(month start frequency)

关于pandas.date_range()中freq设置方法,见:pandas-date_range(freq)

经过上述代码修改,现在的代码为(示例代码为书中第十六章习题16-2,多了个两地天气对比):

# -*- coding:utf-8 -*- """ Death Valley and Sitka temperatures:highs and lows @auther:Wangsheng """ import csv from datetime import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdate import pandas as pd filename1 = 'death_valley_2014.csv' with open(filename1) as f_obj: reader = csv.reader(f_obj) header_row = next(reader) dates_D,highs_D,lows_D = [ ], [ ],[ ] for row in reader: try: current_date = datetime.strptime(row[0],'%Y-%m-%d') high = int(row[1]) low = int(row[3]) except ValueError: print(current_date,"missing data") else: dates_D.append(current_date) highs_D.append(high) lows_D.append(low) filename2 = 'sitka_weather_2014.csv' with open(filename2) as f_obj: reader = csv.reader(f_obj) header_row = next(reader) dates_S,highs_S,lows_S = [ ], [ ],[ ] for row in reader: try: current_date = datetime.strptime(row[0],'%Y-%m-%d') high = int(row[1]) low = int(row[3]) except ValueError: print(current_date,"missing data") else: dates_S.append(current_date) highs_S.append(high) lows_S.append(low) # 根据数据绘制图形 fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(1,1,1) plt.plot(dates_D,highs_D,label='Death Valley highs',c='red',alpha=0.5) # alpha设置line的透明度0~1,0为完全透明 plt.plot(dates_D,lows_D,label='Death Valley lows',c='blue',alpha=0.5) plt.plot(dates_S,highs_S,label='Sitka highs',c='red',alpha=0.3) plt.plot(dates_S,lows_S,label='Sitka lows',c='blue',alpha=0.3) plt.fill_between(dates_D,highs_D,lows_D,facecolor='blue',alpha=0.2) plt.fill_between(dates_S,highs_S,lows_S,facecolor='blue',alpha=0.15) # 设置图形的格式 plt.title('Daily high and low temperatures - 2014\nDeath Valley and Sitka, CA',fontsize=20) #设置x轴日期格式 plt.xlabel(' ',fontsize=16) ax.xaxis.set_major_formatter(mdate.DateFormatter('%b %Y')) plt.xticks(pd.date_range('2014-01','2014-12',freq='MS'),rotation=30) plt.ylabel("Temperature ( F )",fontsize=16) plt.ylim([0,120]) # 设置y轴刻度范围 plt.tick_params(axis='both',which='major',labelsize=16) plt.legend() # 用于显示诸如plt.plot(dates_S,highs_S,label='Sitka highs',c='red',alpha=0.3)中的label标签 plt.show()

所得图形。

 

希望对你有帮助。

 

公众号:胜言

博客:wangsheng.tech

THANKS.

 

转载请注明原文地址: https://www.6miu.com/read-3100013.html

最新回复(0)