簡體   English   中英

帶條的小平面條形圖在熊貓中並排顯示

[英]Facet barplot with bars are side-by-side in pandas

這行得通,但是沒有更好的方法來使小平面圖與熊貓在熊貓中並排嗎? 我覺得可能有一種使用multiindex和subplots參數寫的干凈方法?

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'group': ['A', 'A', 'B', 'B'], 
                   'name': ['name1', 'name2', 'name3', 'name4'], 
                   '2016': [1, 2, 3, 4], 
                   '2017': [1.2, 2.1, 3.0, 4.9]})    
df.set_index(['name'], inplace=True)

fig, ax = plt.subplots(2)

group_a = df[df.group == 'A']
group_b = df[df.group == 'B']
group_a.plot(kind='bar', rot=0, ax=ax[0])
group_b.plot(kind='bar', rot=0, ax=ax[1])

在此處輸入圖片說明

如果您想做不止一次,那么總是值得考慮使用函數和循環。 在這里,一個循環就足夠了。

groups = df.group.unique()

fig, ax = plt.subplots(len(groups))

for i, group in enumerate(groups):
    df[df.group == group].plot(kind='bar', rot=0, ax=ax[i])

結果圖

暫無
暫無

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

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