从matplotlib.patches中的CirclePolygon获取坐标

时间:2018-05-09 08:35:11

标签: python matplotlib

我有以下代码,它使用Python matplotlib生成圆形多边形(圆形修补程序的多边形近似。)。

import matplotlib.pyplot as plt
from matplotlib.patches import CirclePolygon

circle = CirclePolygon((0, 0), radius = 0.75, fc = 'y')
plt.gca().add_patch(circle)
plt.axis('scaled')
plt.show()

对于上面的代码,我的输出如下: CirclePolygon

我需要一起形成圆形多边形的所有点。如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

Polygon基于路径。您可以通过circle.get_path()获取此路径。您对此路径的vertices感兴趣。 最后,您需要根据Polygon的变换对它们进行变换。

import matplotlib.pyplot as plt
from matplotlib.patches import CirclePolygon

circle = CirclePolygon((0, 0), radius = 0.75, fc = 'y')
plt.gca().add_patch(circle)

verts = circle.get_path().vertices
trans = circle.get_patch_transform()
points = trans.transform(verts)
print(points)

plt.plot(points[:,0],points[:,1])
plt.axis('scaled')
plt.show()

蓝线是由此获得的点的图。

enter image description here

答案 1 :(得分:0)

在将修补程序添加到轴之前,与在将修补程序添加到轴之后,在用户数据坐标中获取修补程序路径的转换不同。在添加到轴之前, patch.get_transform.transform(vertices)会以用户坐标生成数据,添加补丁后会在显示坐标中生成点。要将点转换回用户,请添加(链接)以下转换 ax.stransData.inverted()。transform(points)。请参阅两个功能。这使我感到困惑,但现在完全可以了。

import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Arrow

def get_data_before_adding_to_axes(a_patch):
    """Return true data from Patch Path before adding patch to an axes"""
    verts = a_patch.get_path().vertices
    return a_patch.get_transform().transform(verts)

def get_data_after_adding_to_axes(a_patch, ax=None):
    """Return true data from Patch Path after adding patch to an axes"""
    verts = a_patch.get_path().vertices
    points = a_patch.get_transform().transform(verts) # not screen coordinates
    return ax.transData.inverted().transform(points) # requires extra transform

# Instantiate 2 differnt type of patches:
circle = Circle((-0.5, 1), radius = 0.2, fc = 'y')
arrow  = Arrow(0, 1, 0, -1, fc='b')

fig, ax = plt.subplots()

print("Before adding the patches to the axes:")
for a_patch, its_name in zip([circle, arrow], ['circle', 'arrow']):
    xy = get_data_before_adding_to_axes(a_patch)
    print(its_name, ' :\n', xy)
    ax.plot(*xy.T, color='orange', ls='solid', lw=4)

ax.add_patch(circle)
ax.add_patch(arrow)

print("\nAfter adding the patches to the axes:")
for a_patch, its_name in zip([circle, arrow], ['circle', 'arrow']):
    xy = get_data_after_adding_to_axes(a_patch, ax=ax)
    print(its_name, ' :\n', xy)
    ax.plot(*xy.T, 'o', color='red', ls='dashed', lw=1)

Result, showing the patches and their outlines plotted from their tranformed paths