簡體   English   中英

seaborn barplot 中條形的升序

[英]Ascending order of bars in seaborn barplot

我有以下數據框

   Class    Age Percentage
0   2004    3   43.491170
1   2004    2   29.616607
2   2004    4   13.838925
3   2004    6   10.049712
4   2004    5   2.637445
5   2004    1   0.366142
6   2005    2   51.267369
7   2005    3   19.589268
8   2005    6   13.730432
9   2005    4   11.155305
10  2005    5   3.343524
11  2005    1   0.913590
12  2005    9   0.000511

我想使用 seaborn 繪制條形圖,其中 y 軸是“百分比”,x 軸是“類別”,並使用“年齡”列標記它們。 我還想按降序排列條形,即從較大的條形到較小的條形。

為了做到這一點,我想到了以下幾點:我將根據“百分比”變量的順序更改hue_order參數。 例如,如果我按降序對Class == 2004的 'Percentage' 列進行排序,則hue_order = [3, 2, 4, 6, 5, 1]

這是我的代碼:

import matplotlib.pyplot as plt
import seaborn as sns

def hue_order():
    for cls in dataset.Class.unique():
        temp_df = dataset[dataset['Class'] == cls]
        order = temp_df.sort_values('Percentage', ascending = False)['Age']  
    return order

sns.barplot(x="Class", y="Percentage", hue = 'Age', 
                 hue_order= hue_order(),  
                 data=dataset)
plt.show()

但是,條形僅針對Class == 2005以降序排列。 有什么幫助嗎?

在我的問題中,我使用的是hue參數,因此,它不是建議的重復項。

結果

seaborn hue參數為繪圖添加了另一個維度。 hue_order確定處理此維度的順序。 但是,您不能拆分該訂單。 這意味着您很可能會更改順序,使Age == 2位於圖中的第三位。 但是你不能部分地改變它,例如在某些部分它在第一,而在其他一些它會在第三位。

為了實現這里的期望,即在同一軸內使用不同順序的輔助尺寸,您需要手動處理。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({"Class" : [2004]*6+[2005]*7,
                   "Age" : [3,2,4,6,5,1,2,3,6,4,5,1,9],
                   "Percentage" : [50,40,30,20,10,30,20,35,40,50,45,30,15]})

def sortedgroupedbar(ax, x,y, groupby, data=None, width=0.8, **kwargs):
    order = np.zeros(len(data))
    df = data.copy()
    for xi in np.unique(df[x].values):
        group = data[df[x] == xi]
        a = group[y].values
        b = sorted(np.arange(len(a)),key=lambda x:a[x],reverse=True)
        c = sorted(np.arange(len(a)),key=lambda x:b[x])
        order[data[x] == xi] = c   
    df["order"] = order
    u, df["ind"] = np.unique(df[x].values, return_inverse=True)
    step = width/len(np.unique(df[groupby].values))
    for xi,grp in df.groupby(groupby):
        ax.bar(grp["ind"]-width/2.+grp["order"]*step+step/2.,
               grp[y],width=step, label=xi, **kwargs)
    ax.legend(title=groupby)
    ax.set_xticks(np.arange(len(u)))
    ax.set_xticklabels(u)
    ax.set_xlabel(x)
    ax.set_ylabel(y)


fig, ax = plt.subplots()    
sortedgroupedbar(ax, x="Class",y="Percentage", groupby="Age", data=df)
plt.show()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM