Matplotlib 슬라이더 및 그래프 아래 음영 처리

Sep 07 2020

슬라이더를 사용하여 인터랙티브 한 그림을 만들려고하는데 제가 그리는 그래프 아래에 영역을 음영 처리하고 싶습니다. 다음 코드 ( 2 개의 슬라이더 가있는 Interactive matplotlib 플롯 에서 수정 됨 )는 대화 형 그래프를 생성합니다.

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

내가 원하는 것은 그래프 아래에 음영 처리되는 것입니다. 인터랙티브하지 않은 경우 해결 방법 : matplotlib에서 곡선 아래 영역을 음영 처리하는 방법이 잘 작동합니다 (예 : ax.plot (X, Y)가 아닌 ax.fill (X, Y) 사용). 그러나 상호 작용으로 오류가 발생합니다.

"AttributeError : 'Polygon'개체에 'set_ydata'속성이 없습니다."

이것을 달성하는 방법을 아십니까?

답변

3 Mike67 Sep 07 2020 at 08:52

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

산출