ax.plot_date((dates, dates), (highs, lows), '-')
我目前使用这个命令来绘制使用Matplotlib的金融高点和低点。它的效果很好,但是如何在没有市场数据的情况下(例如周末和假期)将x轴左侧的空白空白去掉?如何跳过财务Matplotlib Python图表中的空日期(周末)?
我有日期,高点,低点,关闭和打开的列表。我无法找到任何创建带有x轴的图表来显示日期但不强制执行恒定比例的示例。
ax.plot_date((dates, dates), (highs, lows), '-')
我目前使用这个命令来绘制使用Matplotlib的金融高点和低点。它的效果很好,但是如何在没有市场数据的情况下(例如周末和假期)将x轴左侧的空白空白去掉?如何跳过财务Matplotlib Python图表中的空日期(周末)?
我有日期,高点,低点,关闭和打开的列表。我无法找到任何创建带有x轴的图表来显示日期但不强制执行恒定比例的示例。
我认为您需要通过使用xticks
来设置滴答标签到代表日期的字符串中“人工合成”您想要的情节的确切形式(当然,即使您的日期是等间隔放置滴答代表不等间隔),然后使用普通的plot
。
scikits.timeseries的广告功能之一是“创建具有智能间隔轴标签的时间序列图”。
您可以看到一些示例图here。在第一个例子中(如下所示),“商业”频率用于数据,这会自动排除假期和周末等。它还会掩盖缺失的数据点,您将在该图中看到空隙,而不是线性插入它们。
我通常会使用NumPy的NaN(非数字)为无效或不存在的值。它们由Matplotlib表示为图中的空白,NumPy是pylab/Matplotlib的一部分。
>>> import pylab
>>> xs = pylab.arange(10.) + 733632. # valid date range
>>> ys = [1,2,3,2,pylab.nan,2,3,2,5,2.4] # some data (one undefined)
>>> pylab.plot_date(xs, ys, ydate=False, linestyle='-', marker='')
[<matplotlib.lines.Line2D instance at 0x0378D418>]
>>> pylab.show()
有一个如何做到这一点的Matplotlib网站的例子:
https://matplotlib.org/gallery/ticks_and_spines/date_index_formatter.html
到目前为止答案(2018)与Matplotlib 2.1.2,巨蟒2.7.12
函数equidate_ax
可处理数据点间距等距的简单日期x轴所需的所有内容。用基于this example的ticker.FuncFormatter
实现。
from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np
import datetime
def equidate_ax(fig, ax, dates, fmt="%Y-%m-%d", label="Date"):
"""
Sets all relevant parameters for an equidistant date-x-axis.
Tick Locators are not affected (set automatically)
Args:
fig: pyplot.figure instance
ax: pyplot.axis instance (target axis)
dates: iterable of datetime.date or datetime.datetime instances
fmt: Display format of dates
label: x-axis label
Returns:
None
"""
N = len(dates)
def format_date(index, pos):
index = np.clip(int(index + 0.5), 0, N - 1)
return dates[index].strftime(fmt)
ax.xaxis.set_major_formatter(FuncFormatter(format_date))
ax.set_xlabel(label)
fig.autofmt_xdate()
#
# Some test data (with python dates)
#
dates = [datetime.datetime(year, month, day) for year, month, day in [
(2018,2,1), (2018,2,2), (2018,2,5), (2018,2,6), (2018,2,7), (2018,2,28)
]]
y = np.arange(6)
# Create plots. Left plot is default with a gap
fig, [ax1, ax2] = plt.subplots(1, 2)
ax1.plot(dates, y, 'o-')
ax1.set_title("Default")
ax1.set_xlabel("Date")
# Right plot will show equidistant series
# x-axis must be the indices of your dates-list
x = np.arange(len(dates))
ax2.plot(x, y, 'o-')
ax2.set_title("Equidistant Placement")
equidate_ax(fig, ax2, dates)