将Pandas日期转换为Chaco合规日期

时间:2014-02-27 14:14:38

标签: python pandas chaco

[编辑

EDIT]

我想在我的Chaco情节中的轴上绘制我的熊猫DataFrame的日期

我不知道如何将DataFrame中的PeriodIndex转换为Chaco可以接受的内容。

我的数据框索引看起来像这样

>>> dataframe.index
<class 'pandas.tseries.period.PeriodIndex'>
freq: B
[1984-09-07, ..., 2014-01-16]
length: 7404

我能得到的最好的情节看起来像这样..注意日期不正确

enter image description here

这是一个展示问题的示例应用程序..我试图尽可能简洁。

如何将pandas日期转换为chaco日期?

非常感谢任何帮助。

# Enthought library imports
from enable.api import Component, ComponentEditor
from traits.api import HasTraits, Instance
from traitsui.api import UItem, View

# Chaco imports
from chaco.api import ArrayPlotData, Plot, ArrayDataSource, CandlePlot, BarPlot, DataRange1D, \
        LinePlot, LinearMapper, VPlotContainer, PlotAxis, PlotGrid, \
        FilledLinePlot, add_default_grids, PlotGraphicsContext
from chaco.tools.api import PanTool, ZoomTool
from chaco.scales.api import CalendarScaleSystem
from chaco.scales_tick_generator import ScalesTickGenerator

from pandas import Series, DataFrame, Panel
import numpy as np
import pandas as pd
import datetime
import pickle
import os

def get_my_plot_container():
    dataframe = pd.read_pickle(r"C:\AAPL_result.pickle")

    # ---------HERE HERE HERE HERE !--------------
    #
    # I want to convert my pandas DataFrame PeriodIndex into something chaco can use.. 

    df_index = dataframe.index.to_timestamp().values.astype(float)
    df_index = df_index / (1000.0 * 3600.0*24.0) # divide by milliseconds in a day. (total hack.)

    close = dataframe["Close"].values

    index_ads   = ArrayDataSource(df_index)
    close_ads   = ArrayDataSource(close)

    x_range =  DataRange1D(index_ads)
    y_range = DataRange1D(close_ads)

    xmapper =  LinearMapper(range = x_range)
    ymapper = LinearMapper(range = y_range)
    tick_gen = ScalesTickGenerator(scale=CalendarScaleSystem())

    myplot = FilledLinePlot(
        index           = index_ads,
        value           = close_ads,
        index_mapper    = xmapper,
        value_mapper    = ymapper,
        tick_generator  = tick_gen 
    )

    bottom_axis = PlotAxis(component = myplot,
                            orientation='bottom',
                            title="Date",
                            mapper=myplot.x_mapper,
                            tick_generator  = tick_gen,
                            )

    myplot.underlays.append(bottom_axis)

    myVplot_container = VPlotContainer(padding=200)
    myVplot_container.add(myplot)

    return myVplot_container





class Demo(HasTraits):
    myplot = Instance(Component)

    traits_view = View(UItem('myplot', editor=ComponentEditor()),
                       width=1920, height=1080, resizable=True,
                       title="Candlestick plot")

    def _myplot_default(self):
         return get_my_plot_container()

demo = Demo()

if __name__ == "__main__":


    demo.configure_traits()

#--EOF---

1 个答案:

答案 0 :(得分:0)

我认为以下内容代表了当前使用DateTime索引绘制Pandas DataFrames的最佳实践:

import numpy as np
from pandas import DataFrame, date_range

from chaco.api import ArrayPlotData, PlotAxis
from chaco.shell.scaly_plot import ScalyPlot
from chaco.scales.api import CalendarScaleSystem
from enable.api import ComponentEditor
from traits.api import HasTraits, Instance
from traitsui.api import Item, View


class DateTimeIndexPlot(HasTraits):
    plot = Instance(ScalyPlot)

    def _plot_default(self):
        df = DataFrame(
            np.random.randn(10, 2),
            index=date_range("01/01/2018", periods=10, frequency="D"),
            columns=['A', 'B'],
        )
        data = ArrayPlotData(
            x=df.index.values.astype('datetime64[s]').astype(float),
            y_a=df['A'],
            y_b=df['B'],
            )
        plot = ScalyPlot(
            data,
            linear_scale_factory=CalendarScaleSystem,
            y_axis=PlotAxis(orientation='left')
        )
        plot.plot(('x', 'y_a'))
        plot.plot(('x', 'y_b'))
        return plot

    traits_view = View(
        Item('plot', editor=ComponentEditor(), show_label=False),
        title="Chaco plot - DataFrame with DateTimeIndex"
        )

if __name__ == '__main__':
    dtip = DateTimeIndexPlot()
    dtip.configure_traits()

请注意,我将标准比例系统设置为CalendarScaleSystem,然后使用PlotAxis覆盖该系统以获取默认的滴答生成器。我在Chaco v4.7.1中的结果如下所示: enter image description here