Skip to content

fix(stat_density): use the standard deviation when nrd0 sees a zero IQR - #1149

Open
nk-batman21 wants to merge 1 commit into
has2k1:mainfrom
nk-batman21:fix/nrd0-zero-iqr-fallback
Open

nk-batman21 wants to merge 1 commit into
has2k1:mainfrom
nk-batman21:fix/nrd0-zero-iqr-fallback

Conversation

@nk-batman21

Copy link
Copy Markdown

When the IQR of a group is 0, nrd0 (the default bw of geom_density, geom_violin, geom_sina and geom_beeswarm) falls back to IQR/1.349, which is 0 at that point, and then to abs(x[0]) or 1. So the bandwidth ignores the spread of the data and depends on which row comes first. This happens whenever the middle half of a group is a single value, e.g. zero-inflated data such as daily rainfall, or ratings where one answer dominates.

import pandas as pd
from plotnine import aes, geom_density, ggplot

x = [0, 0, 0, 0, 0, 0, 0, 0, 5, 10]
df = pd.DataFrame({"g": ["a"] * 10 + ["b"] * 10, "y": x + x[::-1]})
d = (ggplot(df, aes("y", color="g")) + geom_density()).build().layers[0].data
d.groupby("group")["density"].max()
# before: 0.562 and 0.0629 for the same values
# after:  0.1672 and 0.1672

R's bw.nrd0 uses the standard deviation in this case:

hi <- sd(x)
if(!(lo <- min(hi, IQR(x)/1.34)))
    (lo <- hi) || (lo <- abs(x[1L])) || (lo <- 1.)

For these values that gives 1.9164; plotnine gave 0.5679, or 5.6786 with the rows reversed. This change uses std instead of std_estimate in the fallback, so it matches R. When all the values are equal the result is unchanged. The fallback was added for #317.

Ran: pytest tests/test_geom_density.py tests/test_geom_violin.py tests/test_geom_sina.py tests/test_geom_beeswarm.py tests/test_stat_calculate_methods.py on Python 3.14 and 3.11 (lowest-direct)
Ran: ruff check ., ruff format --check ., pyright

R's bw.nrd0 falls back to the standard deviation when the IQR is 0.
nrd0 fell back to IQR/1.349, which is always 0 at that point, so the
bandwidth came from the first value, or 1. The same values in another
row order then gave a different density, violin, sina or beeswarm.
@codecov

codecov Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.92%. Comparing base (2431ef4) to head (7103c0f).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1149   +/-   ##
=======================================
  Coverage   88.92%   88.92%           
=======================================
  Files         229      229           
  Lines       17320    17320           
  Branches     2204     2204           
=======================================
  Hits        15402    15402           
  Misses       1289     1289           
  Partials      629      629           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant