2013-01-10 43 views
1

我想知道是否有更優雅的方式在下面的代碼中繪製多邊形,或者使用特殊的繪圖函數或參數?matplotlib函數圖的彩色段

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.stats import norm 
x = np.linspace(-4,4,150) 
# plot density with shaded area showing Pr(-2 <= x <= 1) 
lb = -2 
ub = 1 
d=norm.pdf(x) 
fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1) 
ax.plot(x, d) 
### can this be done more elegantly ### 
sx = np.linespace(lb,ub,100) 
sd = norm.pdf(sx) 
sx = [lb] + sx + [ub] 
sd = [0] + list(sd) + [0] 
xy = np.transpose(np.array([sx, sd])) 
pgon = plt.Polygon(xy, color='b') 
####################################### 
ax.add_patch(pgon) 
plt.show() 

回答

1

也許你正在尋找plt.fill_between

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.stats import norm 
x = np.linspace(-4,4,150) 
# plot density with shaded area showing Pr(-2 <= x <= 1) 
lb = -2 
ub = 1 
d = norm.pdf(x) 
fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1) 
ax.plot(x, d) 

idx = np.searchsorted(x,[lb,ub]) 
sx = x[idx[0]:idx[1]] 
sd = d[idx[0]:idx[1]] 
plt.fill_between(sx, sd, 0, color = 'b') 
plt.show() 

enter image description here

+0

事實上,這是我需要的,謝謝! – ronnydw

+0

我改變了'sx'和'sd'的計算方式。分割'x'和'd'比重新計算'norm.pdf'更有效。也許在這種情況下它不是那麼重要,但我認爲它是更好的風格(如果計算更昂貴,也許很重要)。 – unutbu