Controle deslizante Matplotlib e sombreado no gráfico

Sep 07 2020

Estou tentando criar uma figura interativa com um controle deslizante, mas também gostaria de sombrear a região sob o gráfico que estou desenhando. O código a seguir (adaptado do gráfico de matplotlib interativo com dois controles deslizantes ) produz um gráfico interativo:

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()

O que eu quero é que ele seja sombreado sob o gráfico. Se não for interativo, a solução em: Como sombrear a região sob a curva em matplotlib funciona bem (ou seja, use ax.fill (X, Y) e não ax.plot (X, Y)). Porém, com a interatividade, recebo um erro:

"AttributeError: o objeto 'Polygon' não tem atributo 'set_ydata'"

Alguma ideia de como conseguir isso?

Respostas

3 Mike67 Sep 07 2020 at 08:52

No pyplot, você pode preencher sob a curva usando fill_between. Com animação, limpe os dados anteriores usando fill_betweenum preenchimento branco.

Aqui está o código atualizado:

#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()

Resultado