簡體   English   中英

在 x 軸上創建帶有年份月份的 pandas dataframe 的方面 plot

[英]Create facet plot of pandas dataframe with month of year on x-axis

我有一個數據系列,由各個會計年度的月銷售額組成。 我正在使用pandas dataframe 來存儲數據。 每個會計年度從三月的第一天開始,到次年二月的最后一天結束。 我使用plotly刻面 plot 來顯示一年中的月份垂直對齊,因此 2021 年 3 月低於 2020 年 3 月,依此類推。

盡管對 x 軸使用分類變量,但排序略有偏差。 我嘗試使用具有唯一值的“yearmon”變量進行排序,但這也不起作用。 具體來說,在 plot 中,2018 年 1 月和 2 月的值以下為空白,2021 年 1 月和 2 月的值也不合適。 我怎樣才能在沒有這些問題的情況下獲得顯示連續數據的方面? 編輯:我覺得它與類別的順序有關,但還沒有設法確定它。

使用 plotly 和 pandas 數據框的分面圖

import pandas as pd
import numpy as np
import plotly.express as px
import chart_studio.plotly as py

rng = np.random.default_rng(12345)
df = pd.DataFrame(rng.integers(80, 100, size=(36, 1)), columns=list('A'))
df.index = pd.date_range("2018-03-01", periods=36, freq="M")
df['year'] = df.index.strftime('%Y')
df['month'] = df.index.strftime('%b')
df['monthindex'] = df.index.strftime('%m')
df['yearmon'] = df['year']+df['monthindex']

month_categories = ['Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb']
df["month"] = pd.Categorical(df["month"], categories = month_categories)
df = df.sort_values(by = "yearmon")

fig = px.bar(df, x = 'month', y = 'A', facet_col='year', facet_col_wrap=1)
py.image.save_as(fig, 'plotly.png', width=1000, height=500)

更新

使用下面@vestland 的代碼作為基礎,我根據下面的評論調整了開始日期和財政年度分配,因為財政年度通常與日歷年不一致。 此外,數據系列的長度是任意的——可能是幾個月,也可能是十年——開始和結束月份也是如此。 最后,我希望 x 軸以財政年度的第一個月和最后幾個月開始和結束,所以在這種情況下(三月和二月)“三月”應該是左邊的第一個刻度線,“二月”右邊的最后一個。 如果這不夠清楚,我深表歉意。

import pandas as pd
import numpy as np
import plotly.express as px
import chart_studio.plotly as py

rng = np.random.default_rng(12345)
df = pd.DataFrame(rng.integers(80, 100, size=(36, 1)), columns=list('A'))
df.index = pd.date_range("2018-01-01", periods=36, freq="M")
df['year'] = df.index.strftime('%Y')
df['month'] = df.index.strftime('%b')
df['monthindex'] = df.index.strftime('%m')
df['yearmon'] = df['year']+df['monthindex']

month_categories = ['Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb']
df["month"] = pd.Categorical(df["month"], categories = month_categories)
df = df.sort_values(by = "yearmon")

df['fiscal_year'] = [2017]*2+[2018]*12+[2019]*12+[2020]*10
fig = px.bar(df, x = 'month', y = 'A', facet_col='fiscal_year', facet_col_wrap=1)
fig.show()

這似乎給出了以下信息: 使用非日歷會計年度繪圖

如果我理解正確,那么除了一個小細節之外,您似乎做的一切都是正確的。 這有點令人驚訝,所以我很可能誤解了你的問題的前提。 反正...

具體來說,在 plot 中,2018 年 1 月和 2 月的值以下為空白

那是因為df.head()中不存在這樣的日期

             A  year month monthindex yearmon
2018-03-31  93  2018   Mar         03  201803
2018-04-30  84  2018   Apr         04  201804
2018-05-31  95  2018   May         05  201805
2018-06-30  86  2018   Jun         06  201806
2018-07-31  84  2018   Jul         07  201807

如果我正確理解您的意圖,您實際上希望將january and february of 2019與第一個 x 軸相關聯。 盡管您付出了極大的努力,但還沒有建立這樣的關聯。 我不太確定你會怎么做,但如果你確保設置這樣的東西:

df['fiscal_year'] = [2018]*12+[2019]*12+[2020]*12

並得到:

在此處輸入圖像描述

然后你可以運行

fig = px.bar(df, x = 'month', y = 'A', facet_col='fiscal_year',facet_col_wrap=1)

並得到:

在此處輸入圖像描述

如您所見, January and february of 2019現在出現在 2018 年的 x 軸上。對於這些年的 rest,依此類推。 我希望這就是你要找的。 如果沒有,請隨時告訴我。

完整代碼:

import pandas as pd
import numpy as np
import plotly.express as px
import chart_studio.plotly as py

rng = np.random.default_rng(12345)
df = pd.DataFrame(rng.integers(80, 100, size=(36, 1)), columns=list('A'))
df.index = pd.date_range("2018-03-01", periods=36, freq="M")
df['year'] = df.index.strftime('%Y')
df['month'] = df.index.strftime('%b')
df['monthindex'] = df.index.strftime('%m')
df['yearmon'] = df['year']+df['monthindex']

month_categories = ['Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb']
df["month"] = pd.Categorical(df["month"], categories = month_categories)
df = df.sort_values(by = "yearmon")

df['fiscal_year'] = [2018]*12+[2019]*12+[2020]*12
fig = px.bar(df, x = 'month', y = 'A', facet_col='fiscal_year', facet_col_wrap=1)
fig.show()

在這種情況下,問題似乎是 plotly 不遵守用於 x 軸的 pandas 數據系列中的類別順序,除非特別指示這樣做,如 plotly 論壇中所指出的 此處記錄。 px.bar調用中使用category_orders允許我們覆蓋默認的 plotly 假設並創建一個從指定財政年度的第一個月到財政年度最后一個月的 x 軸。

import pandas as pd
import numpy as np
import plotly.express as px
import chart_studio.plotly as py

rng = np.random.default_rng(12345)
df = pd.DataFrame(rng.integers(80, 100, size=(36, 1)), columns=list('A'))
df.index = pd.date_range("2018-01-01", periods=36, freq="M")
df['year'] = df.index.strftime('%Y')
df['month'] = df.index.strftime('%b')
df['monthindex'] = df.index.strftime('%m')
df['yearmon'] = df['year']+df['monthindex']

month_categories = ['Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb']
df["month"] = pd.Categorical(df["month"], categories = month_categories)
df = df.sort_values(by = "yearmon")

df['fiscal_year'] = [2017]*2+[2018]*12+[2019]*12+[2020]*10

fig = px.bar(df, x = 'month', y = 'A', 
              facet_col='fiscal_year',
              facet_col_wrap=1,
              category_orders={ # replaces default order by column name
                "month": ['Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb']
            })       
fig.show() 

使用有序類別的 pandas 數據框的多面圖

暫無
暫無

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

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