如何在xaxis中绘制Pandas数据帧和分组?

2024-10-03 02:32:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个按月份分组的pandas数据框,每个月都有一个地区,有各自的销售额和利润额

我可以创建一个图表(链接到图片在文章的末尾),但是X轴显示每个垂直条的(日期,区域)。我希望显示的是,每个垂直条只标记相应的区域,而不是按月份将4个区域中的每个区域分组

这可能吗

Python代码:

fig, ax = plt.subplots(figsize=(17, 6))
result.plot(kind='bar', ax=ax)
plt.show()

数据帧内容

                           Profit       Sales
Order Date Region
2015-01-31 Central  -602.8452   2510.5116
           East    -1633.3880   4670.9940
           South   -1645.0817   4965.8340
           West      600.3079   6026.7360
2015-02-28 Central   330.9740   2527.5860
           East     1806.5875   6463.1330
           South     222.5703   1156.5140
           West      453.7190   1804.1780
2015-03-31 Central    51.4141   6730.2680
           East     1474.0029   6011.7410
           South    3982.8631  10322.0950
           West     4223.8177  15662.1480
2015-04-30 Central   992.0608  11642.0550
           East     1095.2726   7778.7960
           South     767.3671   5718.3335
           West     1332.7957   9056.0240
2015-05-31 Central   963.9297   8623.9030
           East     1633.5375   7481.4240
           South     429.2514   1983.7040
           West     1641.1504  12042.6555
...

Chart


Tags: 数据区域pandas链接图表pltax地区
1条回答
网友
1楼 · 发布于 2024-10-03 02:32:03

如果只想更改条的顺序,可以更改索引的顺序,然后对索引进行排序:

result = result.reorder_levels(['Region', 'Order Date']).sort_index()

fig, ax = plt.subplots(figsize=(17, 6))
result.plot(kind='bar')
plt.show()

如果需要4个单独的绘图,可以尝试创建4个子绘图,并将每个区域的过滤数据集映射到每个子绘图轴:

# reorder levels for easier index slicing
result = result.reorder_levels(['Region', 'Order Date']).sort_index()

fig, axes = plt.subplots(1, 4, figsize=(17, 6))
result.iloc['Central'].plot.bar(ax = axes[0])
result.iloc['East'].plot.bar(ax = axes[1])
result.iloc['South'].plot.bar(ax = axes[2])
result.iloc['West'].plot.bar(ax = axes[3])
plt.show()

从那里你可以调整你的子图标题,轴标签,添加注释等,让它看起来像你想要的

相关问题 更多 >