亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 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 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號