【问题标题】:Facet barplot with bars are side-by-side in pandas带有条形的构面条形图在熊猫中并排
【发布时间】:2017-06-27 17:52:18
【问题描述】:

这可行,但没有更好的方法来分面 barplot 与 bar 在 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])

【问题讨论】:

    标签: python pandas matplotlib plot facet


    【解决方案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])
    

    【讨论】:

      猜你喜欢
      • 2017-12-30
      • 2015-06-28
      • 2019-04-13
      • 2017-04-01
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      相关资源
      最近更新 更多