对于普通条形图,您可以按照您希望的方式对数据进行排序。
但是,对于分组条形图,您还不能设置顺序。
但此功能的开发正在进行中,可能会在下一个版本中提供:https://github.com/holoviz/holoviews/issues/3799
当前使用 Hvplot 0.5.2 和 Holoviews 1.12 的解决方案:
1) 如果您使用的是 Bokeh 后端,则可以使用关键字挂钩:
from itertools import product
# define hook function to set order on bokeh plot
def set_grouped_barplot_order(plot, element):
# define you categorical ordering in a list of tuples
factors = product(['2', '1'], ['le', 'la', 'lu'])
# since you're using horizontal bar set order on y_range.factors
# if you would have had a normal (vertical) barplot you would use x_range.factors
plot.state.y_range.factors = [*factors]
# create plot
group = df.groupby("group").sum()
group_plot = group.hvplot.barh(
x="group",
y=["le", "la", "lu"],
padding=0.05,
)
# apply your special ordering function
group_plot.opts(hooks=[set_grouped_barplot_order], backend='bokeh')
Hooks 允许您将特定的散景设置应用于您的绘图。您不需要经常使用钩子,但在这种情况下它们非常方便。
文档:
http://holoviews.org/user_guide/Customizing_Plots.html#Plot-hooks
https://holoviews.org/FAQ.html
2) 另一种解决方案是将您的 Holoviews 图转换为实际散景图,然后设置排序:
from itertools import product
import holoviews as hv
from bokeh.plotting import show
# create plot
group = df.groupby("group").sum()
group_plot = group.hvplot.barh(
x="group",
y=["le", "la", "lu"],
padding=0.05,
)
# render your holoviews plot as a bokeh plot
my_bokeh_plot = hv.render(group_plot, backend='bokeh')
# set the custom ordering on your bokeh plot
factors = product(['2', '1'], ['le', 'la', 'lu'])
my_bokeh_plot.y_range.factors = [*factors]
show(my_bokeh_plot)
我个人更喜欢第一种解决方案,因为它保留在 Holoviews 中。
结果图: