【发布时间】:2020-09-06 22:57:38
【问题描述】:
我正在尝试创建一个带有滑块的交互式图形,但我还想在我正在绘制的图形下方添加阴影区域。以下代码(改编自 Interactive matplotlib plot with two sliders)生成一个交互式图表:
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
#Define the function we're graphing
def gaussian(x, sigma):
N = pow(2*pi,-0.5)/sigma
Z = x/sigma
return N*np.exp(-Z*Z/2)
#Default standard deviation of 1
std0=1
#Set up initial default data
X = np.arange(-5,5,0.1)
Y = gaussian(X,std0)
#Create an axis for main graph
fig, ax = plt.subplots(1,1)
ax.set_xlim([-5,5])
ax.set_ylim([0,1])
#[line] will be modified later with new Y values
[line]=ax.plot(X,Y)
#this moves the figure up so that it's not on top of the slider
fig.subplots_adjust(bottom=0.4)
#Create slider
sigma_slider_ax = fig.add_axes([0.25,0.25,0.65,0.03])
sigma_slider = Slider(sigma_slider_ax, 'Standard Deviation', 0.5,2.0,valinit=std0)
#Define what happens when sliders changed
def line_update(val):
Y = gaussian(X,sigma_slider.val)
line.set_ydata(Y)
fig.canvas.draw_idle()
#Call the above function when the slider is changed
sigma_slider.on_changed(line_update)
plt.show()
我想要的是它在图表下的阴影。如果它不是交互式的,那么解决方案位于: How to shade region under the curve in matplotlib 效果很好(即使用 ax.fill(X,Y) 而不是 ax.plot(X,Y))。但是,通过交互,我得到一个错误:
"AttributeError: 'Polygon' 对象没有属性 'set_ydata'"
知道如何实现吗?
【问题讨论】:
标签: python matplotlib plot