mirror of
https://github.com/Estom/notes.git
synced 2026-04-01 18:11:42 +08:00
matplotlib & pandas
This commit is contained in:
54
Python/matplotlab/gallery/widgets/buttons.md
Normal file
54
Python/matplotlab/gallery/widgets/buttons.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# 按钮
|
||||
|
||||
构建一个简单的按钮GUI来修改正弦波。
|
||||
|
||||
``下一个``和``上一个``按钮小部件有助于以新频率显示波形。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.widgets import Button
|
||||
|
||||
freqs = np.arange(2, 20, 3)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
plt.subplots_adjust(bottom=0.2)
|
||||
t = np.arange(0.0, 1.0, 0.001)
|
||||
s = np.sin(2*np.pi*freqs[0]*t)
|
||||
l, = plt.plot(t, s, lw=2)
|
||||
|
||||
|
||||
class Index(object):
|
||||
ind = 0
|
||||
|
||||
def next(self, event):
|
||||
self.ind += 1
|
||||
i = self.ind % len(freqs)
|
||||
ydata = np.sin(2*np.pi*freqs[i]*t)
|
||||
l.set_ydata(ydata)
|
||||
plt.draw()
|
||||
|
||||
def prev(self, event):
|
||||
self.ind -= 1
|
||||
i = self.ind % len(freqs)
|
||||
ydata = np.sin(2*np.pi*freqs[i]*t)
|
||||
l.set_ydata(ydata)
|
||||
plt.draw()
|
||||
|
||||
callback = Index()
|
||||
axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
|
||||
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
|
||||
bnext = Button(axnext, 'Next')
|
||||
bnext.on_clicked(callback.next)
|
||||
bprev = Button(axprev, 'Previous')
|
||||
bprev.on_clicked(callback.prev)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: buttons.py](https://matplotlib.org/_downloads/buttons.py)
|
||||
- [下载Jupyter notebook: buttons.ipynb](https://matplotlib.org/_downloads/buttons.ipynb)
|
||||
47
Python/matplotlab/gallery/widgets/check_buttons.md
Normal file
47
Python/matplotlab/gallery/widgets/check_buttons.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# 复选按钮
|
||||
|
||||
使用复选按钮打开和关闭视觉元素。
|
||||
|
||||
该程序显示了“检查按钮”的使用,类似于复选框。 显示了3种不同的正弦波,我们可以选择使用复选按钮显示哪些波形。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.widgets import CheckButtons
|
||||
|
||||
t = np.arange(0.0, 2.0, 0.01)
|
||||
s0 = np.sin(2*np.pi*t)
|
||||
s1 = np.sin(4*np.pi*t)
|
||||
s2 = np.sin(6*np.pi*t)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
l0, = ax.plot(t, s0, visible=False, lw=2, color='k', label='2 Hz')
|
||||
l1, = ax.plot(t, s1, lw=2, color='r', label='4 Hz')
|
||||
l2, = ax.plot(t, s2, lw=2, color='g', label='6 Hz')
|
||||
plt.subplots_adjust(left=0.2)
|
||||
|
||||
lines = [l0, l1, l2]
|
||||
|
||||
# Make checkbuttons with all plotted lines with correct visibility
|
||||
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
|
||||
labels = [str(line.get_label()) for line in lines]
|
||||
visibility = [line.get_visible() for line in lines]
|
||||
check = CheckButtons(rax, labels, visibility)
|
||||
|
||||
|
||||
def func(label):
|
||||
index = labels.index(label)
|
||||
lines[index].set_visible(not lines[index].get_visible())
|
||||
plt.draw()
|
||||
|
||||
check.on_clicked(func)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: check_buttons.py](https://matplotlib.org/_downloads/check_buttons.py)
|
||||
- [下载Jupyter notebook: check_buttons.ipynb](https://matplotlib.org/_downloads/check_buttons.ipynb)
|
||||
31
Python/matplotlab/gallery/widgets/cursor.md
Normal file
31
Python/matplotlab/gallery/widgets/cursor.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# 光标
|
||||
|
||||

|
||||
|
||||
```python
|
||||
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)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: cursor.py](https://matplotlib.org/_downloads/cursor.py)
|
||||
- [下载Jupyter notebook: cursor.ipynb](https://matplotlib.org/_downloads/cursor.ipynb)
|
||||
3
Python/matplotlab/gallery/widgets/index.md
Normal file
3
Python/matplotlab/gallery/widgets/index.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# 小部件
|
||||
|
||||
如何在matplotlib中编写原始的、但与GUI无关的小部件的示例
|
||||
102
Python/matplotlab/gallery/widgets/lasso_selector_demo_sgskip.md
Normal file
102
Python/matplotlab/gallery/widgets/lasso_selector_demo_sgskip.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# 套索选择器演示
|
||||
|
||||
使用套索工具以交互方式选择数据点。
|
||||
|
||||
此示例绘制散点图。 然后,您可以通过在图表上的点周围绘制套索循环来选择几个点。 要绘制,只需单击图形,按住,然后将其拖动到需要选择的点周围。
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
from matplotlib.widgets import LassoSelector
|
||||
from matplotlib.path import Path
|
||||
|
||||
|
||||
class SelectFromCollection(object):
|
||||
"""Select indices from a matplotlib collection using `LassoSelector`.
|
||||
|
||||
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.lasso = LassoSelector(ax, onselect=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.lasso.disconnect_events()
|
||||
self.fc[:, -1] = 1
|
||||
self.collection.set_facecolors(self.fc)
|
||||
self.canvas.draw_idle()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
data = np.random.rand(100, 2)
|
||||
|
||||
subplot_kw = dict(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
|
||||
fig, ax = plt.subplots(subplot_kw=subplot_kw)
|
||||
|
||||
pts = ax.scatter(data[:, 0], data[:, 1], s=80)
|
||||
selector = SelectFromCollection(ax, pts)
|
||||
|
||||
def accept(event):
|
||||
if event.key == "enter":
|
||||
print("Selected points:")
|
||||
print(selector.xys[selector.ind])
|
||||
selector.disconnect()
|
||||
ax.set_title("")
|
||||
fig.canvas.draw()
|
||||
|
||||
fig.canvas.mpl_connect("key_press_event", accept)
|
||||
ax.set_title("Press enter to accept selected points.")
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: lasso_selector_demo_sgskip.py](https://matplotlib.org/_downloads/lasso_selector_demo_sgskip.py)
|
||||
- [下载Jupyter notebook: lasso_selector_demo_sgskip.ipynb](https://matplotlib.org/_downloads/lasso_selector_demo_sgskip.ipynb)
|
||||
194
Python/matplotlab/gallery/widgets/menu.md
Normal file
194
Python/matplotlab/gallery/widgets/menu.md
Normal file
@@ -0,0 +1,194 @@
|
||||
# 菜单
|
||||
|
||||

|
||||
|
||||
输出:
|
||||
|
||||
```python
|
||||
100 371 91 29
|
||||
100 342 91 29
|
||||
100 313 91 29
|
||||
100 284 91 29
|
||||
100 255 91 29
|
||||
```
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.colors as colors
|
||||
import matplotlib.patches as patches
|
||||
import matplotlib.mathtext as mathtext
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.artist as artist
|
||||
import matplotlib.image as image
|
||||
|
||||
|
||||
class ItemProperties(object):
|
||||
def __init__(self, fontsize=14, labelcolor='black', bgcolor='yellow',
|
||||
alpha=1.0):
|
||||
self.fontsize = fontsize
|
||||
self.labelcolor = labelcolor
|
||||
self.bgcolor = bgcolor
|
||||
self.alpha = alpha
|
||||
|
||||
self.labelcolor_rgb = colors.to_rgba(labelcolor)[:3]
|
||||
self.bgcolor_rgb = colors.to_rgba(bgcolor)[:3]
|
||||
|
||||
|
||||
class MenuItem(artist.Artist):
|
||||
parser = mathtext.MathTextParser("Bitmap")
|
||||
padx = 5
|
||||
pady = 5
|
||||
|
||||
def __init__(self, fig, labelstr, props=None, hoverprops=None,
|
||||
on_select=None):
|
||||
artist.Artist.__init__(self)
|
||||
|
||||
self.set_figure(fig)
|
||||
self.labelstr = labelstr
|
||||
|
||||
if props is None:
|
||||
props = ItemProperties()
|
||||
|
||||
if hoverprops is None:
|
||||
hoverprops = ItemProperties()
|
||||
|
||||
self.props = props
|
||||
self.hoverprops = hoverprops
|
||||
|
||||
self.on_select = on_select
|
||||
|
||||
x, self.depth = self.parser.to_mask(
|
||||
labelstr, fontsize=props.fontsize, dpi=fig.dpi)
|
||||
|
||||
if props.fontsize != hoverprops.fontsize:
|
||||
raise NotImplementedError(
|
||||
'support for different font sizes not implemented')
|
||||
|
||||
self.labelwidth = x.shape[1]
|
||||
self.labelheight = x.shape[0]
|
||||
|
||||
self.labelArray = np.zeros((x.shape[0], x.shape[1], 4))
|
||||
self.labelArray[:, :, -1] = x/255.
|
||||
|
||||
self.label = image.FigureImage(fig, origin='upper')
|
||||
self.label.set_array(self.labelArray)
|
||||
|
||||
# we'll update these later
|
||||
self.rect = patches.Rectangle((0, 0), 1, 1)
|
||||
|
||||
self.set_hover_props(False)
|
||||
|
||||
fig.canvas.mpl_connect('button_release_event', self.check_select)
|
||||
|
||||
def check_select(self, event):
|
||||
over, junk = self.rect.contains(event)
|
||||
if not over:
|
||||
return
|
||||
|
||||
if self.on_select is not None:
|
||||
self.on_select(self)
|
||||
|
||||
def set_extent(self, x, y, w, h):
|
||||
print(x, y, w, h)
|
||||
self.rect.set_x(x)
|
||||
self.rect.set_y(y)
|
||||
self.rect.set_width(w)
|
||||
self.rect.set_height(h)
|
||||
|
||||
self.label.ox = x + self.padx
|
||||
self.label.oy = y - self.depth + self.pady/2.
|
||||
|
||||
self.hover = False
|
||||
|
||||
def draw(self, renderer):
|
||||
self.rect.draw(renderer)
|
||||
self.label.draw(renderer)
|
||||
|
||||
def set_hover_props(self, b):
|
||||
if b:
|
||||
props = self.hoverprops
|
||||
else:
|
||||
props = self.props
|
||||
|
||||
r, g, b = props.labelcolor_rgb
|
||||
self.labelArray[:, :, 0] = r
|
||||
self.labelArray[:, :, 1] = g
|
||||
self.labelArray[:, :, 2] = b
|
||||
self.label.set_array(self.labelArray)
|
||||
self.rect.set(facecolor=props.bgcolor, alpha=props.alpha)
|
||||
|
||||
def set_hover(self, event):
|
||||
'check the hover status of event and return true if status is changed'
|
||||
b, junk = self.rect.contains(event)
|
||||
|
||||
changed = (b != self.hover)
|
||||
|
||||
if changed:
|
||||
self.set_hover_props(b)
|
||||
|
||||
self.hover = b
|
||||
return changed
|
||||
|
||||
|
||||
class Menu(object):
|
||||
def __init__(self, fig, menuitems):
|
||||
self.figure = fig
|
||||
fig.suppressComposite = True
|
||||
|
||||
self.menuitems = menuitems
|
||||
self.numitems = len(menuitems)
|
||||
|
||||
maxw = max(item.labelwidth for item in menuitems)
|
||||
maxh = max(item.labelheight for item in menuitems)
|
||||
|
||||
totalh = self.numitems*maxh + (self.numitems + 1)*2*MenuItem.pady
|
||||
|
||||
x0 = 100
|
||||
y0 = 400
|
||||
|
||||
width = maxw + 2*MenuItem.padx
|
||||
height = maxh + MenuItem.pady
|
||||
|
||||
for item in menuitems:
|
||||
left = x0
|
||||
bottom = y0 - maxh - MenuItem.pady
|
||||
|
||||
item.set_extent(left, bottom, width, height)
|
||||
|
||||
fig.artists.append(item)
|
||||
y0 -= maxh + MenuItem.pady
|
||||
|
||||
fig.canvas.mpl_connect('motion_notify_event', self.on_move)
|
||||
|
||||
def on_move(self, event):
|
||||
draw = False
|
||||
for item in self.menuitems:
|
||||
draw = item.set_hover(event)
|
||||
if draw:
|
||||
self.figure.canvas.draw()
|
||||
break
|
||||
|
||||
|
||||
fig = plt.figure()
|
||||
fig.subplots_adjust(left=0.3)
|
||||
props = ItemProperties(labelcolor='black', bgcolor='yellow',
|
||||
fontsize=15, alpha=0.2)
|
||||
hoverprops = ItemProperties(labelcolor='white', bgcolor='blue',
|
||||
fontsize=15, alpha=0.2)
|
||||
|
||||
menuitems = []
|
||||
for label in ('open', 'close', 'save', 'save as', 'quit'):
|
||||
def on_select(item):
|
||||
print('you selected %s' % item.labelstr)
|
||||
item = MenuItem(fig, label, props=props, hoverprops=hoverprops,
|
||||
on_select=on_select)
|
||||
menuitems.append(item)
|
||||
|
||||
menu = Menu(fig, menuitems)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: menu.py](https://matplotlib.org/_downloads/menu.py)
|
||||
- [下载Jupyter notebook: menu.ipynb](https://matplotlib.org/_downloads/menu.ipynb)
|
||||
29
Python/matplotlab/gallery/widgets/multicursor.md
Normal file
29
Python/matplotlab/gallery/widgets/multicursor.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# 多光标
|
||||
|
||||
同时在多个图上显示光标。
|
||||
|
||||
此示例生成两个子图,并将光标悬停在一个子图中的数据上,该数据点的值分别显示在两个子图中。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.widgets import MultiCursor
|
||||
|
||||
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)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: multicursor.py](https://matplotlib.org/_downloads/multicursor.py)
|
||||
- [下载Jupyter notebook: multicursor.ipynb](https://matplotlib.org/_downloads/multicursor.ipynb)
|
||||
111
Python/matplotlab/gallery/widgets/polygon_selector_demo.md
Normal file
111
Python/matplotlab/gallery/widgets/polygon_selector_demo.md
Normal file
@@ -0,0 +1,111 @@
|
||||
# 多边形选择器演示
|
||||
|
||||
显示如何以交互方式选择多边形的索引。
|
||||
|
||||

|
||||
|
||||
输出:
|
||||
|
||||
```python
|
||||
Select points in the figure by enclosing them within a polygon.
|
||||
Press the 'esc' key to start a new polygon.
|
||||
Try holding the 'shift' key to move all of the vertices.
|
||||
Try holding the 'ctrl' key to move a single vertex.
|
||||
|
||||
Selected points:
|
||||
[]
|
||||
```
|
||||
|
||||
```python
|
||||
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.")
|
||||
|
||||
plt.show()
|
||||
|
||||
selector.disconnect()
|
||||
|
||||
# After figure is closed print the coordinates of the selected points
|
||||
print('\nSelected points:')
|
||||
print(selector.xys[selector.ind])
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: polygon_selector_demo.py](https://matplotlib.org/_downloads/polygon_selector_demo.py)
|
||||
- [下载Jupyter notebook: polygon_selector_demo.ipynb](https://matplotlib.org/_downloads/polygon_selector_demo.ipynb)
|
||||
59
Python/matplotlab/gallery/widgets/radio_buttons.md
Normal file
59
Python/matplotlab/gallery/widgets/radio_buttons.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# 单选按钮
|
||||
|
||||
使用单选按钮选择绘图的属性。
|
||||
|
||||
单选按钮允许您在可视化中选择多个选项。在这种情况下,按钮允许用户选择要在图中显示的三种不同正弦波中的一种。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.widgets import RadioButtons
|
||||
|
||||
t = np.arange(0.0, 2.0, 0.01)
|
||||
s0 = np.sin(2*np.pi*t)
|
||||
s1 = np.sin(4*np.pi*t)
|
||||
s2 = np.sin(8*np.pi*t)
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
l, = ax.plot(t, s0, lw=2, color='red')
|
||||
plt.subplots_adjust(left=0.3)
|
||||
|
||||
axcolor = 'lightgoldenrodyellow'
|
||||
rax = plt.axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor)
|
||||
radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz'))
|
||||
|
||||
|
||||
def hzfunc(label):
|
||||
hzdict = {'2 Hz': s0, '4 Hz': s1, '8 Hz': s2}
|
||||
ydata = hzdict[label]
|
||||
l.set_ydata(ydata)
|
||||
plt.draw()
|
||||
radio.on_clicked(hzfunc)
|
||||
|
||||
rax = plt.axes([0.05, 0.4, 0.15, 0.15], facecolor=axcolor)
|
||||
radio2 = RadioButtons(rax, ('red', 'blue', 'green'))
|
||||
|
||||
|
||||
def colorfunc(label):
|
||||
l.set_color(label)
|
||||
plt.draw()
|
||||
radio2.on_clicked(colorfunc)
|
||||
|
||||
rax = plt.axes([0.05, 0.1, 0.15, 0.15], facecolor=axcolor)
|
||||
radio3 = RadioButtons(rax, ('-', '--', '-.', 'steps', ':'))
|
||||
|
||||
|
||||
def stylefunc(label):
|
||||
l.set_linestyle(label)
|
||||
plt.draw()
|
||||
radio3.on_clicked(stylefunc)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: radio_buttons.py](https://matplotlib.org/_downloads/radio_buttons.py)
|
||||
- [下载Jupyter notebook: radio_buttons.ipynb](https://matplotlib.org/_downloads/radio_buttons.ipynb)
|
||||
61
Python/matplotlab/gallery/widgets/rectangle_selector.md
Normal file
61
Python/matplotlab/gallery/widgets/rectangle_selector.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# 矩形选择器
|
||||
|
||||
在某处鼠标点击,将鼠标移动到某个目的地,然后释放按钮。 此类提供单击和释放事件,并从点击点到实际鼠标位置(在相同轴内)绘制一条线或一个框,直到释放按钮。 在方法'self.ignore()'中,检查来自eventpress和eventrelease的按钮是否相同。
|
||||
|
||||

|
||||
|
||||
输出:
|
||||
|
||||
```python
|
||||
click --> release
|
||||
```
|
||||
|
||||
```python
|
||||
from matplotlib.widgets import RectangleSelector
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def line_select_callback(eclick, erelease):
|
||||
'eclick and erelease are the press and release events'
|
||||
x1, y1 = eclick.xdata, eclick.ydata
|
||||
x2, y2 = erelease.xdata, erelease.ydata
|
||||
print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2))
|
||||
print(" The button you used were: %s %s" % (eclick.button, erelease.button))
|
||||
|
||||
|
||||
def toggle_selector(event):
|
||||
print(' Key pressed.')
|
||||
if event.key in ['Q', 'q'] and toggle_selector.RS.active:
|
||||
print(' RectangleSelector deactivated.')
|
||||
toggle_selector.RS.set_active(False)
|
||||
if event.key in ['A', 'a'] and not toggle_selector.RS.active:
|
||||
print(' RectangleSelector activated.')
|
||||
toggle_selector.RS.set_active(True)
|
||||
|
||||
|
||||
fig, current_ax = plt.subplots() # make a new plotting range
|
||||
N = 100000 # If N is large one can see
|
||||
x = np.linspace(0.0, 10.0, N) # improvement by use blitting!
|
||||
|
||||
plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something
|
||||
plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5)
|
||||
plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3)
|
||||
|
||||
print("\n click --> release")
|
||||
|
||||
# drawtype is 'box' or 'line' or 'none'
|
||||
toggle_selector.RS = RectangleSelector(current_ax, line_select_callback,
|
||||
drawtype='box', useblit=True,
|
||||
button=[1, 3], # don't use middle button
|
||||
minspanx=5, minspany=5,
|
||||
spancoords='pixels',
|
||||
interactive=True)
|
||||
plt.connect('key_press_event', toggle_selector)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: rectangle_selector.py](https://matplotlib.org/_downloads/rectangle_selector.py)
|
||||
- [下载Jupyter notebook: rectangle_selector.ipynb](https://matplotlib.org/_downloads/rectangle_selector.ipynb)
|
||||
64
Python/matplotlab/gallery/widgets/slider_demo.md
Normal file
64
Python/matplotlab/gallery/widgets/slider_demo.md
Normal file
@@ -0,0 +1,64 @@
|
||||
# 滑块演示
|
||||
|
||||
使用滑块小部件来控制绘图的可视属性。
|
||||
|
||||
在此示例中,滑块用于选择正弦波的频率。 您可以通过这种方式控制绘图的许多连续变化属性。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.widgets import Slider, Button, RadioButtons
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
plt.subplots_adjust(left=0.25, bottom=0.25)
|
||||
t = np.arange(0.0, 1.0, 0.001)
|
||||
a0 = 5
|
||||
f0 = 3
|
||||
delta_f = 5.0
|
||||
s = a0*np.sin(2*np.pi*f0*t)
|
||||
l, = plt.plot(t, s, lw=2, color='red')
|
||||
plt.axis([0, 1, -10, 10])
|
||||
|
||||
axcolor = 'lightgoldenrodyellow'
|
||||
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
|
||||
axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
|
||||
|
||||
sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0, valstep=delta_f)
|
||||
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
|
||||
|
||||
|
||||
def update(val):
|
||||
amp = samp.val
|
||||
freq = sfreq.val
|
||||
l.set_ydata(amp*np.sin(2*np.pi*freq*t))
|
||||
fig.canvas.draw_idle()
|
||||
sfreq.on_changed(update)
|
||||
samp.on_changed(update)
|
||||
|
||||
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
|
||||
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
|
||||
|
||||
|
||||
def reset(event):
|
||||
sfreq.reset()
|
||||
samp.reset()
|
||||
button.on_clicked(reset)
|
||||
|
||||
rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
|
||||
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
|
||||
|
||||
|
||||
def colorfunc(label):
|
||||
l.set_color(label)
|
||||
fig.canvas.draw_idle()
|
||||
radio.on_clicked(colorfunc)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: slider_demo.py](https://matplotlib.org/_downloads/slider_demo.py)
|
||||
- [下载Jupyter notebook: slider_demo.ipynb](https://matplotlib.org/_downloads/slider_demo.ipynb)
|
||||
51
Python/matplotlab/gallery/widgets/span_selector.md
Normal file
51
Python/matplotlab/gallery/widgets/span_selector.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# 跨度选择器
|
||||
|
||||
SpanSelector是一个鼠标小部件,用于选择xmin / xmax范围并绘制下轴中所选区域的详细视图
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.widgets import SpanSelector
|
||||
|
||||
# Fixing random state for reproducibility
|
||||
np.random.seed(19680801)
|
||||
|
||||
fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6))
|
||||
ax1.set(facecolor='#FFFFCC')
|
||||
|
||||
x = np.arange(0.0, 5.0, 0.01)
|
||||
y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))
|
||||
|
||||
ax1.plot(x, y, '-')
|
||||
ax1.set_ylim(-2, 2)
|
||||
ax1.set_title('Press left mouse button and drag to test')
|
||||
|
||||
ax2.set(facecolor='#FFFFCC')
|
||||
line2, = ax2.plot(x, y, '-')
|
||||
|
||||
|
||||
def onselect(xmin, xmax):
|
||||
indmin, indmax = np.searchsorted(x, (xmin, xmax))
|
||||
indmax = min(len(x) - 1, indmax)
|
||||
|
||||
thisx = x[indmin:indmax]
|
||||
thisy = y[indmin:indmax]
|
||||
line2.set_data(thisx, thisy)
|
||||
ax2.set_xlim(thisx[0], thisx[-1])
|
||||
ax2.set_ylim(thisy.min(), thisy.max())
|
||||
fig.canvas.draw()
|
||||
|
||||
# Set useblit=True on most backends for enhanced performance.
|
||||
span = SpanSelector(ax1, onselect, 'horizontal', useblit=True,
|
||||
rectprops=dict(alpha=0.5, facecolor='red'))
|
||||
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: span_selector.py](https://matplotlib.org/_downloads/span_selector.py)
|
||||
- [下载Jupyter notebook: span_selector.ipynb](https://matplotlib.org/_downloads/span_selector.ipynb)
|
||||
37
Python/matplotlab/gallery/widgets/textbox.md
Normal file
37
Python/matplotlab/gallery/widgets/textbox.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# 文本框
|
||||
|
||||
允许使用Textbox小部件输入文本。
|
||||
|
||||
您可以使用“文本框”小部件让用户提供需要显示的任何文本,包括公式。 您可以使用提交按钮创建具有给定输入的绘图。
|
||||
|
||||

|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.widgets import TextBox
|
||||
fig, ax = plt.subplots()
|
||||
plt.subplots_adjust(bottom=0.2)
|
||||
t = np.arange(-2.0, 2.0, 0.001)
|
||||
s = t ** 2
|
||||
initial_text = "t ** 2"
|
||||
l, = plt.plot(t, s, lw=2)
|
||||
|
||||
|
||||
def submit(text):
|
||||
ydata = eval(text)
|
||||
l.set_ydata(ydata)
|
||||
ax.set_ylim(np.min(ydata), np.max(ydata))
|
||||
plt.draw()
|
||||
|
||||
axbox = plt.axes([0.1, 0.05, 0.8, 0.075])
|
||||
text_box = TextBox(axbox, 'Evaluate', initial=initial_text)
|
||||
text_box.on_submit(submit)
|
||||
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 下载这个示例
|
||||
|
||||
- [下载python源码: textbox.py](https://matplotlib.org/_downloads/textbox.py)
|
||||
- [下载Jupyter notebook: textbox.ipynb](https://matplotlib.org/_downloads/textbox.ipynb)
|
||||
Reference in New Issue
Block a user