[英]How can I plot a pandas dataframe and have groupings in the x-axis?
I have a pandas dataframe that is grouped by Month, and with each month is a Region with their respective Sales and Profit amounts.我有一个按月分组的 pandas dataframe,每个月都有一个区域,每个月都有各自的销售额和利润金额。
I'm able to create a chart (link to the graphic is at the end of the post) but the X-axis displays the (Date, Region) for each vertical bar.我能够创建一个图表(指向该图形的链接在帖子的末尾),但 X 轴显示每个垂直条的(日期、区域)。 What I'm looking to display is to have each vertical bar labeled with only the respective Region, than group each of the 4 regions by the Month.
我希望显示的是让每个垂直条只标有相应的区域,而不是按月份对 4 个区域中的每一个进行分组。
Is this possible?这可能吗?
Python code: Python代码:
fig, ax = plt.subplots(figsize=(17, 6))
result.plot(kind='bar', ax=ax)
plt.show()
Pandas Dataframe contents Pandas Dataframe 内容
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
...
If you want to simply change the ordering of the bars, you can change the order of your index and then sort the index:如果您只想更改条形的顺序,可以更改索引的顺序,然后对索引进行排序:
result = result.reorder_levels(['Region', 'Order Date']).sort_index()
fig, ax = plt.subplots(figsize=(17, 6))
result.plot(kind='bar')
plt.show()
If you want 4 separate plots, you can try create 4 subplots and map a filtered dataset for each region to each of the subplot axes:如果您想要 4 个单独的图,您可以尝试创建 4 个子图和 map 为每个区域到每个子图轴的过滤数据集:
# 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.loc['Central'].plot.bar(ax = axes[0])
result.loc['East'].plot.bar(ax = axes[1])
result.loc['South'].plot.bar(ax = axes[2])
result.loc['West'].plot.bar(ax = axes[3])
plt.show()
From there you can tweak your subplot titles, axis labels, add annotation, etc. to get it to look the way you want.从那里你可以调整你的子图标题、轴标签、添加注释等,让它看起来像你想要的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.