簡體   English   中英

如何使用三列三行的三個數據框創建堆疊的條形圖

[英]how to create a stacked bar with three dataframe with three columns & three rows

我有三個數據df_Male , df_female , Df_TransGender

樣本數據df_Male

continent   avg_count_country   avg_age
  Asia          55                5
  Africa        65                10
  Europe        75                8

df_Female

continent   avg_count_country   avg_age
  Asia          50                7
  Africa        60                12
  Europe        70                0

df_Transgender

continent   avg_count_country   avg_age
  Asia          30                6
  Africa        40                11
  America       80                10

現在,我們堆積的條形圖應該看起來像

X軸將包含三個刻度線,男性,女性,變性者

Y軸將為Total_count--100

並且在酒吧avg_age將被堆疊

現在我正在嘗試像樞軸表

pivot_df = df.pivot(index='new_Columns', columns='avg_age ', values='Values')

越來越困惑如何繪制此圖,任何人都可以幫助將三個數據框合並為一個,以便它創建Male,Female和Transgener列

在此處處理該主題: https ://pandas.pydata.org/pandas-docs/stable/merging.html

(請注意, df_Transgender中的第三大洲與其他數據df_Transgender “ America”而不是“ Europe”不同;我在下圖中更改了它,希望這是正確的。)

frames = [df_Male, df_Female, df_Transgender]
df = pd.concat(frames, keys=['Male', 'Female', 'Transgender'])

              continent  avg_count_country  avg_age
Male        0      Asia                 55        5
            1    Africa                 65       10
            2    Europe                 75        8
Female      0      Asia                 50        7
            1    Africa                 60       12
            2    Europe                 70        0
Transgender 0      Asia                 30        6
            1    Africa                 40       11
            2    Europe                 80       10

btm = [0, 0, 0]
for name, grp in df.groupby('continent', sort=False):
    plt.bar(grp.index.levels[1], grp.avg_age.values, bottom=btm, tick_label=grp.index.levels[0], label=name)
    btm = grp.avg_age.values
plt.legend(ncol = 3)

在此處輸入圖片說明

正如您在下面的評論中所述,第三個數據集中的America沒錯,您可以像上面一樣繼續向每個數據框添加行,就像這樣:

df_Male.append({'avg_age': 0, 'continent': 'America'}, ignore_index=True)
df_Female.append({'avg_age': 0, 'continent': 'America'}, ignore_index=True)
df_Transgender.append({'avg_age': 0, 'continent': 'Europe'}, ignore_index=True)

暫無
暫無

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

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