为什么我的x轴记号在plotly graph中排序不正确

2024-06-25 07:18:20 发布

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

我正试图在几周内描绘一个销售趋势。但是在x轴上,刻度没有按正确的顺序排列,这使得我的图形看起来很奇怪

图表: enter image description here

正如你所看到的,圆圈周,需要从起点或轴开始。为什么在我对数据框中的日期进行排序之后,仍然会发生这种情况

熊猫代码:

basic_df = filterDataFrameByDate(df,start_date,end_date)
df = basic_df.groupby(['S2PName',basic_df['S2BillDate'].dt.to_period(flag)], sort=False)['S2PGTotal'].agg([('totSale','sum'),('count','size')]).reset_index()
df.sort_values('S2BillDate',inplace=True)
df['S2BillDate'] = df['S2BillDate'].astype('str')

我还注意到,当我从图例中取消选择“Samosa”时,记号排列正确

截图: enter image description here

有谁能帮我解决这个问题吗

熊猫代码和数据:

代码:

 print(df['S2BillDate'].unique())

作品:

    <PeriodArray>
['2020-02-03/2020-02-09', '2020-02-10/2020-02-16', '2020-02-17/2020-02-23',
 '2020-02-24/2020-03-01']
Length: 4, dtype: period[W-SUN]

代码:

   df = basic_df.groupby(['S2PName',basic_df['S2BillDate'].dt.to_period(flag)], sort=False)['S2PGTotal'].agg([('totSale','sum'),('count','size')]).reset_index()

作品:

[537 rows x 4 columns]
                          S2PName             S2BillDate   totSale  count
0                          SAMOSA  2020-02-10/2020-02-16   4057.89    228
1                          COFFEE  2020-02-10/2020-02-16  10567.21    582
2                             TEA  2020-02-10/2020-02-16   6808.92    445
3                           POORI  2020-02-10/2020-02-16   7556.77    179
4                          PONGAL  2020-02-10/2020-02-16   4758.97    122
..                            ...                    ...       ...    ...
411                PEPPER CHICKEN  2020-02-24/2020-03-01     90.00      1
412  SEZWAN CHICKEN FRIED NOODLES  2020-02-24/2020-03-01    199.50      2
413         SEZWAN VEG FRIED RICE  2020-02-24/2020-03-01     69.83      1
414         SEZWAN EGG FRIED RICE  2020-02-24/2020-03-01     89.78      1
415                    EGG MASALA  2020-02-24/2020-03-01     50.04      1

Tags: 数据代码dfdatebasiccountdtsort
1条回答
网友
1楼 · 发布于 2024-06-25 07:18:20

我可以重现你的问题。我正在使用plotly.express,但它与plotly.graph_objs的工作方式相同

资料

import pandas as pd
import plotly.express as px

df = pd.DataFrame({"SPName":["SAMOSA"]*3+ ["COFFEE"]*4,
                   "S2BillDate":["2020-02-10/2020-02-16",
                                 "2020-02-17/2020-02-23",
                                 "2020-02-24/2020-03-01",
                                 "2020-02-24/2020-03-01",
                                 "2020-02-17/2020-02-23",
                                 "2020-02-10/2020-02-16",
                                 "2020-02-03/2020-02-09"],
                    "totSale":[4000, 4500, 5000, 10_000, 12_000, 10_000, 2000]})

这个产品

fig = px.line(df, x="S2BillDate", y="totSale", color="SPName")
fig.update_traces(mode='markers+lines')
fig.show()

enter image description here

这里的问题是如何对日期进行排序。如果您看到COFFEE的第一点是2020-02-24/2020-03-01,那么第二点是2020-02-17/2020-02-23以此类推

一个快速解决方案将是

df1 = df.sort_values("S2BillDate").reset_index(drop=True)

fig = px.line(df1, x="S2BillDate", y="totSale", color="SPName")
fig.update_traces(mode='markers+lines')

enter image description here

我个人更喜欢在xaxis上使用日期而不是字符串

df["Date"] = df["S2BillDate"].str.split("/").str[1].astype("M8")
fig = px.line(df, x="Date", y="totSale", color="SPName")
fig.update_traces(mode='markers+lines')
```[![enter image description here][3]][3]

but in this case in order to show the ticktext in the format you asked for you still need to sort `df` and in this case there you need more coding.

```python
df = df.sort_values(["Date"]).reset_index(drop=True)
fig = px.line(df, x="Date", y="totSale", color="SPName")
fig.update_traces(mode='markers+lines')
fig.update_layout(
    xaxis = dict(
        type="category",
        tickmode = 'array',
        tickvals = df["Date"].tolist(),
        ticktext = df["S2BillDate"].tolist()
    )
)
fig.show()

相关问题 更多 >