Sorted categories (Pandas `Categorical` series) aren't sorted in chart
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 18.8k
- Forks
- 2.8k
- Avg merge
- 16h 26m
- Merged PRs (30d)
- 21
Description
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?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the issue with the provided pandas DataFrame and px.scatter(df, x="Rating", y="Cost") entry point, then trace how categorical axis values are handled. Confirm that ordered categories determine the axis order and add regression coverage; done means the chart follows Low, Medium, High rather than data order.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- pandas, python
- Domain
- data-visualization
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100