pafcu
pafcu

Reputation: 8128

Remove duplicate matplotlib contour labels when contour goes partially outside visible area

I'm having a problem with drawing "zoomed" in contour maps. The problem is best illustrated with the following images:

I have a contour plot like the one below:

Full plot

Howevere, when I "zoom" in, by only plotting part of the data (take a slice of the original input array), the result is the following:

partial plot

It seems like labels are added twice for each line, probably because the lines go outside the visible space and then return again. How do I prevent the second set of labels from appearing, without having to place all labels manually? Near the rectangle in the centre all the lines overlap anyway, so there is no need for the labels placed there.

Upvotes: 1

Views: 2096

Answers (1)

HYRY
HYRY

Reputation: 97331

You can remove the paths which don't need label temporarily from the cs object, after call the clabel(), restore those deleted pathes to the cs object.

Here is an example. For every level's collections, remain the longest path, and remove all others. path_length() calculate the length of path.

import pylab as pl
import numpy as np

x, y = np.mgrid[-2:1:100j, -1:1:100j]
z = np.sqrt(x*x+y*y)

cs = pl.contour(x, y, z, linewidths=2)

def path_length(path):
    v = path.vertices
    dv = np.diff(v, axis=0)
    return np.sum(np.sqrt(np.sum(dv**2, axis=-1)))

# remain the longest path and remove all others
deleted_path = []
for c in cs.collections:
    paths = c.get_paths()
    if len(paths) > 1:
        paths.sort(key=path_length, reverse=True)
        for p in paths[1:]:
            deleted_path.append((c, p))
        del paths[1:]

# create labels
r = pl.clabel(cs, cs.levels, inline=True, fontsize=10)

# restore all removed paths
for c, p in deleted_path:
    c.get_paths().append(p)

pl.show()

Here is the result, as you can see, there is only one label for green & brown line.

From your plot, I think you can use path length as the judgment. If the length of rectangle is larger than the outside curves, you need to find other method to figure out which path to remove.

enter image description here

Upvotes: 3

Related Questions