我從犯罪資料集在 Plotly 中創建了一個折線圖,它的設定大致符合我的需要,但我想將 x 軸刻度標簽從當前的日期和時間(見下文)轉換為一天一周中的。例如,在圖表上,第一個點是 2022/06/25,這是一個星期六。我想讓標簽說只是星期六。我的表還包含一個列,其中包含每個日期的星期幾,但我不知道如何更改日期的那一天。
最壞的情況,我需要對 x 軸上的每個刻度標簽進行硬編碼?
任何輸入表示贊賞。謝謝!
我的代碼:
df = pd.read_csv("test.csv")
df = df[(df['Occurrence_Category'] == 'Non-Violent')]
df = df.groupby(['Reported_Date', 'Day_of_Week'], as_index=False).size()
print(df)
fig = px.line(
df,
x='Reported_Date',
y='size',
labels={'size': 'Number of Occurrences', 'Reported_Date': 'Day of the Week'},
title="Number of Non-Violent Crimes in the last 90 days"
)
fig.update_layout(
xaxis=dict(
tickmode='linear',
tick0=1,
dtick=1
),
yaxis=dict(
tickmode='linear',
tick0=0,
dtick=25
),
)
fig.show()
編輯:這是前 10 行的字典。
data_dict =
{'Reported_Date': {0: '2022/06/25 12:00:00 00', 1: '2022/06/26 12:00:00 00', 2: '2022/06/27 12:00:00 00', 3: '2022/06/28 12:00:00 00', 4: '2022/06/29 12:00:00 00', 5: '2022/06/30 12:00:00 00', 6: '2022/07/01 12:00:00 00', 7: '2022/07/02 12:00:00 00', 8: '2022/07/03 12:00:00 00', 9: '2022/07/04 12:00:00 00'}, 'Day_of_Week': {0: 'Sat', 1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed', 5: 'Thu', 6: 'Fri', 7: 'Sat', 8: 'Sun', 9: 'Mon'}, 'size': {0: 113, 1: 94, 2: 165, 3: 141, 4: 153, 5: 129, 6: 65, 7: 104, 8: 74, 9: 167}}
當我列印 df 時,我得到:

我目前的圖表:

uj5u.com熱心網友回復:
您所要做的就是將 轉換為這樣的Reported_Date型別datetime:
df['Reported_Date'] = df['Reported_Date'].apply(pd.to_datetime)
并指定tickformat以提取作業日,并洗掉其他引數以格式化 x 軸,如下所示:
fig.update_layout(
xaxis=dict(
tickformat = '%a' #<----- this is the format to get weekday
),
yaxis=dict(
tickmode='linear',
tick0=0,
dtick=25
),
)

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519491.html
