Matplotlib: contour graph with slider

Matplotlib's newbie is here. I try to use the slider to adjust the parameter in the contour plot, but when I do this, I get:

AttributeError: QuadContourSet instance has no attribute 'set_data' 

I suspect that I am calling set_data on the wrong object, but I cannot find documentation about what the correct object is. You can help? Thanks.

Here is the full code:

 import numpy as np import matplotlib as mpl import matplotlib.mlab as mlab import matplotlib.pyplot as pyl from matplotlib.contour import QuadContourSet from matplotlib.widgets import Slider #Define display parameters mpl.rcParams['xtick.direction'] = 'out' mpl.rcParams['ytick.direction'] = 'out' delta = 0.025 #Define model parameters alpha = .5 beta = .5 x_bar, a, b, c = 2, 0, 1, .1 v = np.arange(0, 10, delta) w = np.arange(0, 10, delta) #Calculate grid values V, W = np.meshgrid(v,w) Z = (V**(beta))*(W**(1-beta)) X = x_bar + a + b*Z U = alpha*np.log(V) + (1-alpha)*np.log(X) - c*(W+V) # Plot fig = pyl.figure() ax = fig.add_subplot(221) CS = QuadContourSet(pyl.gca(), V, W, U, 200) pyl.clabel(CS, inline=1, fontsize=10) pyl.title('Simplest default with labels') #Define slider for alpha axcolor = 'lightgoldenrodyellow' alpha_axis = pyl.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) alpha_slider = Slider(alpha_axis, 'Amp', 0, 1, valinit=.5) def update(val): alpha = alpha_slider.val U = alpha*np.log(V) + (1-alpha)*np.log(X) - c*(W+V) CS.set_data(V, W, U) pyl.draw() alpha_slider.on_changed(update) pyl.show() 
+6
source share
1 answer

The problem is that the QuadContourSet object is not able to update its data, because if you arbitrarily change the data, all of this must be listed. I don’t know if there is anything about your specific way of generating data that would provide an easier way to change the contour lines, but if not, I think you need to do the construction of the contours from scratch:

 # After your "Define model parameters" block def compute_and_plot(ax, alpha): #Calculate grid values V, W = np.meshgrid(v,w) Z = (V**(beta))*(W**(1-beta)) X = x_bar + a + b*Z U = alpha*np.log(V) + (1-alpha)*np.log(X) - c*(W+V) CS = QuadContourSet(ax, V, W, U, 200) pyl.clabel(CS, inline=1, fontsize=10) # Plot fig = pyl.figure() pyl.title('Simplest default with labels') ax = fig.add_subplot(221) compute_and_plot(ax, alpha) #Define slider for alpha axcolor = 'lightgoldenrodyellow' alpha_axis = pyl.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) alpha_slider = Slider(alpha_axis, 'Amp', 0, 1, valinit=.5) def update(ax, val): alpha = alpha_slider.val ax.cla() compute_and_plot(ax, alpha) pyl.draw() alpha_slider.on_changed(lambda val: update(ax, val)) pyl.show() 
+3
source

Source: https://habr.com/ru/post/907961/


All Articles