Last active
April 17, 2016 04:10
-
-
Save icook/40dbcc6a63d7b2023cdb9f093c8c10df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# widgets example code: check_buttons.py | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from matplotlib.widgets import CheckButtons | |
class LabelWrapper(str): | |
def __new__(cls, graph, text): | |
s = str.__new__(cls, text) | |
s.graph = graph | |
return s | |
t = np.arange(0.0, 2.0, 0.01) | |
fig, ax = plt.subplots() | |
graphs = [] | |
labels = [] | |
for i in range(3): | |
hz = (i + 1) * 2 | |
values = np.sin(hz * np.pi * t) | |
label = '{} Hz'.format(hz) | |
graph = ax.plot(t, values, visible=True, lw=2, color='k', label=label) | |
graphs.extend(graph) | |
labels.append(label) | |
legend = ax.legend(loc='upper right', shadow=False) | |
plt.subplots_adjust(left=0.2) | |
# We can use index alignment between graphs and labels because we know | |
# CheckButtons preserves the order of labels that we pass it | |
rax = plt.axes([0.05, 0.4, 0.1, 0.15]) | |
check = CheckButtons(rax, labels, (True,) * len(labels)) | |
for i, label in enumerate(check.labels): | |
label._text = LabelWrapper(graphs[i], label._text) | |
print(label._text.graph) | |
# Then look just how elegant our callback is! And we don't have the problem of | |
# duplicate labels breaking things | |
def funcNew(clicked_label): | |
print(clicked_label.graph) | |
visible = clicked_label.graph.get_visible() | |
clicked_label.graph.set_visible(not visible) | |
plt.draw() | |
check.on_clicked(funcNew) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment