简体   繁体   English

如何在 Matplotlib 的子图中添加多个条形图

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

I have a Pandas data frame that is dynamic.我有一个动态的 Pandas 数据帧。 and I am trying to place a bar graph in a subplot that will show multiple graphs in a single window.我试图在一个子图中放置一个条形图,它将在单个 window 中显示多个图表。 On the x-axis, there is 'Area' and on the y-axis, there is Area Count.在 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]) 
  • It's not exactly clear what you're attempting, however, given that the data shown is discreet (not continuous), it should be plotted as a bar plot, not a line plot.但是,由于显示的数据是离散的(不连续的),因此尚不清楚您要尝试什么,因此应该将其绘制为条形 plot,而不是一条线 plot。
  • All of the values should be removed from lists by using pandas.Series.explode .应使用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

Plotting绘图

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