使用 hvplot/holoviews 更改分组条形图中条形的顺序

Mic*_*elA 5 python bokeh holoviews hvplot holoviz

我尝试创建分组条形图,但无法弄清楚如何影响条形图的顺序。

给定这些示例数据:

import pandas as pd
import hvplot.pandas

df = pd.DataFrame({
    "lu": [200, 100, 10], 
    "le": [220, 80, 130], 
    "la": [60, 20, 15], 
    "group": [1, 2, 2],
})
df = df.groupby("group").sum()
Run Code Online (Sandbox Code Playgroud)

我想创建一个水平分组条形图,显示两个组 1 和 2 以及所有三列。列应按“le”、“la”和“lu”的顺序出现。

当然,我会尝试使用 Hvplot:

df.hvplot.barh(x = "group", y = ["le", "la", "lu"])
Run Code Online (Sandbox Code Playgroud)

这样我得到下面的结果: 分组条形图顺序错误 hvplot

Hvplot 似乎并不关心我添加列的顺序(调用df.hvplot.barh(x = "group", y = ["lu", "le", "la"])不会改变任何内容。Hvplot 似乎也不关心数据框中的原始顺序。

是否有任何选项可以影响条形的顺序?

San*_*ord 4

这个问题刚刚在 HoloViews 1.13 中得到修复

您可以按照您想要的方式对条形图进行排序:

df.hvplot.barh(x="group", y=["lu", "la", "le"])
Run Code Online (Sandbox Code Playgroud)


在我撰写本文时,HoloViews 1.13 尚未正式发布,但您可以通过以下方式安装它:

pip 安装 git+ https://github.com/holoviz/holoviews.git


如果您想更多地控制顺序,可以在 grouped_barplot 上使用 .redim.values() :

group_specific_order = [2, 1]
variable_specific_order = ['lu', 'la', 'le']

# Note that group and Variable are the variable names of your dimensions here
# when you use this on a different grouped barchart, then please change to the 
# names of your own dimensions.
your_grouped_barplot.redim.values(
    group=group_specific_order, 
    Variable=variable_specific_order,
)
Run Code Online (Sandbox Code Playgroud)