2014-04-01 91 views
3

我要繪製一個甜甜圈填充或fill_between使用pyplot甜甜圈,我的劇本是情節與matplotlib

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) 

如何獲得用紅色填充區域甜甜圈?

回答

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

2

您可以通過單獨繪製的上半部和下半部做到這一點:

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

8

可以遍歷在閉曲線的區域的邊界,並且使用fill方法來填充該封閉區域內的區域:

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

circle

這可以容易地應用到任何形狀,例如,內部或外部的五角形:

pentagon

+1

+1:非常好,一般的解決方案(比我的更好) – tom10