Eri*_*Red 18 python graph matplotlib financial
ax.plot_date((dates, dates), (highs, lows), '-')
Run Code Online (Sandbox Code Playgroud)
我目前正在使用此命令使用Matplotlib绘制金融高点和低点.它工作得很好,但是如何在没有市场数据的情况下删除x轴上的空白区域,例如周末和假日?
我有日期,高点,低点,关闭和打开的列表.我找不到任何创建带有x轴的图表的示例,该图表显示日期但不强制执行常量比例.
idr*_*bst 10
有一个如何在Matplotlib网站上执行此操作的示例:
https://matplotlib.org/gallery/ticks_and_spines/date_index_formatter.html
我认为你需要通过使用xticks将标签标签设置为代表日期的字符串来"人工合成"你想要的确切形式(当然,即使你所代表的日期不是等间隔的,也会以等间距的方式设置标记. )然后使用平原plot.
scikits.timeseries的一个广告功能是"创建具有智能间隔轴标签的时间序列图".
你可以在这里看到一些示例图.在第一个示例(如下所示)中,"业务"频率用于数据,其自动排除假日和周末等.它还会屏蔽缺失的数据点,您可以将其视为此图中的间隙,而不是线性插值.
alt text http://pytseries.sourceforge.net/_images/yahoo.png
我通常会将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()
Run Code Online (Sandbox Code Playgroud)
使用 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)
Run Code Online (Sandbox Code Playgroud)
我再次遇到这个问题,并能够创建一个像样的函数来处理这个问题,特别是关于日内日期时间。感谢@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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18011 次 |
| 最近记录: |