pola-rs/polars · error

cannot use `plot.kde` when Series name is `'density'`

Error message

cannot use `plot.kde` when Series name is `'density'`

What it means

Raised by Series.plot.kde (py-polars/src/polars/series/plotting.py:114) when the Series is named 'density'. The KDE chart calls Altair's transform_density(..., as_=[name, "density"]), which creates a derived column named 'density' for the y axis; a Series already named 'density' would collide with that derived field, so polars raises ValueError before building the chart.

Source

Thrown at py-polars/src/polars/series/plotting.py:114

        .. versionchanged:: 1.6.0
            In prior versions of Polars, HvPlot was the plotting backend. If you would
            like to restore the previous plotting functionality, all you need to do
            is add `import hvplot.polars` at the top of your script and replace
            `df.plot` with `df.hvplot`.

        Parameters
        ----------
        **kwargs
            Additional keyword arguments passed to Altair.

        Examples
        --------
        >>> s = pl.Series("price", [1, 3, 3, 3, 5, 2, 6, 5, 5, 5, 7])
        >>> s.plot.kde()  # doctest: +SKIP
        """  # noqa: W505
        if self._series_name == "density":
            msg = "cannot use `plot.kde` when Series name is `'density'`"
            raise ValueError(msg)
        encodings: Encodings = {"x": self._series_name, "y": "density:Q"}
        return (
            alt.Chart(self._df)
            .transform_density(self._series_name, as_=[self._series_name, "density"])
            .mark_area(tooltip=True)
            .encode(**encodings, **kwargs)
            .interactive()
        )

    def line(
        self,
        /,
        **kwargs: Unpack[EncodeKwds],
    ) -> alt.Chart:
        """
        Draw line plot.

        Polars does not implement plotting logic itself but instead defers to

View on GitHub (pinned to df599052da)

Solutions

  1. Rename before plotting: s.rename("value").plot.kde()
  2. Rename the column upstream in the DataFrame: df.rename({"density": "density_est"})["density_est"].plot.kde()
  3. Standardize ingestion to avoid reserved-ish chart field names if you plot often

Example fix

# before
s = pl.Series("density", [1.0, 2.2, 3.1])
s.plot.kde()  # ValueError

# after
s.rename("value").plot.kde()
Defensive patterns

Strategy: validation

Validate before calling

s_safe = s.rename("value") if s.name == "density" else s
s_safe.plot.kde()

Try / catch

try:
    chart = s.plot.kde()
except ValueError as e:
    if "'density'" in str(e):
        chart = s.rename("value").plot.kde()
    else:
        raise

Prevention

When it happens

Trigger: pl.Series("density", [...]).plot.kde(), or any KDE plot on a column literally named 'density' — typically the output of a previous density estimation or a stats table.

Common situations: Plotting kernel-density results stored in a 'density' column, or ingested datasets that already use 'density' as a field name. Pure name-collision guard; the data itself is fine.

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/9b5cd8517ac6d913. Report an issue: GitHub.