簡體   English   中英

我如何 plot 和 pandas dataframe 並在 x 軸上進行分組?

[英]How can I plot a pandas dataframe and have groupings in the x-axis?

我有一個按月分組的 pandas dataframe,每個月都有一個區域,每個月都有各自的銷售額和利潤金額。

我能夠創建一個圖表(指向該圖形的鏈接在帖子的末尾),但 X 軸顯示每個垂直條的(日期、區域)。 我希望顯示的是讓每個垂直條只標有相應的區域,而不是按月份對 4 個區域中的每一個進行分組。

這可能嗎?

Python代碼:

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

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
...

圖表

如果您只想更改條形的順序,可以更改索引的順序,然后對索引進行排序:

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

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

如果您想要 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()

從那里你可以調整你的子圖標題、軸標簽、添加注釋等,讓它看起來像你想要的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM