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

时间:2009-08-13 17:33:30

标签: python graph matplotlib financial

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

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

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

8 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:5)

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

答案 2 :(得分:5)

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

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

alt text

答案 3 :(得分: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()

答案 4 :(得分:2)

您可以简单地将日期更改为字符串:

import matplotlib.pyplot as plt
import datetime

f = plt.figure(1, figsize=(10,5))
ax = f.add_subplot(111)

today = datetime.datetime.today().date()
yesterday = today - datetime.timedelta(days=1)
three_days_later = today + datetime.timedelta(days=3)

x_values = [yesterday, today, three_days_later]
y_values = [75, 80, 90]

x_values = [f'{x:%Y-%m-%d}' for x in x_values]
ax.bar(x_values, y_values, color='green')
plt.show()

答案 5 :(得分:1)

使用Matplotlib 2.1.2,Python 2.7.12

的最新答案(2018)

函数/main处理具有等距数据点间距的简单日期x轴所需的一切。使用基于ticker.FuncFormatterthis example实现。

equidate_ax

Comparison of default plotting method and equidistant x-axis

答案 6 :(得分: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()   

答案 7 :(得分:0)

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()