matplotlib处理日期值,设置主副刻度

导入模块

import datetime
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates

设置格式并导入数据 

months = mdates.MonthLocator()#刻度上显示出月份
days = mdates.DayLocator()#刻度上显示出每月的几号
timeFmt = mdates.DateFormatter('%Y-%m')#格式化时间形式(年-月)
#input data
events = [datetime.date(2021,1,23),datetime.date(2021,1,28),
          datetime.date(2021,2,3),datetime.date(2021,2,21),
          datetime.date(2021,3,15),datetime.date(2021,3,24),
          datetime.date(2021,4,8),datetime.date(2021,4,24)]
readings = [12,22,25,20,18,15,17,14]

 绘图,设置刻度

'''
fig代表绘图窗口(Figure);ax代表这个绘图窗口上的坐标系(axis)
fig,ax = plt.subplots()等价于:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.plot(events,readings)
'''

fig,ax = plt.subplots()
#设置主副刻度
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(timeFmt)
ax.xaxis.set_minor_locator(days)
#字符串旋转
for label in ax.get_xticklabels(): 
    label.set_rotation(30)  #逆时针旋转30°
    label.set_horizontalalignment('right')  #右对齐

plt.show()

结果


参考:

法比奥·内利. Python数据分析实战:第2版.北京:人民邮电出版社, 2019.11.

fig, ax = plt.subplots(figsize = (a, b))解析 与 plt.subplot()函数解析_哎呦-_-不错的博客-CSDN博客

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值