2

真的很难理解如何构建 chaco 条形图。

我一直在研究一个在线示例,并将其简化为以下简化代码:

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

不用说我的尝试没有奏效。当我运行这段代码(在 ipython 笔记本中)时,我得到的只是一个空白的绘图窗口,用黑色填充。

我怀疑我的错误可能与“valuemapper”条目有关,因为我不太明白这些条目的用途。对于我的代码错误的任何指示,我将不胜感激。

更一般地说,这种编码方法对我来说似乎非常复杂 - 有没有更简单的方法来制作 chaco 条形图?

4

1 回答 1

3

不幸的是,这里的bar_width特质BarPlot并没有试图变得聪明。数据空间中的默认宽度为 10,这完全超出了绘图的宽度。要解决此问题,您可以手动调整宽度:

 plot = BarPlot(index=index, value=value,
                value_mapper=value_mapper,
                index_mapper=index_mapper,
                bar_width=0.8)

请注意,这仍然不会为您提供正确的“条形图”,因为您将丢失周围的轴装饰和其他组件。最简单的方法是使用 chaco 的Plot对象。

这是一个将BarPlot实例添加到 a的示例Plot

https://github.com/enthought/chaco/blob/master/examples/demo/tornado.py

plot下面是一个使用便捷方法创建条形图的示例Plot

https://github.com/enthought/chaco/blob/master/examples/demo/basic/bar_plot_stacked.py

是的,“情节”非常严重(Chaco - Getting multiple data series to use the same axes and maps)。

于 2015-02-05T04:07:19.747 回答