Skip to content

[Bug]: manual positioning fails for ax.clabel #31702

@Hen42rik

Description

@Hen42rik

Bug summary

When adding the label position with the manual keyword, an IndexError is raised when using fewer levels than available in the contour.

Code for reproduction

# create random data
from matplotlib import pyplot as plt
import numpy as np
fig, ax = plt.subplots()
len_data = 10000
xs = np.random.normal(0, 1, len_data)
ys = np.random.normal(0, 1, len_data)
hist, x_edges, y_edges = np.histogram2d(xs, ys, bins=20)
Xc = 0.5 * (x_edges[:-1] + x_edges[1:])
Yc = 0.5 * (y_edges[:-1] + y_edges[1:])
flat = hist.flatten()
order = np.argsort(flat)[::-1]
cumsum = np.cumsum(flat[order])
cumsum/=cumsum[-1]

# compute contour levels
prob_levels = [0.95, 0.5]
clevels=[flat[order][np.searchsorted(cumsum, p)] for p in prob_levels]

#plot contour
contour = ax.contour(Xc, Yc, hist.T,levels = clevels)
ax.clabel(contour, levels= [clevels[-1]], fmt = {clevels[-1]: 'Label'},  inline=True, fontsize=ax.xaxis.label.get_size(), manual = [(1, 0.5)])

plt.show()

Actual outcome

line 22, in
ax.clabel(contour, levels= [clevels[-1]], fmt = {clevels[-1]: 'Label'}, inline=True, fontsize=ax.xaxis.label.get_size(), manual = [(1, 0.5)])
File "/home/.conda/envs/test_env/lib/python3.12/site-packages/matplotlib/axes/_axes.py", line 6697, in clabel
return CS.clabel(levels, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/.conda/envs/test_env/lib/python3.12/site-packages/matplotlib/contour.py", line 195, in clabel
self.add_label_near(x, y, inline, inline_spacing)
File "/home/.conda/envs/test_env/lib/python3.12/site-packages/matplotlib/contour.py", line 562, in add_label_near
self.add_label(*proj, rotation, self.labelLevelList[idx_level_min],
~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
IndexError: list index out of range

Expected outcome

A contour label should be created only on the inner `contour```

Additional information

This seems to be due to this line, where self.add_label(*proj, rotation, self.labelLevelList[idx_level_min], self.labelCValueList[idx_level_min])
should rather be self.add_label(*proj, rotation, self.labelLevelList[level], self.labelCValueList[level])

Operating system

Ubuntu

Matplotlib Version

3.10.6

Matplotlib Backend

No response

Python version

3.12

Jupyter version

No response

Installation

None

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions