Skip to content

Fix: Prevent clabel() from modifying filled contour geometry#31348

Closed
shivamrajsr07 wants to merge 1 commit intomatplotlib:mainfrom
shivamrajsr07:fix-contour-label-bug
Closed

Fix: Prevent clabel() from modifying filled contour geometry#31348
shivamrajsr07 wants to merge 1 commit intomatplotlib:mainfrom
shivamrajsr07:fix-contour-label-bug

Conversation

@shivamrajsr07
Copy link

Summary

Fixes an issue where adding contour labels using clabel() on filled contour plots (contourf) alters the geometry of the filled regions.

When inline labeling is enabled, the labeling logic modifies internal path data. This behavior is appropriate for line contours but unintentionally affects filled contours, resulting in distorted shapes.

Root Cause

The inline labeling code updates the internal _paths of the contour set regardless of whether the contour is filled or not. For filled contours, these paths define the filled regions themselves, so modifying them changes the visual output.

Fix

Restrict path modification to non-filled contours only. Inline labeling now avoids mutating _paths when self.filled is True.

Reproduction

Example demonstrating the issue:

import matplotlib.pyplot as plt
import numpy as np

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)

Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

fig, axs = plt.subplots(2, 1)

axs[0].contourf(X, Y, Z)

CS = axs[1].contourf(X, Y, Z)
axs[1].clabel(CS)

plt.show()

@github-actions
Copy link

Thank you for opening your first PR into Matplotlib!

If you have not heard from us in a week or so, please leave a new comment below and that should bring it to our attention. Most of our reviewers are volunteers and sometimes things fall through the cracks. We also ask that you please finish addressing any review comments on this PR and wait for it to be merged (or closed) before opening a new one, as it can be a valuable learning experience to go through the review process.

You can also join us on gitter for real-time discussion.

For details on testing, writing docs, and our review process, please see the developer guide.
Please let us know if (and how) you use AI, it will help us give you better feedback on your PR.

We strive to be a welcoming and open project. Please follow our Code of Conduct.

@rcomer
Copy link
Member

rcomer commented Mar 22, 2026

Skipping the path breaking is indeed simple. However, the problem plot also wrongly shows two numbers on each boundary, and that is much harder to fix. As noted already in the issue comments and the existing PR, this was never expected to work for filled contours.

So I’m sorry but I’m going to close this.

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

Projects

Development

Successfully merging this pull request may close these issues.

2 participants