Suwak Matplotlib i zacieniowany pod wykresem

Sep 07 2020

Próbuję stworzyć interaktywną figurę za pomocą suwaka, ale chciałbym też zacienić obszar pod wykresem, który rysuję. Poniższy kod (zaadaptowany z interaktywnego wykresu matplotlib z dwoma suwakami ) tworzy interaktywny wykres:

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

Chcę, żeby był zacieniowany pod wykresem. Jeśli nie jest interaktywne, to rozwiązanie w: Jak cieniować region pod krzywą w matplotlib działa dobrze (tj. Użyj ax.fill (X, Y), a nie ax.plot (X, Y)). Jednak przy interaktywności pojawia się błąd:

„AttributeError: obiekt 'Polygon' nie ma atrybutu 'set_ydata'”

Masz pomysł, jak to osiągnąć?

Odpowiedzi

3 Mike67 Sep 07 2020 at 08:52

W pyplocie możesz wypełnić pod krzywą za pomocą fill_between. W przypadku animacji wyczyść poprzednie dane, używając fill_betweenbiałego wypełnienia.

Oto zaktualizowany kod:

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

Wynik