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

       本人是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.

 

  • 14
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值