【问题标题】:Matplotlib slider and shaded under graphMatplotlib 滑块和图形下的阴影
【发布时间】: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


    【解决方案1】:

    在 pyplot 中,您可以使用 fill_between 填充曲线下方。带动画,用fill_between用白色填充清除之前的数据。

    这是更新后的代码:

    #Define what happens when sliders changed
    def line_update(val):
        ax.fill_between([-5,5], [1,1], facecolor='white', alpha=1)  # fill white
        #ax.fill_between(X, [1 for v in Y], facecolor='white', alpha=1)  # fill white
        Y = gaussian(X,sigma_slider.val)
        line.set_ydata(Y)
        ax.fill_between(X, Y, facecolor='blue', alpha=0.30) # fill blue
        fig.canvas.draw_idle()
    
    #Call the above function when the slider is changed
    sigma_slider.on_changed(line_update)
    line_update(0)  # fill curve first time
    
    plt.show()
    

    输出

    【讨论】:

    • 谢谢,这太完美了!但是有两个问题:(1) 声明全局 Y, ax 的行的意义何在? (2) 不是在图表下将填充设置为白色,而是将其设置为白色是否有任何缺点(例如 ax.fill_between([-5,5],[1,1],'white') 应该这样做我想?)
    • 你是对的。在这种情况下,使用 [-5,5],[1,1] 也可以。很好。至于global,我认为这是各种解决方案尝试留下的。答案随更改而更新。
    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多