I'm really struggling to understand how to build chaco bar plots.
I've been poring over an online example and have reduced it down to the following simplified code:
import numpy as np
from traits.api import HasTraits, Instance
from traitsui.api import View, Item
from chaco.api import BarPlot, ArrayDataSource, DataRange1D, LinearMapper
from enable.api import ComponentEditor
class MyBarPlot(HasTraits):
plot = Instance(BarPlot)
traits_view = View(
Item('plot',editor=ComponentEditor(), show_label=False))
def _plot_default(self):
idx = np.array([1, 2, 3, 4, 5])
vals = np.array([2, 4, 7, 4, 3])
index = ArrayDataSource(idx)
index_range = DataRange1D(index, low=0.5, high=5.5)
index_mapper = LinearMapper(range=index_range)
value = ArrayDataSource(vals)
value_range = DataRange1D(value, low=0)
value_mapper = LinearMapper(range=value_range)
plot = BarPlot(index=index, value=value,
value_mapper=value_mapper,
index_mapper=index_mapper)
return plot
if __name__ == "__main__":
myplot = MyBarPlot()
myplot.configure_traits()
Needless to say my attempt didn't work. When I run this code (in an ipython notebook) all I get is a blank plot window, filled with black.
I suspect my error might have something to do with the 'valuemapper' entries as I don't really understand what these are for. I'd be grateful for any pointers on my code error.
More generally, this coding approach seems very complicated to me - is there a simpler way to make chaco bar plots?
Unfortunately, the bar_width
trait of BarPlot
doesn't try to be smart here. The default is a width of 10 in data space, which completely overwhelms the width of the plot. To fix this, you can adjust the width manually:
plot = BarPlot(index=index, value=value,
value_mapper=value_mapper,
index_mapper=index_mapper,
bar_width=0.8)
Note that this still won't give you a proper "bar plot" because you'll be missing the surrounding axes decorations and other components. The easiest way to accomplish that would be to use chaco's Plot
object.
Here's an example that adds a BarPlot
instance to a Plot
:
https://github.com/enthought/chaco/blob/master/examples/demo/tornado.py
And here's an example that creates a bar plot using the plot
convenience method in Plot
:
https://github.com/enthought/chaco/blob/master/examples/demo/basic/bar_plot_stacked.py
Yes, "plot" is quite terribly overloaded (Chaco - Getting multiple data series to use the same axes and maps).