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

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

使用輔助軸線圖制作分類或分組條形圖

使用輔助軸線圖制作分類或分組條形圖

一只甜甜圈 2021-12-26 15:06:55
我需要使用條形圖和折線圖比較 4 個班次(分類/分組)之間的不同日常數據集。我到處尋找,但沒有找到一個可行的解決方案,其中不包括生成新的支點等。我已經使用了 matplotlib 和 seaborn,雖然我可以做一個或另一個(每個班次的不同顏色的條/線),一旦我合并另一個,要么消失,要么其他異常發生,就像只有一個情節點顯示. 我已經查看了所有的解決方案,可以在兩種圖表類型上表示單個系列的數據,但沒有一個屬于多類別或針對這兩種類型進行分組。數據示例:report_date wh_id   shift   Head_Count  UTL_R3/17/19     55  A   72  25%3/18/19     55  A   71  10%3/19/19     55  A   76  20%3/20/19     55  A   59  33%3/21/19     55  A   65  10%3/22/19     55  A   54  20%3/23/19     55  A   66  14%3/17/19     55  1   11  10%3/17/19     55  2   27  13%3/17/19     55  3   18  25%3/18/19     55  1   23  100%3/18/19     55  2   16  25%3/18/19     55  3   12  50%3/19/19     55  1   28  10%3/19/19     55  2   23  50%3/19/19     55  3   14  33%3/20/19     55  1   29  25%3/20/19     55  2   29  25%3/20/19     55  3   10  50%3/21/19     55  1   17  20%3/21/19     55  2   29  14%3/21/19     55  3   30  17%3/22/19     55  1   12  14%3/22/19     55  2   10  100%3/22/19     55  3   17  14%3/23/19     55  1   16  10%3/23/19     55  2   11  100%3/23/19     55  3   13  10%tm_daily_df = pd.read_csv('fg_TM_Daily.csv')tm_daily_df = tm_daily_df.set_index('report_date')fig2, ax2 = plt.subplots(figsize=(12,8))ax3 = ax2.twinx()group_obj = tm_daily_df.groupby('shift')g = group_obj['Head_Count'].plot(kind='bar', x='report_date',  y='Head_Count',ax=ax2,stacked=False,alpha = .2)g = group_obj['UTL_R'].plot(kind='line',x='report_date', y='UTL_R', ax=ax3,marker='d', markersize=12)plt.legend(tm_daily_df['shift'].unique())這段代碼讓我得到了最接近的結果。請注意,即使使用stacked = False,它們仍然堆疊在一起。我將設置更改為 True,沒有任何變化。我所需要的只是讓條形彼此相鄰,并具有代表班次的相同配色方案圖表:
查看完整描述

2 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

這里有兩種解決方案(堆疊和非堆疊)。根據您的問題,我們將:

  • Head_Count在左 y 軸和UTL_R右 y 軸上繪圖。

  • report_date 將是我們的 x 軸

  • shift 將代表我們圖形的色調。

堆疊版本使用pandas默認繪圖功能,非堆疊版本使用seaborn.

編輯
根據您的要求,我添加了一個 100% 堆疊圖。雖然這與您在評論中所問的不完全相同,但您詢問的圖形類型可能會在閱讀時造成一些混亂(是基于堆棧的上線或堆棧寬度的值)。另一種解決方案可能是使用 100% 堆疊圖。

堆疊


import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt


dfg = df.set_index(['report_date', 'shift']).sort_index(level=[0,1])


fig, ax = plt.subplots(figsize=(12,6))


ax2  = ax.twinx()


dfg['Head_Count'].unstack().plot.bar(stacked=True, ax=ax, alpha=0.6)

dfg['UTL_R'].unstack().plot(kind='line', ax=ax2, marker='o', legend=None)


ax.set_title('My Graph')

plt.show()

http://img1.sycdn.imooc.com//61c814bc0001386e07310428.jpg

堆疊 100%


import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt


dfg = df.set_index(['report_date', 'shift']).sort_index(level=[0,1])


# Create `Head_Count_Pct` column

for date in dfg.index.get_level_values('report_date').unique():

    for shift in dfg.loc[date, :].index.get_level_values('shift').unique():

        dfg.loc[(date, shift), 'Head_Count_Pct'] = dfg.loc[(date, shift), 'Head_Count'].sum() / dfg.loc[(date, 'A'), 'Head_Count'].sum()


fig, ax = plt.subplots(figsize=(12,6))


ax2  = ax.twinx()

pal = sns.color_palette("Set1")


dfg[dfg.index.get_level_values('shift').isin(['1','2','3'])]['Head_Count_Pct'].unstack().plot.bar(stacked=True, ax=ax, alpha=0.5, color=pal)

dfg['UTL_R'].unstack().plot(kind='line', ax=ax2, marker='o', legend=None, color=pal)


ax.set_title('My Graph')

plt.show()

http://img1.sycdn.imooc.com//61c814cb0001d4d907280429.jpg

未堆疊


import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt


dfg = df.set_index(['report_date', 'shift']).sort_index(level=[0,1])


fig, ax = plt.subplots(figsize=(15,6))


ax2  = ax.twinx()


sns.barplot(x=dfg.index.get_level_values('report_date'),

            y=dfg.Head_Count,

           hue=dfg.index.get_level_values('shift'), ax=ax, alpha=0.7)


sns.lineplot(x=dfg.index.get_level_values('report_date'),

            y=dfg.UTL_R,

           hue=dfg.index.get_level_values('shift'), ax=ax2, marker='o', legend=None)


ax.set_title('My Graph')

plt.show()

http://img1.sycdn.imooc.com//61c814dd000117ae09250387.jpg

編輯#2


這是您第二次請求的圖形(堆疊,但堆棧 n+1 不在堆棧 n 結束的地方開始)。


它稍微涉及更多,因為我們必須做多件事: - 我們需要手動將顏色分配給我們shift的 df - 一旦我們分配了顏色,我們將遍歷每個日期范圍和 1)排序或Head_Count值降序(所以當我們繪制圖形時,我們最大的麻袋在后面),以及 2)繪制數據并將顏色分配給每個 stacj - 然后我們可以創建第二個 y 軸并繪制我們的UTL_R值 - 然后我們需要分配正確的顏色到我們的傳奇標簽


import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt


def assignColor(shift):

    if shift == 'A':

        return 'R'

    if shift == '1':

        return 'B'

    if shift == '2':

        return 'G'

    if shift == '3':

        return 'Y'


# map a color to a shift

df['color'] = df['shift'].apply(assignColor)


fig, ax = plt.subplots(figsize=(15,6))


# plot our Head_Count values

for date in df.report_date.unique():

    d = df[df.report_date == date].sort_values(by='Head_Count', ascending=False)

    y = d.Head_Count.values

    x = date

    color = d.color

    b = plt.bar(x,y, color=color)


# Plot our UTL_R values

ax2 = ax.twinx()    


sns.lineplot(x=df.report_date, y=df.UTL_R, hue=df['shift'], marker='o', legend=None)


# Assign the color label color to our legend

leg = ax.legend(labels=df['shift'].unique(), loc=1)


legend_maping = dict()


for shift in df['shift'].unique():

    legend_maping[shift] = df[df['shift'] == shift].color.unique()[0]


i = 0

for leg_lab in leg.texts:

    leg.legendHandles[i].set_color(legend_maping[leg_lab.get_text()])

    i += 1

http://img1.sycdn.imooc.com//61c814ed0001b32d09090360.jpg

查看完整回答
反對 回復 2021-12-26
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

這個怎么樣?


tm_daily_df['UTL_R'] = tm_daily_df['UTL_R'].str.replace('%', '').astype('float') / 100

pivoted = tm_daily_df.pivot_table(values=['Head_Count', 'UTL_R'], 

                                  index='report_date', 

                                  columns='shift')

pivoted


#             Head_Count             UTL_R

# shift                1   2   3   A     1     2     3     A

# report_date

# 3/17/19             11  27  18  72  0.10  0.13  0.25  0.25

# 3/18/19             23  16  12  71  1.00  0.25  0.50  0.10

# 3/19/19             28  23  14  76  0.10  0.50  0.33  0.20

# 3/20/19             29  29  10  59  0.25  0.25  0.50  0.33

# 3/21/19             17  29  30  65  0.20  0.14  0.17  0.10

# 3/22/19             12  10  17  54  0.14  1.00  0.14  0.20

# 3/23/19             16  11  13  66  0.10  1.00  0.10  0.14


fig, ax = plt.subplots()

pivoted['Head_Count'].plot.bar(ax=ax)

pivoted['UTL_R'].plot.line(ax=ax, legend=False, secondary_y=True, marker='D')

ax.legend(loc='upper left', title='shift')

http://img1.sycdn.imooc.com//61c814fc000137e906320470.jpg

查看完整回答
反對 回復 2021-12-26
  • 2 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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