如何在Matplotlib中绘制实心圆弧 [英] How to draw a filled arc in matplotlib

查看:156
本文介绍了如何在Matplotlib中绘制实心圆弧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In matplotlib, I would like draw an filled arc which looks like this:

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

The following code results in an unfilled line arc:

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()

文档说,实心圆弧不是可能的.画一个的最好方法是什么?

The documentation says that filled arcs are not possible. What would be the best way to draw one?

推荐答案

@jeanrjc的解决方案几乎可以帮助您,但是它添加了一个完全不必要的白色三角形,它也会隐藏其他对象(见下图,版本 1).

@jeanrjc's solution almost gets you there, but it adds a completely unnecessary white triangle, which will hide other objects as well (see figure below, version 1).

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

This is a simpler approach, which only adds a polygon of the arc:

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

Basically we create a series of points (points) along the edge of the circle (from theta1 to theta2). This is already enough, as we can set the close flag in the Polygon constructor which will add the line from the last to the first point (creating a closed arc).

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):

这篇关于如何在Matplotlib中绘制实心圆弧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆