ax.plot_date((dates, dates), (highs, lows), '-')

我目前正在使用此命令来绘制财务高点和低点 Matplotlib. 。效果很好,但如何删除 x 轴上没有市场数据的日子(例如周末和节假日)留下的空白?

我有日期、最高价、最低价、收盘价和开盘价列表。我找不到任何创建带有 x 轴的图表的示例,该图表显示日期但不强制执行恒定比例。

有帮助吗?

解决方案

我觉得你需要“人工合成”要使用xticks设置刻度标签代表的日期(当然将蜱在均布的时间间隔,即使你代表的日期字符串情节的确切形式不平均分布),然后使用纯plot

其他提示

有一个如何做到这一点的Matplotlib网站的例子:

https://matplotlib.org/gallery/ticks_and_spines/date_index_formatter.html

我将通常使用 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()

之一的 scikits.timeseries 中的广告特征是“创建与智能隔开轴标签时间序列图”。

您可以看到一些例如地块这里。在第一个例子(如下所示)的“业务”频率被用于所述数据,其中自动排除假日和周末等。它也掩盖丢失的数据点,你看到的差距在这个情节,而不是线性插值他们。

“替代文字”

使用 Matplotlib 2.1.2、Python 2.7.12 的最新答案(2018)

功能 equidate_ax 处理具有等距数据点间距的简单日期 x 轴所需的一切。实现与 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)

Comparison of default plotting method and equidistant x-axis

我就遇到了这个问题,再次,是能够创造一个体面的函数来处理这个问题,特别是关于盘中日期时间。信用到@Primer 该答案。

def plot_ts(ts, step=5, figsize=(10,7), title=''):
    """
    plot timeseries ignoring date gaps

    Params
    ------
    ts : pd.DataFrame or pd.Series
    step : int, display interval for ticks
    figsize : tuple, figure size
    title: str
    """

    fig, ax = plt.subplots(figsize=figsize)
    ax.plot(range(ts.dropna().shape[0]), ts.dropna())
    ax.set_title(title)
    ax.set_xticks(np.arange(len(ts.dropna())))
    ax.set_xticklabels(ts.dropna().index.tolist());

    # tick visibility, can be slow for 200,000+ ticks 
    xticklabels = ax.get_xticklabels() # generate list once to speed up function
    for i, label in enumerate(xticklabels):
        if not i%step==0:
            label.set_visible(False)  
    fig.autofmt_xdate()   

scikits.timeseries功能已经在很大程度上被移动到熊猫,所以现在可以重新取样一个数据帧只包括在工作日的值。

>>>import pandas as pd
>>>import matplotlib.pyplot as plt

>>>s = pd.Series(list(range(10)), pd.date_range('2015-09-01','2015-09-10'))
>>>s

2015-09-01    0
2015-09-02    1
2015-09-03    2
2015-09-04    3
2015-09-05    4
2015-09-06    5
2015-09-07    6
2015-09-08    7
2015-09-09    8
2015-09-10    9

>>> s.resample('B', label='right', closed='right').last()
2015-09-01    0
2015-09-02    1
2015-09-03    2
2015-09-04    3
2015-09-07    6
2015-09-08    7
2015-09-09    8
2015-09-10    9

和然后绘制数据帧作为正常

s.resample('B', label='right', closed='right').last().plot()
plt.show()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top