%matplotlib ipympl
import ipywidgets as widgets
import matplotlib.pyplot as plt
import numpy as np
%load_ext autoreload
%autoreload 2
from mpl_interactions import *
fig, ax = plt.subplots()
def y(heck):
return heck
def xmin(heck):
return heck
# controls = interactive_axhline(y,0,1, heck=(0,1))
controls = interactive_axhline(y,xmin,1, heck=(0,1))
# ret.set_ydata([.5,1])
Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …
VBox(children=(HBox(children=(IntSlider(value=0, description='heck', max=49, readout=False), Label(value='0.00…
plt.axhline()
def interactive_axhline(
y=0,
xmin=0,
xmax=1,
ax=None,
slider_formats=None,
title=None,
force_ipywidgets=False,
play_buttons=False,
play_button_pos="right",
controls=None,
display_controls=True,
**kwargs,
):
"""
Control an horizontal line using widgets.
parameters
----------
y : float or function
y position in data coordinates of the horizontal line.
xmin : float or function
Should be between 0 and 1, 0 being the far left of the plot, 1 the
far right of the plot.
xmax : float or function
Should be between 0 and 1, 0 being the far left of the plot, 1 the
far right of the plot.
ax : matplotlib axis, optional
If None a new figure and axis will be created
slider_formats : None, string, or dict
If None a default value of decimal points will be used. Uses the new {} style formatting
force_ipywidgets : boolean
If True ipywidgets will always be used, even if not using the ipympl backend.
If False the function will try to detect if it is ok to use ipywidgets
If ipywidgets are not used the function will fall back on matplotlib widgets
play_buttons : bool or dict, optional
Whether to attach an ipywidgets.Play widget to any sliders that get created.
If a boolean it will apply to all kwargs, if a dictionary you choose which sliders you
want to attach play buttons too.
play_button_pos : str, or dict, or list(str)
'left' or 'right'. Whether to position the play widget(s) to the left or right of the slider(s)
controls : mpl_interactions.controller.Controls
An existing controls object if you want to tie multiple plot elements to the same set of
controls
display_controls : boolean
Whether the controls should display on creation. Ignored if controls is specified.
returns
-------
controls
"""
ipympl = notebook_backend()
fig, ax = gogogo_figure(ipympl, ax)
use_ipywidgets = ipympl or force_ipywidgets
slider_formats = create_slider_format_dict(slider_formats)
controls, params = gogogo_controls(
kwargs, controls, display_controls, slider_formats, play_buttons, play_button_pos
)
def update(params, indices, cache):
if title is not None:
ax.set_title(title.format(**params))
y_ = callable_else_value(y, params, cache).item()
line.set_ydata([y_, y_])
xmin_ = callable_else_value(xmin, params, cache).item()
xmax_ = callable_else_value(xmax, params, cache).item()
line.set_xdata([xmin_, xmax_])
# TODO consider updating just the ydatalim here
controls.register_function(update, fig, params)
line = ax.axhline(
callable_else_value(y, params).item(),
callable_else_value(xmin, params).item(),
callable_else_value(xmax, params).item(),
)
return controls
def interactive_axvline(
x=0,
ymin=0,
ymax=1,
ax=None,
slider_formats=None,
title=None,
force_ipywidgets=False,
play_buttons=False,
play_button_pos="right",
controls=None,
display_controls=True,
**kwargs,
):
ipympl = notebook_backend()
fig, ax = gogogo_figure(ipympl, ax)
use_ipywidgets = ipympl or force_ipywidgets
slider_formats = create_slider_format_dict(slider_formats)
controls, params = gogogo_controls(
kwargs, controls, display_controls, slider_formats, play_buttons, play_button_pos
)
def update(params, indices, cache):
if title is not None:
ax.set_title(title.format(**params))
x_ = callable_else_value(x, params, cache).item()
line.set_ydata([x_, x_])
ymin_ = callable_else_value(ymin, params, cache).item()
ymax_ = callable_else_value(ymax, params, cache).item()
line.set_xdata([ymin_, ymax_])
# TODO consider updating just the ydatalim here
controls.register_function(update, fig, params)
line = ax.axvline(
callable_else_value(x, params).item(),
callable_else_value(ymin, params).item(),
callable_else_value(ymax, params).item(),
)
return controls
ret.set_ydata([0.5, 1])
ret = ax.axhline(0,np.array(0),1)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-14-748f618dad05> in <module> ----> 1 ret = ax.axhline(0,np.array(0),1) ~/Documents/jupyter/matplotlib/lib/matplotlib/axes/_axes.py in axhline(self, y, xmin, xmax, **kwargs) 703 >>> axhline(y=.5, xmin=0.25, xmax=0.75) 704 """ --> 705 self._check_no_units([xmin, xmax], ['xmin', 'xmax']) 706 if "transform" in kwargs: 707 raise ValueError("'transform' is not allowed as a keyword " ~/Documents/jupyter/matplotlib/lib/matplotlib/axes/_axes.py in _check_no_units(vals, names) 791 for val, name in zip(vals, names): 792 if not munits._is_natively_supported(val): --> 793 raise ValueError(f"{name} must be a single scalar value, " 794 f"but got {val}") 795 ValueError: xmin must be a single scalar value, but got 0
arr = np.array(0)
arr.item()
0
np.asscalar(arr)
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-12-d3e0db857085> in <module> ----> 1 arr[0] IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed
ret.set_xdata([0,1.5])
def axhline(y=0, xmin=0, xmax=1):
Signature: ax.axhline(y=0, xmin=0, xmax=1, **kwargs) Docstring: Add a horizontal line across the axis. Parameters ---------- y : float, default: 0 y position in data coordinates of the horizontal line. xmin : float, default: 0 Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot. xmax : float, default: 1 Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot. Returns ------- `~matplotlib.lines.Line2D` Other Parameters ---------------- **kwargs Valid keyword arguments are `.Line2D` properties, with the exception of 'transform': Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha: scalar or None animated: bool antialiased or aa: bool clip_box: `.Bbox` clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: {'butt', 'round', 'projecting'} dash_joinstyle: {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: `.Figure` fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style string, `~.path.Path` or `~.markers.MarkerStyle` markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or List[int] or float or (float, float) or List[bool] path_effects: `.AbstractPathEffect` picker: unknown pickradius: float rasterized: bool or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: {'butt', 'round', 'projecting'} solid_joinstyle: {'miter', 'round', 'bevel'} transform: `matplotlib.transforms.Transform` url: str visible: bool xdata: 1D array ydata: 1D array zorder: float See Also -------- hlines : Add horizontal lines in data coordinates. axhspan : Add a horizontal span (rectangle) across the axis. axline : Add a line with an arbitrary slope. Examples -------- * draw a thick red hline at 'y' = 0 that spans the xrange:: >>> axhline(linewidth=4, color='r') * draw a default hline at 'y' = 1 that spans the xrange:: >>> axhline(y=1) * draw a default hline at 'y' = .5 that spans the middle half of the xrange:: >>> axhline(y=.5, xmin=0.25, xmax=0.75) Source: @docstring.dedent_interpd def axhline(self, y=0, xmin=0, xmax=1, **kwargs): """ Add a horizontal line across the axis. Parameters ---------- y : float, default: 0 y position in data coordinates of the horizontal line. xmin : float, default: 0 Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot. xmax : float, default: 1 Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot. Returns ------- `~matplotlib.lines.Line2D` Other Parameters ---------------- **kwargs Valid keyword arguments are `.Line2D` properties, with the exception of 'transform': %(_Line2D_docstr)s See Also -------- hlines : Add horizontal lines in data coordinates. axhspan : Add a horizontal span (rectangle) across the axis. axline : Add a line with an arbitrary slope. Examples -------- * draw a thick red hline at 'y' = 0 that spans the xrange:: >>> axhline(linewidth=4, color='r') * draw a default hline at 'y' = 1 that spans the xrange:: >>> axhline(y=1) * draw a default hline at 'y' = .5 that spans the middle half of the xrange:: >>> axhline(y=.5, xmin=0.25, xmax=0.75) """ self._check_no_units([xmin, xmax], ['xmin', 'xmax']) if "transform" in kwargs: raise ValueError("'transform' is not allowed as a keyword " "argument; axhline generates its own transform.") ymin, ymax = self.get_ybound() # Strip away the units for comparison with non-unitized bounds. yy, = self._process_unit_info([("y", y)], kwargs) scaley = (yy < ymin) or (yy > ymax) trans = self.get_yaxis_transform(which='grid') l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs) self.add_line(l) self._request_autoscale_view(scalex=False, scaley=scaley) return l File: ~/Documents/jupyter/matplotlib/lib/matplotlib/axes/_axes.py Type: method
ret.get_ydata()
[0, 1]