簡體   English   中英

如何在 Matplotlib 的子圖中添加多個條形圖

[英]How to add multiple bar graph in subplot in Matplotlib

我有一個動態的 Pandas 數據幀。 我試圖在一個子圖中放置一個條形圖,它將在單個 window 中顯示多個圖表。 在 x 軸上,有“面積”,在 y 軸上,有面積計數。

   Names                 Area         Area Count
0  Info 1        [LOCATION, PERSON]   [130, 346]
1  Info 2              [NRP]          [20]
rows = len(df1['Names']) 
fig, ax = plt.subplots(nrows=rows, ncols=1) 
df1['Area'].plot(ax=ax[0,0])
df1['Area Count'].plot(ax=ax[0,1]) 
  • 但是,由於顯示的數據是離散的(不連續的),因此尚不清楚您要嘗試什么,因此應該將其繪制為條形 plot,而不是一條線 plot。
  • 應使用pandas.Series.explode從列表中刪除所有值。
import pandas as pd
import seaborn as sns

# test dataframe
data = {'Names': ['Info 1', 'Info 2'], 'Area': [['LOCATION', 'PERSON'], ['NRP']], 'Area Count': [[130, 346], [20]]}
df = pd.DataFrame(data)

# display(df)
    Names                Area  Area Count
0  Info 1  [LOCATION, PERSON]  [130, 346]
1  Info 2               [NRP]        [20]

# explode the lists
df = df.set_index('Names').apply(pd.Series.explode).reset_index()

# display(df)
    Names      Area Area Count
0  Info 1  LOCATION        130
1  Info 1    PERSON        346
2  Info 2       NRP         20

繪圖

df.plot.bar(x='Area', y='Area Count')

在此處輸入圖像描述

sns.barplot(data=df, x='Area', y='Area Count', hue='Names', dodge=False)

在此處輸入圖像描述

df.pivot(index='Area', columns='Names', values='Area Count').plot.bar()

在此處輸入圖像描述

df.pivot(index='Names', columns='Area', values='Area Count').plot.bar()

在此處輸入圖像描述

sns.catplot(data=df, col='Names', x='Area', y='Area Count', kind='bar', estimator=sum)

在此處輸入圖像描述

rows = len(df.Names.unique())
fig, ax = plt.subplots(nrows=rows, ncols=1, figsize=(6, 8))
for i, v in enumerate(df.Names.unique()):
    data = df[df.Names == v]
    data.plot.bar(x='Area', y='Area Count', title=v, ax=ax[i], legend=False)
plt.tight_layout()
plt.show()

在此處輸入圖像描述

暫無
暫無

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

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