Skip to content

[Bug]: cannot give init value for RangeSlider widget #22686

Description

@vpicouet

Bug summary

I think xy[4] = .25, val[0] should be commented in /matplotlib/widgets. py", line 915, in set_val
as it prevents to initialized value for RangeSlider

Code for reproduction

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RangeSlider

# generate a fake image
np.random.seed(19680801)
N = 128
img = np.random.randn(N, N)

fig, axs = plt.subplots(1, 2, figsize=(10, 5))
fig.subplots_adjust(bottom=0.25)

im = axs[0].imshow(img)
axs[1].hist(img.flatten(), bins='auto')
axs[1].set_title('Histogram of pixel intensities')

# Create the RangeSlider
slider_ax = fig.add_axes([0.20, 0.1, 0.60, 0.03])
slider = RangeSlider(slider_ax, "Threshold", img.min(), img.max(),valinit=[0.0,0.0])

# Create the Vertical lines on the histogram
lower_limit_line = axs[1].axvline(slider.val[0], color='k')
upper_limit_line = axs[1].axvline(slider.val[1], color='k')


def update(val):
    # The val passed to a callback by the RangeSlider will
    # be a tuple of (min, max)

    # Update the image's colormap
    im.norm.vmin = val[0]
    im.norm.vmax = val[1]

    # Update the position of the vertical lines
    lower_limit_line.set_xdata([val[0], val[0]])
    upper_limit_line.set_xdata([val[1], val[1]])

    # Redraw the figure to ensure it updates
    fig.canvas.draw_idle()


slider.on_changed(update)
plt.show()

Actual outcome

  File "<ipython-input-52-b704c53e18d4>", line 19, in <module>
    slider = RangeSlider(slider_ax, "Threshold", img.min(), img.max(),valinit=[0.0,0.0])

  File "/Users/Vincent/opt/anaconda3/envs/py38/lib/python3.8/site-packages/matplotlib/widgets.py", line 778, in __init__
    self.set_val(valinit)

  File "/Users/Vincent/opt/anaconda3/envs/py38/lib/python3.8/site-packages/matplotlib/widgets.py", line 915, in set_val
    xy[4] = val[0], .25

IndexError: index 4 is out of bounds for axis 0 with size 4

Expected outcome

range slider with user initial values

Additional information

error can be removed by commenting this line

    def set_val(self, val):
        """
        Set slider value to *val*.

        Parameters
        ----------
        val : tuple or array-like of float
        """
        val = np.sort(np.asanyarray(val))
        if val.shape != (2,):
            raise ValueError(
                f"val must have shape (2,) but has shape {val.shape}"
            )
        val[0] = self._min_in_bounds(val[0])
        val[1] = self._max_in_bounds(val[1])
        xy = self.poly.xy
        if self.orientation == "vertical":
            xy[0] = .25, val[0]
            xy[1] = .25, val[1]
            xy[2] = .75, val[1]
            xy[3] = .75, val[0]
            # xy[4] = .25, val[0]
        else:
            xy[0] = val[0], .25
            xy[1] = val[0], .75
            xy[2] = val[1], .75
            xy[3] = val[1], .25
            # xy[4] = val[0], .25
        self.poly.xy = xy
        self.valtext.set_text(self._format(val))
        if self.drawon:
            self.ax.figure.canvas.draw_idle()
        self.val = val
        if self.eventson:
            self._observers.process("changed", val)

Operating system

OSX

Matplotlib Version

3.5.1

Matplotlib Backend

No response

Python version

3.8

Jupyter version

No response

Installation

pip

Activity

  1. WeatherGod commented on Mar 23, 2022

    @WeatherGod
    Member
  2. vpicouet commented on Mar 23, 2022

    @vpicouet
    Author

    Yes, i might have been too fast, cause it allows to skip the error but then it seems that the polygon is not right...
    Let me know if you know how this should be solved...
    Capture d’écran, le 2022-03-22 à 23 20 23

  3. ianhi commented on Mar 23, 2022

    @ianhi
    Contributor

    So I think you found an edge case because your valinit has both values equal. This means that the poly object created by axhspan is not as large as the rest of the code expects.

    self.poly = ax.axvspan(valinit[0], valinit[1], 0, 1, **kwargs)

    A quick workaround is to have the valinit contain two different numbers (even if only minuscule difference)

  4. vpicouet commented on Mar 23, 2022

    @vpicouet
    Author

    Yes you are right!
    Thanks a lot for digging into this!!

  5. ianhi commented on Mar 23, 2022

    @ianhi
    Contributor

    Compare:

    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    poly_same_valinit = ax.axvspan(0, 0, 0, 1)
    poly_diff_valinit = ax.axvspan(0, .5, 0, 1)
    print(poly_same_valinit.xy.shape)
    print(poly_diff_valinit.xy.shape)

    which gives:

    (4, 2)
    (5, 2)
    
  6. ianhi commented on Mar 23, 2022

    @ianhi
    Contributor

    Two solutions spring to mind:

    1. Easier option
      Throw an error in init if valinit[0] == valinit[1]

    2. Maybe better option?
      Don't use axhspan and manually create the poly to ensure it always has the expected number of vertices

  7. vpicouet commented on Mar 23, 2022

    @vpicouet
    Author

    Option 2 might be better yes

  8. ianhi commented on Mar 23, 2022

    @ianhi
    Contributor

    @vpicouet any interest in opening a PR?

  9. added
    🌱 Good first issueOpen a pull request against these issues if there are no active ones!
    on Mar 23, 2022
  10. vpicouet commented on Mar 25, 2022

    @vpicouet
    Author

    I don't think I am qualified to do so, never opened a PR yet.
    RangeSlider might also contain another issue.
    When I call RangeSlider.set_val([0.0,0.1])
    It changes only the blue poly object and the range value on the right side of the slider not the dot:
    Capture d’écran, le 2022-03-25 à 15 53 44

  11. ianhi commented on Mar 25, 2022

    @ianhi
    Contributor

    I don't think I am qualified to do so, never opened a PR yet.

    That's always true until you've opened your first one :). But I also understand that it can be intimidating.

    RangeSlider might also contain another issue.
    When I call RangeSlider.set_val([0.0,0.1])
    It changes only the blue poly object and the range value on the right side of the slider not the dot:

    oh hmm - good catch! may be worth opening a separate issue there as these are two distinct bugs and this one may be a bit more comlicated to fix.

  12. vpicouet commented on Mar 25, 2022

    @vpicouet
    Author

    Haha true! I might try when I have more time!
    Throwing an error at least as I have never worked with axhspan and polys.
    Ok, openning another issue.

  13. nik1097 commented on Mar 26, 2022

    @nik1097

    Can I try working on this? @ianhi @vpicouet
    From the discussion, I could identify that a quick fix would be to use a try-except block to throw an error
    if valinit[0] == valinit[1]

    Please let me know your thoughts.

  14. vpicouet commented on Mar 26, 2022

    @vpicouet
    Author

    Sure!

  15. 4 remaining items

  16. AnnaMastori commented on Apr 1, 2022

    @AnnaMastori
    Contributor

    Is someone still working on this ?

  17. nik1097 commented on Apr 1, 2022

    @nik1097

    I still am but I'm currently caught up with another project. Feel free to give it a shot, thanks! @AnnaMastori

  18. NickolasGiannatos commented on Apr 27, 2022

    @NickolasGiannatos
    Contributor

    should this be the expected outcome of the solution?
    Στιγμιότυπο οθόνης (104)

  19. ianhi commented on Apr 27, 2022

    @ianhi
    Contributor

    @NickolasGiannatos that looks like the correct starting position if you give an init value of (0, 0). The next things to check are that it looks correct when you move the slider around, and that it looks correct with init values like (.3, .5)

  20. AnnaMastori commented on Apr 27, 2022

    @AnnaMastori
    Contributor

    @ianhi Me and @NickolasGiannatos work together. It works for (.3, .5). Is there anything else that we should try ?
    Στιγμιότυπο οθόνης (107)

  21. ianhi commented on Apr 27, 2022

    @ianhi
    Contributor

    @AnnaMastori @NickolasGiannatos can you please open a PR with your changes? It makes it much easier to discuss if we can all look at the same code.

  22. NickolasGiannatos commented on Apr 27, 2022

    @NickolasGiannatos
    Contributor

    okay we will do it as soon as possible although it's our first time so there might be mistakes.

  23. ianhi commented on Apr 27, 2022

    @ianhi
    Contributor

    our first time so there might be mistakes.

    That's fine! I had lots of mistakes my first time

  24. added a commit that references this issue on May 8, 2022
    bed2362
  25. modified the milestones: v3.5.2, v3.6.0 on May 9, 2022
  26. changed the title [-][Bug]: can not give init value for RangeSlider widget[/-] [+][Bug]: cannot give init value for RangeSlider widget[/+] on Apr 10, 2023
  27. added a commit that references this issue on Apr 19, 2026
    4eba104
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions