Skip to content

chance_level_kw in RocCurveDisplay raises an error when using valid matplotlib args #30015

Closed
@JosephBARBIERDARNAL

Description

@JosephBARBIERDARNAL

Describe the bug

When passing additional keyword arguments to the random classifier's line via the chance_level_kw argument, some arguments raise an error even though they are valid matplotlib.pyplot.plot() arguments. The error occurs with the c and ls arguments.

The reason is that in scikit-learn/sklearn/metrics/_plot/roc_curve.py, the following code exists:

chance_level_line_kw = {
    "label": "Chance level (AUC = 0.5)",
    "color": "k",
    "linestyle": "--",
}

if chance_level_kw is not None:
    chance_level_line_kw.update(**chance_level_kw)

Matplotlib raises an error when both color and c, or linestyle and ls are specified (this happens with other arguments too, but these are not relevant here since scikit-learn does not set values for them).

This behavior may also occur with other future classes, especially CapCurveDisplay (in development #28972).

A quick fix might look like this:

if 'ls' in chance_level_kw:
    chance_level_kw['linestyle'] = chance_level_kw['ls']
    del chance_level_kw['ls']

if 'c' in chance_level_kw:
    chance_level_kw['color'] = chance_level_kw['c']
    del chance_level_kw['c']

chance_level_line_kw = {
    "label": "Chance level (AUC = 0.5)",
    "color": "k",
    "linestyle": "--",
}

if chance_level_kw is not None:
    chance_level_line_kw.update(**chance_level_kw)

Steps/Code to Reproduce

from sklearn import metrics

display = metrics.RocCurveDisplay.from_predictions(
    y_true=[0, 0, 1, 1],
    y_pred=[0.1, 0.4, 0.35, 0.8],
    plot_chance_level=True,
    chance_level_kw={'ls': '--'}
)

Expected Results

Screenshot 2024-10-06 at 15 18 34

Actual Results

TypeError: Got both 'linestyle' and 'ls', which are aliases of one another

Versions

System:
    python: 3.12.5 (main, Aug  6 2024, 19:08:49) [Clang 15.0.0 (clang-1500.3.9.4)]
executable: /Users/josephbarbier/Desktop/scikit-learn/sklearn-env/bin/python
   machine: macOS-14.6.1-arm64-arm-64bit

Python dependencies:
      sklearn: 1.6.dev0
          pip: 24.2
   setuptools: 69.5.1
        numpy: 2.1.2
        scipy: 1.14.1
       Cython: 3.0.11
       pandas: None
   matplotlib: 3.9.2
       joblib: 1.4.2
threadpoolctl: 3.5.0

Built with OpenMP: True

threadpoolctl info:
       user_api: openmp
   internal_api: openmp
    num_threads: 10
         prefix: libomp
       filepath: /opt/homebrew/Cellar/libomp/18.1.8/lib/libomp.dylib
        version: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions