plotly / plotly/plotly.py

Sorted categories (Pandas `Categorical` series) aren't sorted in chart

未关闭
#3,802 1 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

bug P3
主要语言
Python
星标
18.8k
派生
2.8k
平均合并
16 小时 26 分钟
30 天内合并 PR
21

描述

I am plotting a chart with a pd.Categorical series on the x-axis. The category has a sort defined.

Expected behaviour: the axis is sorted as per the underlying category definition
Actual behaviour: the axis is sorted by the order of the data

df = pd.DataFrame(
    dict(
        Cost=[10, 20, 15, 2, 9],
        Rating=pd.Categorical(
            values=["High", "Low", "Medium", "Low", "Medium"],
            categories=["Low", "Medium", "High"],
            ordered=True,
        ),
    )
)

fig = px.scatter(df, x="Rating", y="Cost")

This fix would be fairly simple, I think, something like this, where series is whatever's being rendered to the xaxis (or y, or legend, etc)

if isinstance(series.dtype, pd.CategoricalDtype) and series.cat.ordered:
    fig.update_xaxes(
        categoryorder="array",
        categoryarray=series.cat.categories,
    )

Plotly version: 5.9.0.

I've noticed a number of bugs relating to pd.Categorical and pd.PeriodIndex, are there plans for better Pandas support, or is that not an area of focus?

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

使用提供的 pandas DataFrame 和 px.scatter(df, x="Rating", y="Cost") 入口点重现该问题,然后跟踪分类轴值的处理方式。确认有序类别决定轴的顺序,并添加回归覆盖;完成的标准是图表遵循 LowMediumHigh,而不是数据顺序。

由索引模型根据 Issue 内容生成。

评估

技术栈
pandas, python
领域
data-visualization
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
42/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。