Skip to content

sns.pointplot breaks when dodge=True and dataset has a single hue level #3825

Open
@cdpaiva

Description

@cdpaiva

Hi! The following code breaks:

import seaborn as sns
import matplotlib.pyplot as plt


def create_point_plot():
    df = sns.load_dataset("anscombe")
    # simulate a dataset with n_hue_levels == 1
    df = df[df["dataset"] == "I"]

    sns.pointplot(data=df, x="x", y="y", hue="dataset", dodge=True)
    plt.show()


create_point_plot()

This is the error message:

Traceback (most recent call last):
  File "/home/cdp58/Documents/repos/pasna_analysis/pasna_analysis/seaborn_zeroIndex.py", line 14, in <module>
    create_point_plot()
  File "/home/cdp58/Documents/repos/pasna_analysis/pasna_analysis/seaborn_zeroIndex.py", line 10, in create_point_plot
    sns.pointplot(data=df, x="x", y="y", hue="dataset", dodge=True)
  File "/home/cdp58/miniconda3/envs/pscope_analysis/lib/python3.11/site-packages/seaborn/categorical.py", line 2516, in pointplot
    p.plot_points(
  File "/home/cdp58/miniconda3/envs/pscope_analysis/lib/python3.11/site-packages/seaborn/categorical.py", line 1218, in plot_points
    step_size = dodge / (n_hue_levels - 1)
                ~~~~~~^~~~~~~~~~~~~~~~~~~~
ZeroDivisionError: float division by zero

While it does not make strict sense to have dodge=True and a single categorical variable, it would be nice to be able to handle this case. At least this happens sometimes with the datasets I have... I usually have multiple groups, but sometimes only a single group. I understand this could be handled on my end.

I believe flipping dodge to False inside plot_points if n_hue_levels <= 1 would be enough.

I ran this using seaborn=0.13.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions