在调用clabel()之后,可以从cs对象中临时删除不需要标签的路径,将这些删除的路径恢复到cs对象。
这里是一个例子。对于每个级别的收藏,保持最长的路径,并删除所有其他人。 path_length()计算路径的长度。
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()
下面是结果,你可以看到,只有一个绿色&棕色系的标签。
从你的情节,我认为你可以使用路径长度作为判断。如果矩形的长度大于外部曲线,则需要找到其他方法来确定要移除的路径。
![enter image description here](https://i.stack.imgur.com/6UDwx.png)
第二组标签在哪里?我不知道它们在哪里.. – fraxel
@fraxel它们全部沿着矩形左边的中间放置在彼此的顶部。 – pafcu