我有一个 Pandas 数据框,它是通过 MySQL.Connector 从 SQL 输出中获得的,如下所示:
Group Sales Period
0 0 136471.06 2015-1
1 0 645949.37 2015-2
2 0 1414552.66 2015-3
3 0 684672.48 2015-4
4 0 71529.99 2016-1
... ... ... ...
303 119 18641.06 2018-1
304 119 18514.82 2018-2
305 119 16042.67 2018-3
306 119 15043.29 2019-3
307 119 0.00 2020-2
客户属于特定组。我从这些组中获得了季度(期间)销售报告。
如何管理在折线图中绘制每个时期每个组的发展?到目前为止,我只是像这样手动管理它:
plt.rcParams["figure.figsize"] = (20,10)
group_0 = df_4[df_4.Group == 0]
group_100 = df_4[df_4.Group == 100]
group_101 = df_4[df_4.Group == 101]
plt.plot(group_0.Period, group_0.Sales)
plt.plot(group_100.Period, group_100.Sales)
plt.plot(group_101.Period, group_101.Sales)
plt.legend(['0', '100', '101'])
plt.title("Sales per Group per Quarter")
plt.xlabel("Quarter")
plt.ylabel("Sales in Million")
plt.show()
这给了我需要的输出,但我认为必须有更好的方法。绘制整个数据框的其他尝试只是给了我非常奇怪的绘图结果。所附图片是手动尝试,效果不错,但效率低下。所以基本上我正在寻找一种解决方案,试图更有效地完成这项工作。欢迎任何帮助
答案 0 :(得分:2)
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
# Generate some sample data
np.random.seed(5)
gs = 4
ng = 3
df = pd.DataFrame({
'Group': np.concatenate([np.full(gs, i) for i in range(ng)]),
'Sales': np.random.random(gs * ng) * 1_000_000,
'Period': pd.to_datetime(
np.tile(pd.date_range('2015-01', freq='Q', periods=gs).to_numpy(), ng)
)
})
fig, ax = plt.subplots()
for label, group in df.groupby('Group'):
group.plot(kind='line', x='Period', y='Sales', ax=ax, label=label)
plt.title("Sales per Group per Quarter")
plt.xlabel("Quarter")
plt.ylabel("Sales in Million")
plt.tight_layout()
plt.show()
示例df
:
Group Sales Period
0 0 221993.171090 2015-03-31
1 0 870732.306177 2015-06-30
2 0 206719.155339 2015-09-30
3 0 918610.907938 2015-12-31
4 1 488411.188795 2015-03-31
5 1 611743.862903 2015-06-30
6 1 765907.856480 2015-09-30
7 1 518417.987873 2015-12-31
8 2 296800.501576 2015-03-31
9 2 187721.228661 2015-06-30
10 2 80741.268765 2015-09-30
11 2 738440.296199 2015-12-31
示例图: