Using matplotlib slider widget to change clim in image

后端 未结 2 972
我在风中等你
我在风中等你 2021-02-06 07:24

I have virtually no experience with python, but I am trying to create a simple script which loads an image and uses the slider widget to adjust the minimum and maximum of the co

2条回答
  •  鱼传尺愫
    2021-02-06 08:20

    Mostly, you just had lots and lots of syntax problems.

    For example, you were trying to unpack a single value (im1,=ax.imshow(im)) giving you the TypeError you mentioned in your question (as it should). You also set a function to a value when you meant to call it: (im1.set_clim=(smin.val,smax.val)).

    Also, I removed the from pylab import * from your example. This is fine for interactive use, but please, please, please don't use it for actual code. It makes it very difficult to tell where the functions you're calling are coming from (and the pylab namespace, in particular, is huge by design. It should only be used for interactive use or quick one-use scripts.)

    Here's a working example (using random data):

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.widgets import Slider, Button, RadioButtons
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig.subplots_adjust(left=0.25, bottom=0.25)
    min0 = 0
    max0 = 25000
    
    im = max0 * np.random.random((10,10))
    im1 = ax.imshow(im)
    fig.colorbar(im1)
    
    axcolor = 'lightgoldenrodyellow'
    axmin = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    axmax  = fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
    
    smin = Slider(axmin, 'Min', 0, 30000, valinit=min0)
    smax = Slider(axmax, 'Max', 0, 30000, valinit=max0)
    
    def update(val):
        im1.set_clim([smin.val,smax.val])
        fig.canvas.draw()
    smin.on_changed(update)
    smax.on_changed(update)
    
    plt.show()
    

提交回复
热议问题