使用滑块更改变量并重新绘制 Matplotlib 图 [英] Using a slider to change variable and replot Matplotlib figure

查看:60
本文介绍了使用滑块更改变量并重新绘制 Matplotlib 图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用滑块来更改颜色缩放的限制,即使用 set_clim(min,max) 函数.我想要它,以便两个滑块控制最小值和最大值的值,并在它们更改后重新绘制图形.

I'm trying to use a slider to change the limits for color scaling i.e using the set_clim(min,max) function. I want it so that two sliders control the values for the min and max values and after they have changed the figure is replotted.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.widgets import Slider, Button

x=np.linspace(0,100,100)
y=np.linspace(0,100,100)
z=np.zeros((100,100))
for i in range (0,100):
    for j in range (0,100):
        z[i,j]=np.random.random()

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
l=plt.contourf(x,y,z)

axmax = plt.axes([0.25, 0.1, 0.65, 0.03])
axmin  = plt.axes([0.25, 0.15, 0.65, 0.03])

smax = Slider(axmax, 'Max', 0, 1.0, valinit=1)
smin = Slider(axmin, 'Min', 0, 1.0, valinit=0)
def update(val):
    fig.set_clim(smin.val,smax.val)
    fig.canvas.draw_idle()
smax.on_changed(update)
smin.on_changed(update)
plt.show()

当我移动滑块时,上面的代码给了我"AttributeError: 'AxesSubPlot' object has no attribute 'set_clim' ",尽管它确实向我显示了初始未更改的数字.这是我第一次在python中使用小部件(或多或少是我第一次使用python),因此很可能会有一些非常基本的误解.

The above code gives me " AttributeError: 'AxesSubPlot' object has no attribute 'set_clim' " when I move the sliders although it does show me the initial unchanged figure. This is my first time using widgets in python (and more or less my first time using python) so there may well be some quite fundamental misunderstandings.

推荐答案

问题在于错误告诉您, axes 对象没有 set_clim 函数.你想改变(这使得你报告的错误是我期望的,但是)

The problem is as the error tells you, axes objects don't have a set_clim function. You want to change (which makes the error you report on the one I expect, but)

fig.set_clim(smin.val,smax.val)

l.set_clim(smin.val,smax.val)

,因为您需要在 ScalarMappable 对象set_clim .ScalarMappable" rel="nofollow">(doc).

as you need to call set_clim on a ScalarMappable object (doc).

请注意, np.random.random 会引起争论,因此您可以这样做

As a side note, np.random.random takes a size arguement so you can do

z = np.random.random((100, 100))

而不是嵌套循环.

这篇关于使用滑块更改变量并重新绘制 Matplotlib 图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆