matplotlib clabel上的set_clip_path没有正确剪裁

时间:2017-03-21 14:10:29

标签: python matplotlib plot

我正在制作一个剪裁到多边形路径的等高线图:

show @b

令我惊讶的是,尽管import matplotlib.pyplot as plt from matplotlib.patches import Polygon import numpy as np fig = plt.figure() axes = plt.subplot() x,y = np.meshgrid( np.linspace(-10,10,51), np.linspace(-10,10,51) ) z = np.sin(np.sqrt(x**2+y**2)) CS = axes.contour(x, y, z, np.linspace(-1,1,11) ) axes.set_aspect('equal') # clip contours by polygon radius = 8 t = np.linspace(0,2*np.pi,101) x_bound,y_bound = radius*np.sin(t),radius*(np.cos(t)+0.1*(np.cos(7*t))) clip_map = Polygon(list(zip(x_bound,y_bound)),fc='#EEEEEE',ec='none') axes.add_patch(clip_map) for collection in CS.collections: collection.set_clip_path(clip_map) # label the contours CLB = axes.clabel(CS, colors='black') for text_object in CLB: text_object.set_clip_path(clip_map) # Doesn't do anything! plt.show() 对象的Text方法没有返回错误,但标签不会被剪裁:

contour plot where labels aren't clipped

如何剪切灰色多边形区域外的标签?我是否需要手动查找X和Y位置,计算多边形中的点,以及每个set_clip_path项目set_visible = False?为什么这段代码不能正常工作?我正在使用matplotlib版本1.5.1和python 3.5.1。

1 个答案:

答案 0 :(得分:3)

以防万一有人在某天遇到同样的问题,这是一个解决方案,它必须使用shapely包测试多边形中的点来设置Text对象的可见性状态。它完成了工作,但如果可以使用set_clip_path直接在Text对象上工作,那就太好了。

import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import numpy as np
from shapely.geometry import Polygon as ShapelyPolygon
from shapely.geometry import Point as ShapelyPoint

fig = plt.figure()
axes = plt.subplot()
x,y = np.meshgrid( np.linspace(-10,10,51), np.linspace(-10,10,51) ) 
z = np.sin(np.sqrt(x**2+y**2))
CS =  axes.contour(x, y, z, np.linspace(-1,1,11) )
axes.set_aspect('equal')

# clip contours by polygon
radius = 8
t = np.linspace(0,2*np.pi,101)
x_bound,y_bound = radius*np.sin(t),radius*(np.cos(t)+0.1*(np.cos(7*t)))
clip_map = Polygon(list(zip(x_bound,y_bound)),fc='#EEEEEE',ec='none')
axes.add_patch(clip_map)
for collection in CS.collections:
    collection.set_clip_path(clip_map)

# label the contours    
CLB = axes.clabel(CS, colors='black')
clip_map_shapely = ShapelyPolygon(clip_map.get_xy())

for text_object in CLB:
    if not clip_map_shapely.contains(ShapelyPoint(text_object.get_position())):
        text_object.set_visible(False)

plt.show()

sample AndroidManifest.xml