为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喔喔 2022-07-12 16:23:47
我正在尝试使用 hvplot 绘制具有 3 个分类变量和 1 个数值变量的堆积条形图。有谁知道如何正确绘制堆积条形图?请求类型“D”和“S”未以不同颜色显示。数据:https://i.stack.imgur.com/YRXtUm.png 我的代码: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下面是我得到的情节:https://i.stack.imgur.com/op89L.png
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

目前,在 HoloViews (1.13) 中,条形图不可能有超过 2 个分类变量。


另请参阅此 github 问题:

https ://github.com/holoviz/holoviews/issues/2878


但是,您可以执行以下解决方法:

诀窍是在关键字中放置一个x分类变量,一个分类变量,以及其他分类变量关键字by中的变量。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')



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

https://i.stack.imgur.com/fcl7z.png

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')


查看完整回答
反对 回复 2022-07-12
  • 1 回答
  • 0 关注
  • 159 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号