แถบเลื่อน Matplotlib และแรเงาใต้กราฟ

Sep 07 2020

ฉันกำลังพยายามสร้างรูปโต้ตอบด้วยแถบเลื่อน แต่ฉันต้องการแรเงาพื้นที่ใต้กราฟที่ฉันวาดด้วย โค้ดต่อไปนี้ (ดัดแปลงมาจากพล็อต 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.fill (X, Y) ไม่ใช่ ax.plot (X, Y)) อย่างไรก็ตามด้วยการโต้ตอบฉันได้รับข้อผิดพลาด:

"AttributeError: วัตถุ" รูปหลายเหลี่ยม "ไม่มีแอตทริบิวต์" 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()

เอาต์พุต