Skip to content

Turn ContourSet into a standard Collection artist. #25247

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions doc/api/next_api_changes/deprecations/25247-AL.rst

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately this change broke my "contours to shapefile" code, because the temporarily retained functionality of CountourSet.collections actually does not behave as it did before matplotlib 3.8.0. Somehow it is causing my final polygon set to become a single polygon, so that every contour has a connecting segment to the next contour in the set. So I was forced to update my code to the new definition of CountourSet, which I guess isn't a terrible thing, but effectively there is no "deprecation period"...it was immediate for me.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mstoelinga, please try our main branch and see if this is fixed for you. This was a mistake, and should be fixed in 3.8.1

Copy link
Member

@rcomer rcomer Oct 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the collections attribute actually couldn’t be fully backwards compatible (from this comment)

# On access, make oneself invisible and instead add the old-style collections
# (one PathCollection per level). We do not try to further split contours into
# connected components as we already lost track of what pairs of contours need
# to be considered as single units to draw filled regions with holes.

There is now only one path in each collection, whereas there used to be multiple.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"contours to shapefile" code

This sounds like something that could use contourpy directly.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very much so. I need to write up some docs on how to convert ContourPy outputs into other formats such as Shapely.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am also looking for a solution to convert the ContourSet to shapefile. The code below does not work anymore.

from shapely.geometry import LineString

contour = ax.conout(...)
levels = contour.levels
shps = []
lvls = []
for l, c in zip(levels, contour):
    for ps in c.get_paths():
        shps.append(LineString(ps.vertices))
        lvls.append(l)
shp = gpd.GeoDataFrame({'level':lvls}, geometry=shps, )

Any quick fix? Thanks!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rcomer thanks. Are the plotted contours identical to what ContourPy generates?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ougx Matplotlib uses ContourPy's contours.

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
``ContourSet.collections``
~~~~~~~~~~~~~~~~~~~~~~~~~~
... is deprecated. `.ContourSet` is now implemented as a single `.Collection` of paths,
each path corresponding to a contour level, possibly including multiple unconnected
components.

During the deprecation period, accessing ``ContourSet.collections`` will revert the
current ContourSet instance to the old object layout, with a separate `.PathCollection`
per contour level.
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@
linewidths=2, extent=(-3, 3, -2, 2))

# Thicken the zero contour.
CS.collections[6].set_linewidth(4)
lws = np.resize(CS.get_linewidth(), len(levels))
lws[6] = 4
CS.set_linewidth(lws)

ax.clabel(CS, levels[1::2], # label every second level
inline=True, fmt='%1.1f', fontsize=14)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,7 @@

# We don't really need dashed contour lines to indicate negative
# regions, so let's turn them off.

for c in cset2.collections:
c.set_linestyle('solid')
cset2.set_linestyle('solid')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And here this is much nicer :)


# It is easier here to make a separate call to contour than
# to set up an array of colors and linewidths.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
`~matplotlib.patheffects.TickedStroke` to illustrate a constraint in
a typical optimization problem, the angle should be set between
zero and 180 degrees.

"""

import matplotlib.pyplot as plt
Expand Down Expand Up @@ -48,16 +47,13 @@
ax.clabel(cntr, fmt="%2.1f", use_clabeltext=True)

cg1 = ax.contour(x1, x2, g1, [0], colors='sandybrown')
plt.setp(cg1.collections,
path_effects=[patheffects.withTickedStroke(angle=135)])
cg1.set(path_effects=[patheffects.withTickedStroke(angle=135)])

cg2 = ax.contour(x1, x2, g2, [0], colors='orangered')
plt.setp(cg2.collections,
path_effects=[patheffects.withTickedStroke(angle=60, length=2)])
cg2.set(path_effects=[patheffects.withTickedStroke(angle=60, length=2)])

cg3 = ax.contour(x1, x2, g3, [0], colors='mediumblue')
plt.setp(cg3.collections,
path_effects=[patheffects.withTickedStroke(spacing=7)])
cg3.set(path_effects=[patheffects.withTickedStroke(spacing=7)])

ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
Expand Down
3 changes: 1 addition & 2 deletions galleries/examples/misc/patheffect_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@
ax2.imshow(arr)
cntr = ax2.contour(arr, colors="k")

plt.setp(cntr.collections, path_effects=[
patheffects.withStroke(linewidth=3, foreground="w")])
cntr.set(path_effects=[patheffects.withStroke(linewidth=3, foreground="w")])

clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
plt.setp(clbls, path_effects=[
Expand Down
9 changes: 3 additions & 6 deletions galleries/examples/misc/tickedstroke_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,16 +88,13 @@
ax.clabel(cntr, fmt="%2.1f", use_clabeltext=True)

cg1 = ax.contour(x1, x2, g1, [0], colors='sandybrown')
plt.setp(cg1.collections,
path_effects=[patheffects.withTickedStroke(angle=135)])
cg1.set(path_effects=[patheffects.withTickedStroke(angle=135)])

cg2 = ax.contour(x1, x2, g2, [0], colors='orangered')
plt.setp(cg2.collections,
path_effects=[patheffects.withTickedStroke(angle=60, length=2)])
cg2.set(path_effects=[patheffects.withTickedStroke(angle=60, length=2)])

cg3 = ax.contour(x1, x2, g3, [0], colors='mediumblue')
plt.setp(cg3.collections,
path_effects=[patheffects.withTickedStroke(spacing=7)])
cg3.set(path_effects=[patheffects.withTickedStroke(spacing=7)])

ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
Expand Down
12 changes: 3 additions & 9 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2171,15 +2171,9 @@ def _sci(self, im):
``pyplot.viridis``, and other functions such as `~.pyplot.clim`. The
current image is an attribute of the current Axes.
"""
_api.check_isinstance(
(mpl.contour.ContourSet, mcoll.Collection, mimage.AxesImage),
im=im)
if isinstance(im, mpl.contour.ContourSet):
if im.collections[0] not in self._children:
raise ValueError("ContourSet must be in current Axes")
elif im not in self._children:
raise ValueError("Argument must be an image, collection, or "
"ContourSet in this Axes")
_api.check_isinstance((mcoll.Collection, mimage.AxesImage), im=im)
if im not in self._children:
raise ValueError("Argument must be an image or collection in this Axes")
self._current_image = im

def _gci(self):
Expand Down
10 changes: 5 additions & 5 deletions lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,15 +750,15 @@ def add_lines(self, *args, **kwargs):
lambda self, levels, colors, linewidths, erase=True: locals()],
self, *args, **kwargs)
if "CS" in params:
self, CS, erase = params.values()
if not isinstance(CS, contour.ContourSet) or CS.filled:
self, cs, erase = params.values()
if not isinstance(cs, contour.ContourSet) or cs.filled:
raise ValueError("If a single artist is passed to add_lines, "
"it must be a ContourSet of lines")
# TODO: Make colorbar lines auto-follow changes in contour lines.
return self.add_lines(
CS.levels,
CS.to_rgba(CS.cvalues, CS.alpha),
[coll.get_linewidths()[0] for coll in CS.collections],
cs.levels,
cs.to_rgba(cs.cvalues, cs.alpha),
cs.get_linewidths(),
erase=erase)
else:
self, levels, colors, linewidths, erase = params.values()
Expand Down
Loading