python - 如何使用 hvplot 绘制堆积条形图?

标签 python holoviews hvplot holoviz

我正在尝试使用 hvplot 绘制包含 3 个 calcategories 变量和 1 个数值变量的堆积条形图。

有谁知道如何正确绘制堆积条形图?
请求类型“D”和“S”不会以不同的颜色显示。

数据:
image of data with 3 categories and 1 numerical value

我的代码:

by_type = test_df.groupby(['Type', 'Fiscal Period', 'Request Type']).agg({'Count': np.sum})
plot_by_type = by_type.hvplot.bar('Type','Count', by=['Fiscal Period', 'Request Type'], stacked=False, 
                                    flip_xaxis=False, ylabel='Total Count', invert=False,
                                                     cmap=['silver', 'goldenrod'])
plot_by_type

下面是我得到的情节: image of data with 3 categories and 1 numerical value

最佳答案

目前,HoloViews (1.13) 中的条形图不可能有 2 个以上的分类变量。

另请参阅此 github 问题:
https://github.com/holoviz/holoviews/issues/2878

但是,您可以采取如下解决方法:
诀窍是将一个分类设置为 xby 中的一个分类变量关键字以及 groupby 中的其他分类变量关键字。

import pandas as pd
import hvplot.pandas

# create sample data
df = pd.DataFrame({
    'Type': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
    'Fiscal Period': ['2019-01', '2019-01', '2019-02', '2019-02', '2019-01', '2019-01', '2019-02', '2019-02'],
    'Request Type': ['S', 'D', 'S', 'D', 'S', 'D', 'S', 'D'],
    'values': range(1, 9),
})

# create a separate barchart per Type
layout = df.hvplot.bar(
    x='Fiscal Period', 
    y='values', 
    by='Request Type', 
    groupby='Type', 
    stacked=True, 
    cmap='Category20', 
    legend='top_left',
    width=400,
    xlabel='',
).layout()

# make plots nicer so they look more like a clustered barchart
plotA = layout['A'].opts(title='Type: A')
plotB = layout['B'].opts(show_legend=False, yaxis=None, ylabel='', title='Type: B')

# add separate plots together again
(plotA + plotB).opts(title='Showing the counts per Fiscal Period, Request Type and Type')



结果图:

workaround for barchart with 3 categorical variables

作为奖励,此代码将为您提供与上面相同的结果:

def create_subplot(type_selected):
    plot = df[df['Type'] == type_selected].hvplot.bar(
        x='Fiscal Period', 
        y='values', 
        by='Request Type', 
        stacked=True, 
        cmap='Category20', 
        label='Type: ' + type_selected,
        legend='top_left',
        width=400,
        xlabel='',
        ylabel='',
    )
    return plot

plotA = create_subplot('A')
plotB = create_subplot('B').opts(show_legend=False, yaxis=None)

(plotA + plotB).opts(title='Showing the counts per Fiscal Period, Request Type and Type')

关于python - 如何使用 hvplot 绘制堆积条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59980448/

相关文章:

python3默认编码UnicodeDecodeError ascii使用apache WSGI

python - Ubuntu 上的 Matplotlib 错误 "cannot import name pyplot"

python - 如何在 Python 中的 for 循环内附加数据帧

python - 在 Python 中检测 64 位操作系统(Windows)

python - 为什么我从 HoloViews 保存的 Datashader 绘图的分辨率这么低?

python - 如何在大数据集上创建交互式图表?

python - 如何在 Databricks 上使用 HoloViews/hvPlot

python - 如何将 HoloViews (hvplot) 绘图的 X 轴与面板 DatetimePicker(或 DatetimeRangePicker)小部件双向链接

python - Holoviews:代码没有显式定义的 UI 组件

python - hvplot.heatmap 与 Pandas 数据框 : How to specify value dimensions?