在matplotlib中使用fill或fill_between使用pyplot绘制甜甜圈

时间:2014-04-01 14:47:28

标签: python matplotlib fill

我想画一个甜甜圈,我的剧本是

import numpy as np
import matplotlib.pyplot as plt
pi,sin,cos = np.pi,np.sin,np.cos

r1 = 1
r2 = 2

theta = np.linspace(0,2*pi,36)

x1 = r1*cos(theta)
y1 = r1*sin(theta)

x2 = r2*cos(theta)
y2 = r2*sin(theta)

如何获得红色填充区域的甜甜圈?

4 个答案:

答案 0 :(得分:11)

您可以在闭合曲线中遍历该区域的边界,并使用fill方法填充此封闭区域内的区域:

import numpy as np
import matplotlib.pyplot as plt

n, radii = 50, [.7, .95]
theta = np.linspace(0, 2*np.pi, n, endpoint=True)
xs = np.outer(radii, np.cos(theta))
ys = np.outer(radii, np.sin(theta))

# in order to have a closed area, the circles
# should be traversed in opposite directions
xs[1,:] = xs[1,::-1]
ys[1,:] = ys[1,::-1]

ax = plt.subplot(111, aspect='equal')
ax.fill(np.ravel(xs), np.ravel(ys), edgecolor='#348ABD')

plt.show()

circle

这可以很容易地应用于任何形状,例如,圆形内部或外部的五边形:

pentagon

答案 1 :(得分:3)

您可以通过分别绘制上半部和下半部来完成此操作:

import numpy as np
import matplotlib.pyplot as plt

inner = 5.
outer = 10.

x = np.linspace(-outer, outer, 1000, endpoint=True)

yO = outer*np.sin(np.arccos(x/outer)) # x-axis values -> outer circle
yI = inner*np.sin(np.arccos(x/inner)) # x-axis values -> inner circle (with nan's beyond circle)
yI[np.isnan(yI)] = 0.                 # yI now looks like a boulder hat, meeting yO at the outer points

ax = plt.subplot(111)
ax.fill_between(x, yI, yO, color="red")
ax.fill_between(x, -yO, -yI, color="red")

plt.show()

enter image description here

或者您可以使用极坐标,但这是否有益取决于更广泛的背景:

import numpy as np
import matplotlib.pyplot as plt

theta = np.linspace(0., 2.*np.pi, 80, endpoint=True)
ax = plt.subplot(111, polar=True)
ax.fill_between(theta, 5., 10., color="red")

plt.show()

enter image description here

答案 2 :(得分:1)

这有点像黑客,但以下工作:

import numpy as np
import matplotlib.pyplot as plt
pi,sin,cos = np.pi,np.sin,np.cos

r1 = 1
r2 = 2

theta = np.linspace(0,2*pi,36)

x1 = r1*cos(theta)
y1 = r1*sin(theta)

x2 = r2*cos(theta)
y2 = r2*sin(theta)

fig, ax = plt.subplots()

ax.fill_between(x2, -y2, y2, color='red')
ax.fill_between(x1, y1, -y1, color='white')

plt.show()

用红色绘制甜甜圈的整个区域,然后将白色的中央“洞”绘制成白色。

Example plot

答案 3 :(得分:0)

tom10给出的答案是10;) 但是如果你想定义圆(圆环)原点很简单,只需在x,yI,yO和-yO以及-yI中添加位置x,y,如下所示:

...
pos = [4,2]
ax.fill_between(x+pos[0], yI+pos[1], yO+pos[1], color=color)
ax.fill_between(x+pos[0], -yO+pos[1], -yI+pos[1], color=color)
...

REF示例:https://pastebin.com/8Ew4Vthb