Python 日期轴上的绘图类别

Python plot category on a day axis

大家好我有一个日期、类别和数量的数据集,我想在 x-axis 上绘制日期和类别,在 y 轴上绘制数量。这是数据框中每一天的数量与类别图。

import pandas as pd
import numpy as np
import plotly.graph_objects as go

# simulate dataframe shown in question
df = pd.DataFrame(
    index=pd.MultiIndex.from_product(
        [pd.date_range("7-feb-2022", "17-feb-2022"), range(1, 51, 1)],
        names=["Date", "Category"],
    ),
    data=np.random.uniform(1, 25, 550),
    columns=["Quantity"],
).reset_index()

df["Category"] = pd.cut(df["Category"], bins=[0, 10, 20, 30, 40, 50]).astype(str)
df = df.groupby(["Date", "Category"]).sum()

# https://plotly.com/python/categorical-axes/#multicategorical-axes
go.Figure(
    go.Bar(
        x=[
            df.index.get_level_values("Date").strftime("%Y-%m-%d").tolist(),
            df.index.get_level_values("Category").tolist(),
        ],
        y=df["Quantity"],
    )
)