带有酒吧的小平面条形图在熊猫中并排放置

时间:2017-06-27 17:52:18

标签: python pandas matplotlib plot facet

这种方法有效,但是有没有更好的方法来制作条形图,并且大熊猫并排放置条形图?我觉得使用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])

enter image description here

1 个答案:

答案 0 :(得分:3)

如果你想多次做一些事情,总是值得考虑使用一个函数和一个循环。在这里,循环就足够了。

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])

Resulting plot