Matplotlib Date Index Formatter 日期索引格式化学习

官方网站:https://matplotlib.org/gallery/ticks_and_spines/date_index_formatter2.html#sphx-glr-gallery-ticks-and-spines-date-index-formatter2-py

 

效果图:

 

代码:

"""
====================
Date Index Formatter
====================
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.dates import bytespdate2num, num2date
from matplotlib.ticker import Formatter

# 读取matplotlib cbook文件夹下的msft.csv 文件
datafile = cbook.get_sample_data('msft.csv', asfileobj=False) 
print('loading %s' % datafile)

# names=True 跳过头行
# 使用最后40行 日期转化为matplotlib Date 格式
msft_data = np.genfromtxt(datafile, delimiter=',', names=True,
                          converters={0: bytespdate2num('%d-%b-%y')})[-40:] 
print(msft_data)

class MyFormatter(Formatter):
    def __init__(self, dates, fmt='%Y-%m-%d'):
        self.dates = dates
        self.fmt = fmt

#判断数据这一列的行数并转换显示
    def __call__(self, x, pos=0):
        'Return the label for time x at position pos'
        ind = int(np.round(x))  # round舍去小数点
        if ind >= len(self.dates) or ind < 0:
            return ''

        return num2date(self.dates[ind]).strftime(self.fmt)
    
# 将Date列的所有数据num转换为%Y-%m-%d 格式的日期
formatter = MyFormatter(msft_data['Date']) 
# print (formatter.__dict__)

#设置子图
fig, ax = plt.subplots()
# X轴格式化设置
ax.xaxis.set_major_formatter(formatter)
# X轴对应 Date  Y轴对应 Close   o- 设置曲线样式
ax.plot(np.arange(len(msft_data)), msft_data['Close'], 'o-')
# 旋转对齐X轴日期
fig.autofmt_xdate()
plt.show()

 

转载于:https://www.cnblogs.com/siyun/p/10558672.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值