在matplotlib中,我想绘制一个如下所示的实心圆弧:

以下代码导致未填充的圆弧:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

fg, ax = plt.subplots(1, 1)

pac = mpatches.Arc([0, -2.5], 5, 5, angle=0, theta1=45, theta2=135)
ax.add_patch(pac)

ax.axis([-2, 2, -2, 2])
ax.set_aspect("equal")
fg.canvas.draw()

documentation说不可能填充圆弧。
画一个的最好方法是什么?

最佳答案

@jeanrjc's solution几乎可以带您到那里,但是它添加了一个完全不必要的白色三角形,该三角形也将隐藏其他对象(请参见下图,版本1)。

这是一种更简单的方法,它仅添加一个圆弧的多边形:

基本上,我们沿着圆的边缘(从pointstheta1)创建了一系列点(theta2)。这已经足够了,因为我们可以在close构造函数中设置Polygon标志,该标志会将最后一条线添加到第一点(创建闭合弧线)。

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np

def arc_patch(center, radius, theta1, theta2, ax=None, resolution=50, **kwargs):
    # make sure ax is not empty
    if ax is None:
        ax = plt.gca()
    # generate the points
    theta = np.linspace(np.radians(theta1), np.radians(theta2), resolution)
    points = np.vstack((radius*np.cos(theta) + center[0],
                        radius*np.sin(theta) + center[1]))
    # build the polygon and add it to the axes
    poly = mpatches.Polygon(points.T, closed=True, **kwargs)
    ax.add_patch(poly)
    return poly

然后我们将其应用:
fig, ax = plt.subplots(1,2)

# @jeanrjc solution, which might hide other objects in your plot
ax[0].plot([-1,1],[1,-1], 'r', zorder = -10)
filled_arc((0.,0.3), 1, 90, 180, ax[0], 'blue')
ax[0].set_title('version 1')

# simpler approach, which really is just the arc
ax[1].plot([-1,1],[1,-1], 'r', zorder = -10)
arc_patch((0.,0.3), 1, 90, 180, ax=ax[1], fill=True, color='blue')
ax[1].set_title('version 2')

# axis settings
for a in ax:
    a.set_aspect('equal')
    a.set_xlim(-1.5, 1.5)
    a.set_ylim(-1.5, 1.5)

plt.show()

结果(版本2):

关于python - 如何在Matplotlib中绘制实心圆弧,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30642391/

10-10 17:53