如何在 Plotly 中绘制具有序数级别的时间序列 Python

How to plot a time series with ordinal levels in Plotly Python

我有时间序列数据记录在离散的序数级别(例如 012),我想用有意义的名称绘制它们(例如 low, medium, high).

目前我有:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({
    "x": ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04"],
    "y": [2, 1, 2, 0],
})

fig = px.line(x=df.x, y=df.y, line_shape="hv")
fig.show()

产生:

但我想要这样的东西:

这感觉是最简单的方法:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({
    "x": ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04"],
    "y": [2, 1, 2, 0],
})

fig = px.line(x=df.x, y=df.y, line_shape="hv")
fig.update_yaxes(
    ticktext=["Low", "Medium", "High"],
    tickvals=[0, 1, 2],
)

fig.show()

结果:


在 Plotly 语言中,这属于“分类”范畴。

如果顺序需要调整,categoryarraycategoryorder也可以设置为update_yaxes