【问题标题】:Chaco bar plotsChaco 条形图
【发布时间】:2015-04-04 18:28:22
【问题描述】:

真的很难理解如何构建 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 条形图?

【问题讨论】:

    标签: enthought chaco


    【解决方案1】:

    不幸的是,BarPlotbar_width 特征在这里并不聪明。数据空间中的默认宽度为 10,这完全超过了绘图的宽度。要解决此问题,您可以手动调整宽度:

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

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

    这是一个将BarPlot 实例添加到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)。

    【讨论】:

    • 非常感谢 tsyu80 的回复。是的,你是对的,为 bar_width 设置一个适当的值可以使绘图条彼此区分开来,而不是它们都被一个大粗条挡住(这就是为什么我的绘图全是黑色的)。也感谢你的例子。使用绘图便捷方法的第二个似乎提供了“最简单”的解决方案,尽管与 matplotlib 条形图相比它似乎仍然非常复杂
    • 如果您的目标只是生成静态图,Chaco 肯定会更加冗长。也就是说,Chaco 更专注于将绘图嵌入到应用程序中。如果您正在创建一个带有交互式绘图的应用程序,您可能会发现 Chaco 比 matplotlib 更简单。
    • 是的,好点。当我开始掌握整个 traits/ui/chaco 范式时,我非常喜欢它。
    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2017-03-27
    • 2012-03-13
    • 2013-07-03
    相关资源
    最近更新 更多