您如何组织数据以指定不相对于 0 的 hbar_stack 的范围? [背景虚化]

How do you organize data to specify a range for an hbar_stack that is not relative to 0? [Bokeh]

这里有一个代码示例: https://imgur.com/a/mKPNP

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import GnBu3, OrRd3
from bokeh.plotting import figure

output_file("stacked_split.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]

exports = {'fruits' : fruits,
           '2015'   : [2, 1, 4, 3, 2, 4],
           '2016'   : [5, 3, 4, 2, 4, 6],
           '2017'   : [3, 2, 4, 4, 5, 3]}
imports = {'fruits' : fruits,
           '2015'   : [-1, 0, -1, -3, -2, -1],
           '2016'   : [-2, -1, -3, -1, -2, -2],
           '2017'   : [-1, -2, -1, 0, -2, -2]}

p = figure(y_range=fruits, plot_height=250, x_range=(-16, 16), title="Fruit import/export, by year",
           toolbar_location=None)

p.hbar_stack(years, y='fruits', height=0.9, color=GnBu3, source=ColumnDataSource(exports),
             legend=["%s exports" % x for x in years])

p.hbar_stack(years, y='fruits', height=0.9, color=OrRd3, source=ColumnDataSource(imports),
             legend=["%s imports" % x for x in years])

p.y_range.range_padding = 0.1
p.ygrid.grid_line_color = None
p.legend.location = "top_left"
p.axis.minor_tick_line_color = None
p.outline_line_color = None

show(p)

我注意到在这个 hbar_stack 的示例中,条形图是根据相对于 0 的数据呈现的。

我将如何为不包含 0 的柱指定范围?例如,如果我想要一个介于 5 和 10 之间的条?

不幸的是hbar_stack(和vbar_stack)总是从零开始对相关值求和,没有任何偏移量。添加偏移量似乎是需要考虑的潜在合理且直接的事情,因此我建议 making a GitHub issue 请求该功能。

与此同时,有几种不同的方法可以发挥作用

  • 使用一次调用 hbar_stack 但将偏移量预烘焙到您的数据中。如果您的 CDS 列是 numpy 数组或 pandas 系列,这将很简单(将偏移量添加到堆叠的每一列)。类似于:

    for x in years:
        imports[year] += offset
        exports[year] += offset
    

    上面的代码不能按原样工作,因为列是常规的 Python 列表,但是如果您使用 arrays/series,那么添加偏移量将如上所示。

  • 多次调用 hbar 并自行堆叠条形图。 hbar 字形方法接受一个默认为零的参数 left,但您可以根据需要将其设置为固定值或 CDS 列。如果 CDS 列是数组或系列,这也会更容易:

    left = offset
    for x in years:
        right = left + exports[x]
        p.hbar(left=left, right=right)
        left = right
    
    right = offset
    for x in years:
        left = right - imports[x]
        p.hbar(left=left, right=right)
        right = left
    
  • 使用 CustomJSTransform to do the stacking on the client side. Basically, you'd re-implement Stack 但在

  • 中设置偏移量

我使用这个函数来定义颜色范围,而不是从零开始。 希望对你有帮助。

def painter(rate,max_value,min_value,palette):
        darkness = int(float(len(palette)-1) * float(rate - min_value) / float(max_value - min_value))
        return palette[darkness]