首页 > 解决方案 > Pandas:条形图,数据框中重复的 x 列中有两个条形图

问题描述

我有一个稍微奇怪的 csv 文件,其中月份列如此重复。我的目标是创建一个条形图,其中每个月都有两列 y(来自 a 和 b)。我试图通过将数据框分成两部分来解决这个问题 - 仅 a 和仅 b - 但是月份列的重复会妨碍。对 Python 和 Pandas 来说相当新,所以也许有一个我不知道的功能?任何帮助表示赞赏。

month   cond. y   

Jan     a     4    
Jan     b     8     
Feb     a     2     
Feb     b     9       
March   a     3   
March   b     7   

标签: pythonpandasmatplotlibplot

解决方案


解决此问题的最常见方法可能是将长格式数据通过pivot然后重塑为宽格式DataFrame.plot

import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame({
    'month': ['Jan', 'Jan', 'Feb', 'Feb', 'March', 'March'],
    'cond.': ['a', 'b', 'a', 'b', 'a', 'b'],
    'y': [4, 8, 2, 9, 3, 7]
})

df.pivot(index='month', columns='cond.', values='y').plot(kind='bar', rot=0)
plt.tight_layout()
plt.show()

情节 1


有一个明显的问题是 x 轴列出现乱序,因为它们是按字母顺序排列的,而不是按日期排序的。一种选择是reindex在绘图之前。如果月份列是常规的,将会有更多选项,但由于它包含完整的月份名称和缩写,因此手动重新索引可能是最好的选择。

import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame({
    'month': ['Jan', 'Jan', 'Feb', 'Feb', 'March', 'March'],
    'cond.': ['a', 'b', 'a', 'b', 'a', 'b'],
    'y': [4, 8, 2, 9, 3, 7]
})

(
    df.pivot(index='month', columns='cond.', values='y')
        .reindex(['Jan', 'Feb', 'March'])  # Re-order so they appear correctly on x-axis
        .plot(kind='bar', rot=0)
)
plt.tight_layout()
plt.show()

情节 2 重新索引


Seaborn在解决这些类型的问题方面非常受欢迎,因为该hue论点允许避免重塑步骤。此外x将按照帧中出现的顺序,因此reindex也是不必要的(假设数据在源 DataFrame 中以正确的顺序出现)

sns.barplot

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

sns.set_theme()  # (optional) Use seaborn theme
df = pd.DataFrame({
    'month': ['Jan', 'Jan', 'Feb', 'Feb', 'March', 'March'],
    'cond.': ['a', 'b', 'a', 'b', 'a', 'b'],
    'y': [4, 8, 2, 9, 3, 7]
})

sns.barplot(data=df, x='month', y='y', hue='cond.')
plt.tight_layout()
plt.show()

情节3海生


推荐阅读