0
我正在試圖在特定區域的陰影中繪製(x,y)區域。作爲一個簡化示例,請考慮使用confidence intervals進行正態分佈。我想遮蔽置信區間,使一個標準偏差(或一個西格瑪)內的區域最黑暗,兩個標準偏差(或2個西格瑪)內的區域稍微偏淺一些,等等。我有辦法做到這一點,但我正在努力使我的劇本更加靈活。代碼如下。這個plt.fill_between()方法可以在循環中修改嗎?
## imports
import numpy as np
import matplotlib.pyplot as plt
from math import pi
## y = f(x)
def get_f(x, mu, sigma):
""" Normal Distribution Probability Density Function """
norm_constant = (sigma* (2*pi)**(1/2))
return [norm_constant * np.exp((-1) * (x[idx] - mu)**2/(2* sigma**2)) for idx in range(len(x))]
x = np.linspace(0, 100, 5000)
現在我們有x和函數f(x),我們可以繪製一個圖。我留下了可行的代碼部分,並對我的解決方案進行了評論。如果它能夠工作,我更喜歡我的解決方法,因爲根據所需間隔的數量更方便地進行遮擋,並且代碼不重複。
## generate plot
def get_plot(x, num_intervals=None, line_color='g', shade_color='b', mu=48, sigma=7):
""" Returns (x,y) plot; confidence intervals shading is optional """
y = get_f(x, mu, sigma)
plt.plot(x, y, line_color)
if num_intervals is not None:
## THIS CODE SEGMENT BELOW WORKS BUT I WOULD LIKE TO MAKE IT BETTER
plt.fill_between(x, y, where=(mu - sigma <= x), alpha=0.18, color=shade_color)
plt.fill_between(x, y, where=(x <= mu + sigma), alpha=0.18, color=shade_color)
plt.fill_between(x, y, where=(mu - 2*sigma <= x), alpha=0.11, color=shade_color)
plt.fill_between(x, y, where=(x <= mu + 2*sigma), alpha=0.11, color=shade_color)
plt.fill_between(x, y, where=(mu - 3*sigma <= x), alpha=0.02, color=shade_color)
plt.fill_between(x, y, where=(x <= mu + 3*sigma), alpha=0.02, color=shade_color)
## THIS CODE SEGMENT BELOW DOES NOT WORK AS I WOULD LIKE
## IT WILL SHADE THE REGIONS IN THE WRONG SHADE/DARKNESS
## choose shading level via dictionary
# alpha_keys = [idx+1 for idx in range(num_intervals)]
# alpha_vals = [0.18, 0.11, 0.02]
# alpha_dict = dict(zip(alpha_keys, alpha_vals))
# for idx in range(num_intervals):
# print("\nidx & stdev = %d & %d, \nmu - (stdev * sigma) = %.2f, \nmu + (stdev * sigma) = %.2f, alpha = %.2f" %(idx, stdev, mu - stdev*sigma, mu + stdev*sigma, alpha_dict[stdev]), "\n")
# stdev = idx + 1 ## number of standard deviations away from mu
# plt.fill_between(x, y, where=(mu - stdev * sigma <= x), alpha=alpha_dict[stdev], color=shade_color)
# plt.fill_between(x, y, where=(x >= mu + stdev * sigma), alpha=alpha_dict[stdev], color=shade_color)
plt.show()
運行正確的代碼產生this plot。我嘗試更方便的解決方案產生this plot並在下面生成輸出(通過打印語句),但我無法找到我的錯誤來源。
idx & stdev = 0 & 1,
mu - (stdev * sigma) = 41.00,
mu + (stdev * sigma) = 55.00, alpha = 0.18
idx & stdev = 1 & 2,
mu - (stdev * sigma) = 34.00,
mu + (stdev * sigma) = 62.00, alpha = 0.11
idx & stdev = 2 & 3,
mu - (stdev * sigma) = 27.00,
mu + (stdev * sigma) = 69.00, alpha = 0.02
我的方法是更方便的解決方案適應性?