pivot / groupby表中的堆叠条形图Python

问题描述 投票:2回答:1

这是示例数据。如何获得Y轴上的总金额和堆叠的四分之一,X轴上的区域和年份。

Region Year   Quarter  Sum Amount
 A     2016     1       100
                2       80
                3       70
                4       10
       2017     1       90
                2       50
                3       60
                4       30
B      2016     1       120
                2       80
                3       90
                4       20
       2017     2       80
                3       100
python pandas graph bar-chart visualization
1个回答
0
投票
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random

# data
random.seed(365)
data = {'Year': [random.choice([2016, 2017]) for _ in range(1000)],
        'Region': [random.choice(['A', 'B']) for _ in range(1000)],
        'Quarter': [random.choice([1, 2, 3, 4]) for _ in range(1000)],
        'Value': [np.random.randint(10) for _ in range(1000)]}

# dataframe
df = pd.DataFrame(data)

# groupby
gb = df.groupby(['Region', 'Year', 'Quarter'])['Value'].sum().unstack()

# plot
gb.plot.bar(stacked=True)
plt.legend(title='Quarter', loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.