Skip to content

KeyError in express.scatter plot with facet_col when the data contains nan #3453

Description

@ryotatomioka

Reproducer (modified from the original):

import plotly.express as px

df = px.data.tips()
df["sex"][: len(df) // 2] = None
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", facet_col="sex")
fig.write_html("test.html")

The above produces the following error:

Traceback (most recent call last):
File "plotlyscatter.py", line 5, in
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", facet_col="sex")
File "/opt/envs/myenv/lib/python3.8/site-packages/plotly/express/_chart_types.py", line 66, in scatter
return make_figure(args=locals(), constructor=go.Scatter)
File "/opt/envs/myenv/lib/python3.8/site-packages/plotly/express/_core.py", line 1976, in make_figure
group = grouped.get_group(group_name if len(group_name) > 1 else group_name[0])
File "/opt/envs/myenv/lib/python3.8/site-packages/pandas/core/groupby/groupby.py", line 754, in get_group
raise KeyError(name)
KeyError: ('No', '', '', '', nan)

Environment:

  • plotly==5.3.1
  • pandas==1.3.4

The simplest fix (which discards points with nan values) is to use grouped.indices instead of grouped.groups in this line:

for group_name in grouped.groups:

However it would be useful to allow nan values in grouping using dropna=False in DataFrame.groupby:
https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.groupby.html?highlight=groupby#pandas.DataFrame.groupby

Activity

  1. Tapot commented on Oct 21, 2022

    @Tapot

    Got the same error with plotly 5.5.0, in 5.10.0 it is OK - looks like the problem was fixed

  2. pawel-kotowski commented on Oct 9, 2023

    @pawel-kotowski

    I think I have similar issue in plotly 5.10.0 and 5.17.0 when there is no data in one of facet_row or facet_col cols when col is pd.Categorical. Works if I convert it to str type.

  3. self-assigned this
    on Jul 11, 2024
  4. removed their assignment
    on Aug 2, 2024
  5. emilykl commented on Aug 30, 2026

    @emilykl
    Contributor

    This issue is resolved starting with plotly.py v5.9.0. Most likely it was resolved by #3765.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3backlogbugsomething broken

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions