EDIT - I've rewritten the code to make it more readable. I also changed it to just plot a FilledLine instead of candlesticks. *I still need help though!*
I'm new to Chaco (and pandas, and python !) but I'm finally beginning to get the hang of it.. But I've hit a couple of problems and I'm running out of ideas for how to make progress with them..
I've attached my current python source file below.
The program creates this image
As you can see, the x axis is not showing the dates correctly, I want the plot to show the dates in some human readable form "10: 2003, 11: 2003, 12:2003".. Something like that... The pandas DataFrame index is a PeriodIndex which I initially tried to convert to something Chaco would recognise using
df_index = ArrayDataSource(mydataframe.index.to_datetime().values.astype(datetime.datetime))
But I then get thousands of errors saying
Traceback (most recent call last):
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\abstract_window.py", line 420, in _paint
self.component.draw(gc, view_bounds=(0, 0, size[0], size[1]))
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\component.py", line 421, in draw
self._draw(gc, view_bounds, mode)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\component.py", line 763, in _draw
self._dispatch_draw(layer, bb, view_bounds, mode)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\container.py", line 327, in _dispatch_draw
component._dispatch_draw(layer, gc, new_bounds, mode)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\component.py", line 793, in _dispatch_draw
handler(gc, view_bounds, mode)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\chaco\candle_plot.py", line 169, in _draw_plot
self._render(gc, left, right, *vals)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\chaco\base_candle_plot.py", line 126, in _render
gc.line_set(stack((bar_vert_center, min)), stack((bar_vert_center, max)))
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\kiva\agg\agg.py", line 1012, in line_set
def line_set(self, *args): return _agg.GraphicsContextArray_line_set(self, *args)
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
The second problem I have is that I want to save the image generated to disk as a .PNG file or .JPEG.
I took some code from the noninteractive.py chaco example.. But when I look at the image thats saved I see that its just a blank image and the file is only 4.19 kb (or 10k for jpeg)
If anyone can help me fix either of these problems I'd be very grateful.
Any ideas or suggestions would be much appreciated :)
-Jason
Here's the code
//-------------------------------------------------------------------------------------
# Major library imports
from numpy import abs, arange, cumprod, random, vstack
# 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
from chaco.tools.api import PanTool, ZoomTool
from chaco.api import ArrayDataSource, CandlePlot, BarPlot, DataRange1D, \
LinePlot, LinearMapper, VPlotContainer, PlotAxis, PlotGrid, \
FilledLinePlot, add_default_grids, PlotGraphicsContext
from chaco.tools.api import PanTool, ZoomTool, RangeSelection, \
RangeSelectionOverlay
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
from pandas.tseries.offsets import Hour, Minute
#from Plotting import PlottingClass
import datetime
import pickle
import itertools
import random
from contextlib import contextmanager
import time
import cython
#import multiprocessing
from math import floor
import os
import dateutil.parser as parser
import scipy
def get_my_plot_container():
pickleName = r"C:\AAPL_result.pickle"
dataframe = pd.read_pickle(pickleName)
# ---------HERE HERE HERE HERE !--------------
#
# I convert my pandas DataFrame PeriodIndex to something chaco can use.. but I cat get dates to work.
df_index = dataframe.index.to_datetime().values.astype(float) # .values.astype(datetime.datetime) #
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)
myplot = FilledLinePlot(
index = index_ads,
value = close_ads,
index_mapper = xmapper,
value_mapper = ymapper,
)
bottom_axis = PlotAxis(component = myplot,
orientation='bottom',
title="Date",
mapper=myplot.x_mapper,
)
myplot.underlays.append(bottom_axis)
myVplot_container = VPlotContainer(padding=200)
myVplot_container.add(myplot)
return myVplot_container
def save_plot(plot, filename):
width, height = plot.outer_bounds
plot.do_layout(force=True)
gc = PlotGraphicsContext((width, height), dpi=72.0*2)
gc.render_component(plot)
gc.save(filename)
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__":
# ---------HERE HERE HERE HERE !--------------
#
# Here I get my VPlotContainer containing the CandlePlot and its axes etc. and then try to save it..
# But I just get an blank png / jpeg file
myVplot_container = get_my_plot_container()
#save_plot(myVplot_container, r"Z:\JJJJJJ.png")
save_plot(myVplot_container, r"Z:\JJJJJJ.jpg")
demo.configure_traits()
#--EOF---
EDIT - I've rewritten the code to make it more readable. I also changed it to just plot a FilledLine instead of candlesticks. *I still need help though!*
I'm new to Chaco (and pandas, and python !) but I'm finally beginning to get the hang of it.. But I've hit a couple of problems and I'm running out of ideas for how to make progress with them..
I've attached my current python source file below.
The program creates this image
As you can see, the x axis is not showing the dates correctly, I want the plot to show the dates in some human readable form "10: 2003, 11: 2003, 12:2003".. Something like that... The pandas DataFrame index is a PeriodIndex which I initially tried to convert to something Chaco would recognise using
df_index = ArrayDataSource(mydataframe.index.to_datetime().values.astype(datetime.datetime))
But I then get thousands of errors saying
Traceback (most recent call last):
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\abstract_window.py", line 420, in _paint
self.component.draw(gc, view_bounds=(0, 0, size[0], size[1]))
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\component.py", line 421, in draw
self._draw(gc, view_bounds, mode)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\component.py", line 763, in _draw
self._dispatch_draw(layer, bb, view_bounds, mode)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\container.py", line 327, in _dispatch_draw
component._dispatch_draw(layer, gc, new_bounds, mode)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\enable\component.py", line 793, in _dispatch_draw
handler(gc, view_bounds, mode)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\chaco\candle_plot.py", line 169, in _draw_plot
self._render(gc, left, right, *vals)
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\chaco\base_candle_plot.py", line 126, in _render
gc.line_set(stack((bar_vert_center, min)), stack((bar_vert_center, max)))
File "C:\Users\Jason\AppData\Local\Enthought\Canopy\User\lib\site-packages\kiva\agg\agg.py", line 1012, in line_set
def line_set(self, *args): return _agg.GraphicsContextArray_line_set(self, *args)
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
The second problem I have is that I want to save the image generated to disk as a .PNG file or .JPEG.
I took some code from the noninteractive.py chaco example.. But when I look at the image thats saved I see that its just a blank image and the file is only 4.19 kb (or 10k for jpeg)
If anyone can help me fix either of these problems I'd be very grateful.
Any ideas or suggestions would be much appreciated :)
-Jason
Here's the code
//-------------------------------------------------------------------------------------
# Major library imports
from numpy import abs, arange, cumprod, random, vstack
# 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
from chaco.tools.api import PanTool, ZoomTool
from chaco.api import ArrayDataSource, CandlePlot, BarPlot, DataRange1D, \
LinePlot, LinearMapper, VPlotContainer, PlotAxis, PlotGrid, \
FilledLinePlot, add_default_grids, PlotGraphicsContext
from chaco.tools.api import PanTool, ZoomTool, RangeSelection, \
RangeSelectionOverlay
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
from pandas.tseries.offsets import Hour, Minute
#from Plotting import PlottingClass
import datetime
import pickle
import itertools
import random
from contextlib import contextmanager
import time
import cython
#import multiprocessing
from math import floor
import os
import dateutil.parser as parser
import scipy
def get_my_plot_container():
pickleName = r"C:\AAPL_result.pickle"
dataframe = pd.read_pickle(pickleName)
# ---------HERE HERE HERE HERE !--------------
#
# I convert my pandas DataFrame PeriodIndex to something chaco can use.. but I cat get dates to work.
df_index = dataframe.index.to_datetime().values.astype(float) # .values.astype(datetime.datetime) #
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)
myplot = FilledLinePlot(
index = index_ads,
value = close_ads,
index_mapper = xmapper,
value_mapper = ymapper,
)
bottom_axis = PlotAxis(component = myplot,
orientation='bottom',
title="Date",
mapper=myplot.x_mapper,
)
myplot.underlays.append(bottom_axis)
myVplot_container = VPlotContainer(padding=200)
myVplot_container.add(myplot)
return myVplot_container
def save_plot(plot, filename):
width, height = plot.outer_bounds
plot.do_layout(force=True)
gc = PlotGraphicsContext((width, height), dpi=72.0*2)
gc.render_component(plot)
gc.save(filename)
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__":
# ---------HERE HERE HERE HERE !--------------
#
# Here I get my VPlotContainer containing the CandlePlot and its axes etc. and then try to save it..
# But I just get an blank png / jpeg file
myVplot_container = get_my_plot_container()
#save_plot(myVplot_container, r"Z:\JJJJJJ.png")
save_plot(myVplot_container, r"Z:\JJJJJJ.jpg")
demo.configure_traits()
#--EOF---
0 commentaires:
Enregistrer un commentaire