如何在财务Matplotlib Python图中跳过空日期(周末)?

问题描述 投票:15回答:6
ax.plot_date((dates, dates), (highs, lows), '-')

我目前正在使用此命令使用Matplotlib绘制金融高点和低点。它工作得很好,但是如何在没有市场数据的情况下删除x轴上的空白区域,例如周末和假日?

我有日期,高点,低点,关闭和打开的列表。我找不到任何创建带有x轴的图表的示例,该图表显示日期但不强制执行常量比例。

python graph matplotlib financial
6个回答
5
投票

我认为你需要通过使用xticks将刻度标签设置为代表日期的字符串来“人工合成”你想要的确切形式(当然,即使你所代表的日期不是equispaced)然后使用普通的plot


9
投票

有一个如何在Matplotlib网站上执行此操作的示例:

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


5
投票

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

5
投票

scikits.timeseries的一个广告功能是“创建具有智能间隔轴标签的时间序列图”。

你可以看到一些示例图here。在第一个示例(如下所示)中,“业务”频率用于数据,其自动排除假日和周末等。它还会屏蔽缺失的数据点,您可以将其视为此图中的间隙,而不是线性插值。

alt text


1
投票

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

函数equidate_ax处理一个简单的日期x轴所需的一切,数据点的间距相等。使用基于ticker.FuncFormatterthis example实现。

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


0
投票

我再次遇到这个问题,并且能够创建一个很好的函数来处理这个问题,特别是关于日内日期时间。感谢@Primer for this answer.

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 
    for i, label in enumerate(ax.get_xticklabels()):
        if not i%step==0:
            label.set_visible(False)  
    fig.autofmt_xdate()   

0
投票

scikits.timeseries功能大部分已移至pandas,因此您现在可以重新采样数据帧,仅在工作日包含值。

>>>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()
© www.soinside.com 2019 - 2024. All rights reserved.