%matplotlib widget
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import MultiCursor
import ipywidgets as widgets
from IPython.display import display, Markdown, HTML, Image
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
ax1.plot(t, s1)
ax2.plot(t, s2)
multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1)
# When using the `widget` backend from ipympl,
# fig.canvas is a proper Jupyter interactive widget, which can be embedded in
# Layout classes like HBox and Vbox.
# One can bound figure attributes to other widget values.
from ipywidgets import HBox, FloatSlider
#plt.ioff()
plt.clf()
slider = FloatSlider(
orientation='vertical',
value=1.0,
min=0.02,
max=2.0
)
fig = plt.figure(3)
x = np.linspace(0, 20, 500)
lines = plt.plot(x, np.sin(slider.value * x))
def update_lines(change):
lines[0].set_data(x, np.sin(change.new * x))
fig.canvas.draw()
fig.canvas.flush_events()
slider.observe(update_lines, names='value')
HBox([slider, fig.canvas])
out1 = widgets.Output()
out2 = widgets.Output()
display(out1)
display(out2)
with out1:
plt.plot(t, s1)
with out2:
plt.plot(t, s2)
a = widgets.Output()
display(a)
fig, ax1 = plt.subplots()
with a:
display(HTML('coucou'))
ax1.plot(t, s1)
display(HTML('cuicui'))
display(a)
b = widgets.Output()
display(b)
fig, ax1 = plt.subplots()
with b:
display(HTML('cuicui'))
ax1.plot(t, s2)
with a:
display(ax1.plot(t, s1))
from matplotlib.widgets import Cursor
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, facecolor='#FFFFCC')
x, y = 4*(np.random.rand(2, 100) - .5)
ax.plot(x, y, 'o')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
# Set useblit=True on most backends for enhanced performance.
cursor = Cursor(ax, useblit=True, color='red', linewidth=2)
import numpy as np
from matplotlib.widgets import PolygonSelector
from matplotlib.path import Path
class SelectFromCollection(object):
"""Select indices from a matplotlib collection using `PolygonSelector`.
Selected indices are saved in the `ind` attribute. This tool fades out the
points that are not part of the selection (i.e., reduces their alpha
values). If your collection has alpha < 1, this tool will permanently
alter the alpha values.
Note that this tool selects collection objects based on their *origins*
(i.e., `offsets`).
Parameters
----------
ax : :class:`~matplotlib.axes.Axes`
Axes to interact with.
collection : :class:`matplotlib.collections.Collection` subclass
Collection you want to select from.
alpha_other : 0 <= float <= 1
To highlight a selection, this tool sets all selected points to an
alpha value of 1 and non-selected points to `alpha_other`.
"""
def __init__(self, ax, collection, alpha_other=0.3):
self.canvas = ax.figure.canvas
self.collection = collection
self.alpha_other = alpha_other
self.xys = collection.get_offsets()
self.Npts = len(self.xys)
# Ensure that we have separate colors for each object
self.fc = collection.get_facecolors()
if len(self.fc) == 0:
raise ValueError('Collection must have a facecolor')
elif len(self.fc) == 1:
self.fc = np.tile(self.fc, (self.Npts, 1))
self.poly = PolygonSelector(ax, self.onselect)
self.ind = []
def onselect(self, verts):
path = Path(verts)
self.ind = np.nonzero(path.contains_points(self.xys))[0]
self.fc[:, -1] = self.alpha_other
self.fc[self.ind, -1] = 1
self.collection.set_facecolors(self.fc)
self.canvas.draw_idle()
def disconnect(self):
self.poly.disconnect_events()
self.fc[:, -1] = 1
self.collection.set_facecolors(self.fc)
self.canvas.draw_idle()
if __name__ == '__main__':
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
grid_size = 5
grid_x = np.tile(np.arange(grid_size), grid_size)
grid_y = np.repeat(np.arange(grid_size), grid_size)
pts = ax.scatter(grid_x, grid_y)
selector = SelectFromCollection(ax, pts)
print("Select points in the figure by enclosing them within a polygon.")
print("Press the 'esc' key to start a new polygon.")
print("Try holding the 'shift' key to move all of the vertices.")
print("Try holding the 'ctrl' key to move a single vertex.")
selector.disconnect()
# After figure is closed print the coordinates of the selected points
print('\nSelected points:')
print(selector.xys[selector.ind])
import matplotlib.pyplot as plt
def on_pick(event):
artist = event.artist
xmouse, ymouse = event.mouseevent.xdata, event.mouseevent.ydata
x, y = artist.get_xdata(), artist.get_ydata()
ind = event.ind
print ('Artist picked:', event.artist)
print ('{} vertices picked'.format(len(ind)))
print ('Pick between vertices {} and {}'.format(min(ind), max(ind)+1))
print ('x, y of mouse: {:.2f},{:.2f}'.format(xmouse, ymouse))
print ('Data point:', x[ind[0]], y[ind[0]])
print()
fig, ax = plt.subplots()
tolerance = 10 # points
ax.plot(range(10), 'ro-', picker=tolerance)
fig.canvas.callbacks.connect('pick_event', on_pick)
fig, ax = plt.subplots()
ax.plot(np.random.rand(10))
def onclick(event):
print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
('double' if event.dblclick else 'single', event.button,
event.x, event.y, event.xdata, event.ydata))
ax.scatter(event.x, event.y, 'c')
cid = fig.canvas.mpl_connect('button_press_event', onclick)