python、matplotlib画股票分时图、时间序列图的时候如何跳过没有数据的区域

问题

在画股票日内的分时图,发现中午有一段时间是没有数据的,导致画出来的图中间都一一段横盘时间,为了美观,试了很多种办法想把那一段横线去掉,最后发现利用 FuncFormatter 可以实现

官方给出的方法

11.1.9 Skip dates where there is no data
When plotting time series, e.g., financial time series, one often wants to leave out days on which there is no data, e.g., weekends.
By passing in dates on the x-xaxis, you get large horizontal gaps on periods when there is not data.
The solution is to pass in some proxy x-data, e.g., evenly sampled indices, and then use a custom formatter to format these as dates.
The example below shows how to use an ‘index formatter’ to achieve the desired plot:

先用整数作为下标,然后利用matplotlib.ticker.FuncFormatter改变x轴刻度的格式

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker

#读数据
r = mlab.csv2rec('../data/aapl.csv')
r.sort()
r = r[-30:] # get the last 30 days
N = len(r)
ind = np.arange(N) # the evenly spaced plot indices

# 这个函数x代表的是刻度位置,pos默认为None,函数里面可以用到外部的全局变量
def format_date(x, pos=None):
    #保证下标不越界,很重要,越界会导致最终plot坐标轴label无显示
    thisind = np.clip(int(x+0.5), 0, N-1)
    return r.date[thisind].strftime('%Y-%m-%d')

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()
plt.show()

猜你喜欢

转载自blog.csdn.net/AlanGuoo/article/details/79171271