gpt4 book ai didi

python - 为什么 fill_between 在这里不起作用?

转载 作者:行者123 更新时间:2023-11-28 19:49:02 24 4
gpt4 key购买 nike

我正在使用 Anaconda 2.7,我的 fill_between() 尝试没有结果。我不确定我是否遗漏了一个包,或者我的绘图语法是否正在抛出 python...

这是我的代码:

from scipy import stats
import matplotlib.pyplot as plt
from numpy import linspace

alpha_A = 11
beta_A = 41
alpha_B = 3
beta_B = 3

x = linspace(0,1,num = 1000)
postA = stats.beta(alpha_A, beta_A).pdf(x)
postB = stats.beta(alpha_B, beta_B).pdf(x)


plt.figure(2, figsize = (6,4))
plt.plot(postA, color = 'r', label = "A: Beta(" + str(alpha_A) + ',' + str(beta_A) + ')')
plt.plot(postB, color = 'b',label = "B: Beta(" + str(alpha_B) + ',' + str(beta_B) + ')')
plt.legend(loc = "best", frameon = False)
plt.fill_between(x, postA, facecolor = "red") # <---- not working
frame1 = plt.gca()
frame1.axes.get_xaxis().set_ticks([])
ax = plt.gca()
ax.set_xticks([0,200,400,600,800,1000])
ax.set_xticklabels( ['0.0','0.2','0.4','0.6','0.8','1.0']) # https://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#setting-tick-labels
ax.set_title("Posterior Distributions")

这给了我这个图表,其中没有出现红色填充:enter image description here

最佳答案

它确实有效,如果您放大绘图的左侧(您可以在显示的图像上看到它,垂直线上升到 7)。

那么,这是为什么呢?

这是因为你的绘图在 x 轴上上升到 1000,而你要求将其填充到 1 (max(x))。

2 种解决方案:

快速的:

你替换这一行:

plt.fill_between(x, postA, facecolor = "red")

这个

plt.fill_between(range(len(x)), postA, facecolor = "red")

干净的:

代码的第二部分变为:

fig = plt.figure(figsize = (6,4))
ax = fig.add_subplot(111)
ax.plot(x, postA, color = 'r', label = "A: Beta(" + str(alpha_A) + ',' + str(beta_A) + ')')
ax.plot(x, postB, color = 'b',label = "B: Beta(" + str(alpha_B) + ',' + str(beta_B) + ')')
ax.legend(loc = "best", frameon = False)
ax.fill_between(x, postA, facecolor = "red")
ax.set_title("Posterior Distributions")

在这里,如果您只提供 Y 值,则您将绘图中的 x 值指定为 x,而不是 len(postA)。因此,您将直接获得正确的 x-ticks。

这里是干净溶液的结果:

fill_between

希望这对您有所帮助。

关于python - 为什么 fill_between 在这里不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26300147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com