当前位置: 首页>>代码示例>>Python>>正文


Python CheckButtons.on_clicked方法代码示例

本文整理汇总了Python中matplotlib.widgets.CheckButtons.on_clicked方法的典型用法代码示例。如果您正苦于以下问题:Python CheckButtons.on_clicked方法的具体用法?Python CheckButtons.on_clicked怎么用?Python CheckButtons.on_clicked使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.widgets.CheckButtons的用法示例。


在下文中一共展示了CheckButtons.on_clicked方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _do_plot

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
    def _do_plot(self):
        stats = self._statistics.deserialize()
        metrics_to_plot = self._statistics.get_metrics_to_plot()
        subplots_count = len(stats)

        if not subplots_count:
            return

        fig, axarr = plt.subplots(subplots_count)
        fig.canvas.set_window_title(self._plot_title)

        time = range(len(stats[stats.keys()[0]]))
        axes_by_names = {}

        for i, key in enumerate(stats.keys()):
            axarr[i].plot(time, stats[key], label=metrics_to_plot[key].name, lw=1, color=COLORS[i])
            axarr[i].set_xlabel('time (sec)')
            axarr[i].set_ylabel(metrics_to_plot[key].unit.name)
            axarr[i].legend()
            axes_by_names[key] = i

        rax = plt.axes([0.01, 0.8, 0.1, 0.1])
        check_btns = CheckButtons(rax, stats.keys(), [True] * subplots_count)
        check_btns.on_clicked(self._get_show_hide_fn(fig, axarr, axes_by_names))

        plt.subplots_adjust(left=0.2)
        plt.show()
开发者ID:Altoros,项目名称:plsar,代码行数:29,代码来源:plot_sar.py

示例2: plot_hmm_path

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
def plot_hmm_path(trajectory_objs, paths, legends=[], items=[]):
    global colors
    print_n_flush("Colors are:", colors)
    for i, (trajectory, p) in enumerate(zip(trajectory_objs, paths)):
        print_n_flush("Path:", p)
        tr_colors = [colors[int(state)] for state in p]
        t = trajectory.plot2d(color=tr_colors)
        # t = plot_quiver2d(trajectory, color=tr_colors, path=p)
        too_high = [tt for tt in trajectory if tt[1] > 400]
        #         print_n_flush( "Too high", too_high)
        legends.append("Trajectory%i" % i)
        #     items.append(p)
        items.append(t)
    # gca().legend()



    # Let's create checkboxes
    rax = plt.axes([0.05, 0.4, 0.1, 0.15])
    # rax = plt.gca()
    from matplotlib.widgets import CheckButtons

    check = CheckButtons(rax, legends, [True] * len(legends))
    # plt.sca(axes)

    def func(label):
        widget = items[legends.index(label)]
        widget.set_visible(not widget.get_visible())
        plt.draw()

    check.on_clicked(func)
开发者ID:keryil,项目名称:leaparticulatorqt,代码行数:33,代码来源:StreamlinedDataAnalysisGhmm.py

示例3: __click_cb

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
class PeakIdentifier:
    def __click_cb(self, label):
        self.all_names[label] = not self.all_names[label]

    def __init_fig__(self, data_name):
        self.fig = figure()
        self.ax = subplot(111)
        self.fig.subplots_adjust(left=0.3)
        title(_path.basename(data_name))
        self.button_ax = plt.axes([0.05, 0.1, 0.15, 0.8])
        self.check = CheckButtons(self.button_ax, sorted(self.all_names.keys()), [False] * len(self.all_names))
        self.check.on_clicked(self.__click_cb)

    def __init_data__(self, data, start_i, end_i, pos, pos_s):
        start_i = int(start_i)
        end_i = int(end_i) + 1
        self.start_i = start_i
        self.end_i = end_i
        self.__pos = pos
        self.__pos_s = pos_s
        self.d = end_i - start_i
        new_start = start_i - 10 * self.d
        if new_start < 0:
            new_start = 0
        new_end = end_i + 10 * self.d
        if new_end >= len(data[2]):
            new_end = len(data[2] - 1)
        self.new_start = new_start
        self.new_end = new_end
        self.xs = r_[self.new_start : self.new_end]
        y1 = data[2][new_start:new_end]
        y2 = data[3][new_start:new_end]
        self.y = y2 - y1

    def __init_plot__(self):
        self.ax.axvline(self.__pos, color="m", linewidth=2)
        self.ax.axvline(self.__pos - self.__pos_s, color="g")
        self.ax.axvline(self.__pos + self.__pos_s, color="g")

        self.ax.plot(self.xs, self.y, color="c")

        self.ax.set_ylim(min(self.y), max(self.y))
        self.ax.set_xlim(self.new_start, self.new_end)

    def __init_names__(self, names):
        self.all_names = {}
        for n in names:
            self.all_names[n] = False

    def __init__(self, names, data, start_i, end_i, data_name, pos, pos_s):
        self.__init_names__(names)
        self.__init_fig__(data_name)
        self.__init_data__(data, start_i, end_i, pos, pos_s)
        self.__init_plot__()

    def run(self):
        show()
        close()
        return [k for k, v in self.all_names.items() if v]
开发者ID:yuyichao,项目名称:jlab2s13,代码行数:61,代码来源:identify_peaks.py

示例4: plot

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
    def plot(self, params, confidence_levels=[0.90, 0.95, 0.99], downsample=100):
        from plotutils import plotutils as pu
        from matplotlib import pyplot as plt
        from matplotlib.widgets import CheckButtons

        from itertools import cycle
        lines = ['solid', 'dashed', 'dashdot', 'dotted']
        linecycler = cycle(lines)

        N = len(self._tracking_array)
        tracking_array = self._tracking_array

        param1 = tracking_array[params[0]]
        param2 = tracking_array[params[1]]
        pu.plot_greedy_kde_interval_2d(np.vstack([param1, param2]).T, [0.90,0.95,0.99])
        ax = plt.gca()

        arrows = {}
        for proposal in self._proposals:
            ls = next(linecycler)
            sel = tracking_array['proposal'] == proposal
            accepted = tracking_array['accepted'][sel]
            xs = param1[sel]
            ys = param2[sel]
            x_ps = tracking_array[params[0]+'_p'][sel]
            y_ps = tracking_array[params[1]+'_p'][sel]
            dxs = x_ps - xs
            dys = y_ps - ys

            arrows[proposal] = []
            for x, y, dx, dy, a in zip(xs,ys,dxs,dys,accepted):
                if dx != 0 or dy != 0:
                    c = 'green' if a else 'red'
                    arrow = ax.arrow(x, y, dx, dy, fc=c, ec=c, alpha=0.5, visible=False, linestyle=ls)
                    arrows[proposal].append(arrow)

        plt.subplots_adjust(left=0.5)
        rax = plt.axes([0.05, 0.4, 0.4, 0.35])
        check = CheckButtons(rax, self._proposals, [False for i in self._proposals])

        def func(proposal):
            N = len(arrows[proposal])
            step = int(np.floor(N/float(downsample)))
            step = step if step is not 0 else 1
            for l in arrows[proposal][::step]:
                l.set_visible(not l.get_visible())
            plt.draw()

        check.on_clicked(func)
        plt.show()
开发者ID:farr,项目名称:nu-ligo-utils,代码行数:52,代码来源:proptracking.py

示例5: init_ax4

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
def init_ax4():
    
    global ax4, checkService, checkPause, checkEndBen, checkDist, check

    ax4 = fig.add_axes([.72, .15, .08, .12])
    ax4.set_xticklabels([])
    ax4.set_yticklabels([])
    ax4.set_xticks([])
    ax4.set_yticks([])
    
    # Define checkboxes
    check = CheckButtons(ax4, ('Service',   'Stepped', 'Pause',    'EndBen',    'Dist'),
                              (checkService, checkStepped, checkPause, checkEndBen, checkDist))
                               
    # Attach checkboxes to checkbox function
    check.on_clicked(func)
开发者ID:slehar,项目名称:service-prov,代码行数:18,代码来源:axes.py

示例6: initWindow

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
 def initWindow(self):
     if not (self.args.placeOne and self.args.placeTwo):
         self.randomBB()
     axes().set_aspect('equal', 'datalim')
     plt.subplot(2, 2, (1, 2))
     plt.subplot(2, 2, (1, 2)).set_aspect('equal')
     subplots_adjust(left=0.31)
     subplots_adjust(bottom=-0.7)
     plt.title('QSR Visualisation')
     axcolor = 'lightgoldenrodyellow'
     rax = plt.axes([0.03, 0.4, 0.22, 0.45], axisbg=axcolor)
     checkBox = CheckButtons(rax, self.qsr_type,(False,False,False,False,False))
     checkBox.on_clicked(self.EventClick)
     plt.subplot(2, 2, 3)
     plt.axis('off')
     plt.text(1, 1, (self.__compute_qsr(self.bb1, self.bb2)), family='serif', style='italic', ha='center')
     if self.qsr:
         self.updateWindow()
     plt.show()
开发者ID:OMARI1988,项目名称:strands_qsr_lib,代码行数:21,代码来源:basic_qsr_visualiser.py

示例7: initialize

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]

#.........这里部分代码省略.........
        t.append(float(x[0])-0.0001)
        t.append(x[0])
        t.append(float(x[0])+0.0001)
        for y in picked_list:
            if x[2]==y[1] and x[3]==y[2]:
                s_b.append(0.0)
                s_b.append(str(10**float(x[1]))) 
                s_b.append(0.0)
                t_b.append(float(x[0])-0.0001)
                t_b.append(x[0])
                t_b.append(float(x[0])+0.0001)  
    ax = figure_h.add_subplot(212)
    plt.subplots_adjust(left=0.25, bottom=0.25)
    pl.subplots_adjust( hspace=0.0,right=0.97 )

    
    
    a0 = 5
    f0 = 3
    global l,triples_plt
    l, = plt.plot(t,s, lw=2, color='red')
    triples_plt, = plt.plot([],[], '*',markersize=15,color='blue')
    ax.set_xlim([f_lower_g,f_upper_g])
    global picked_plt, ax2
    picked_plt, = plt.plot(t_b,s_b,lw=2,color='black')
    #plt.axis([0, 1, -10, 10])
    #figure_h.canvas.mpl_connect('button_press_event', handle_mouse_press)
    ax2 = figure_h.add_subplot(211,sharex=ax)
    ax2.axes.get_xaxis().set_visible(False)
    
    global peak_list_plt,exp_plt,trans_1_plt,trans_2_plt,trans_3_plt
    peak_list_plt, = ax2.plot([],[],'o',color='red')
    trans_1_plt, = ax2.plot([],[],'s',color='cyan')
    trans_2_plt, = ax2.plot([],[],'s',color='magenta')
    trans_3_plt, = ax2.plot([],[],'s',color='yellow')
    ax2.set_xlim([f_lower_g,f_upper_g])
    global locator   
    locator = ax2.yaxis.get_major_locator() 

    exp_plt, = ax2.plot([],[],lw=2,color='black')

    global peak_1_uncertainty,peak_2_uncertainty,peak_3_uncertainty,peaklist,freq_low,freq_high


    figure_h.canvas.mpl_connect('key_press_event', on_key)
    axcolor = 'lightgoldenrodyellow'
    axA = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
    axB  = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    axC  = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
    
    axua = plt.axes([0.03, 0.22, 0.1, 0.03], axisbg=axcolor)
    axub = plt.axes([0.03, 0.17, 0.1, 0.03], axisbg=axcolor)
    axuc = plt.axes([0.03, 0.12, 0.1, 0.03], axisbg=axcolor)
    #axub  = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    #axuc  = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
    global ua_slider
    ua_slider = Slider(axua, 'mu a', ua_g-1, ua_g+1, valinit=ua_g)
    ua_slider.on_changed(update)
    global ub_slider
    ub_slider = Slider(axub, 'mu b', ub_g-1, ub_g+1, valinit=ub_g)
    ub_slider.on_changed(update)
    global uc_slider
    uc_slider = Slider(axuc, 'mu c', uc_g-1, uc_g+1, valinit=uc_g)
    uc_slider.on_changed(update)
    global A_slider
    global B_slider
    global C_slider
    global rax
    rax = plt.axes([0.0, 0.5, 0.19, 0.4])
    global check
    check = CheckButtons(rax, ('','','',''), (True, False, False,False))
    

    check.on_clicked(func)
    
    
    
    
    A_slider = Slider(axA, 'A', A-dA, A+dA, valinit=A)
    B_slider = Slider(axB, 'B', B-dB, B+dB, valinit=B)
    C_slider = Slider(axC, 'C', C-dC, C+dC, valinit=C)
    
    
    
    A_slider.on_changed(update)
    B_slider.on_changed(update)
    C_slider.on_changed(update)
    global button
    global radio
    resetax = plt.axes([0.1, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset Sliders', color=axcolor, hovercolor='0.975')

    button.on_clicked(reset)
    #rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
    #radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
    #radio.on_clicked(colorfunc)
    global text_box
    #global text_box2
    text_box = plt.text(-1,8, "")
    text_box2 = plt.text(-1,23, "Refine Mouse Selection:                             Select transitions by pushing 'q' and then clicking in the predicted spectrum ")
开发者ID:jldmv,项目名称:bband_scripts,代码行数:104,代码来源:fitting_GUI_B_v10.py

示例8: CBox

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
class CBox(object):
    """Custom checkbox."""
    
    def __init__(self, fig, rect, labels, act=None, func=None, fargs=None):
        """init function

        Parameters:
            fig: a matplotlib.figure.Figure instance
            rect: [left, bottom, width, height]
                each of which in 0-to-1-fraction i.e. 0<=x<=1
            labels: array of strings
                labels to be checked
            act: a len(labels) array of booleans, optional, default: None
                indicating whether the label is active at first
                if None, all labels are inactive
            func: function, optional, default: None
                if not None, function called when checkbox status changes
            fargs: array, optional, default: None
                (optional) arguments for func
        """
        self.fig = fig
        self._rect = rect
        self._func = func
        self._fargs = fargs
        self._labels = labels
        self.axes = self.fig.add_axes(rect)
        self.axes.set_axis_bgcolor('1.00')
        inac = act if act is not None else (False,) * len(labels)
        self.cb = CheckButtons(self.axes, self._labels, inac)
        self.cb.on_clicked(self._onchange)

    def _onchange(self,label):
        """Actual function called when checkbox status changes."""
        if self.get_visible():
            if self._func is not None:
                if self._fargs is not None:
                    self._func(*self._fargs)
                else:
                    self._func()
            self.fig.canvas.draw()

    def get_status(self):
        """Get checkbox status.

        Returns: status
            status: list of booleans
                a len(labels) list of booleans indicating whether
                    label is active
                    
        NB: checkbox status changes even when it's not visible
            if a click hits the checkbox!
        """
        stat = []
        for i in self.cb.lines:
            stat.append(i[0].get_visible() or i[1].get_visible())
        return stat
        
    def set_visible(self,b):
        """Set its visibility.

        Parameters:
            b: boolean
        """
        self.axes.set_visible(b)

    def get_visible(self):
        """Get its visibility.

        Returns: b
            b: boolean
        """
        return self.axes.get_visible()
开发者ID:alesslazzari,项目名称:eledp,代码行数:74,代码来源:widg.py

示例9: Graphics

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
class Graphics (GraphMolecule, GraphBias, GraphTrans, GraphOrbitals, GraphIVCurve):
    """ Manages the graphical representation of the project
        Attributes
        fig                     Handle to the entire figure
        Bias                    The selected bias
        Gate                    The selected gate voltage
        OrbitalSel              The selected orbital or series of orbitals

        axSC                    Handle to the radio buttons window for the self consistency
        cbSC                    Handle to the radio buttons for the self consistency

        axOptions1              Handle to the checkbox window with options 1
        cbOptions1              Handle to the checkboxes with options 1
        
        axOptions2              Handle to the checkbox window with options 2
        cbOptions2              Handle to the checkboxes with options 2

        axGleft, axGright       Handle to the slider windows for selecting the lead interaction strength
        sGleft,  sGright        Handle to the sliders for selecting the lead interaction strength

        axSave                  Handle to the save button window
        bSave                   Handle to the save button

        Methods
        init()
        OnPick(event)           Manages the pick events
        OnClick(event)          Manages the on click events
        Save()                  Manages the input from the save button
        Options1(label)         Manages the input from the options 1 window
        Options2(label)         Manages the input from the options 2 window

        SetMolecule(Mol)        Sets the molecule class from which the graphics gets its information
        UpdateMolecule()        Updates everything that changes when the molecule has changed

        UpdateConsistency(label)Updates the selected consistency method
        UpdateG(val)            Updates the interaction strength with the leads
        UpdateBias(bias)        Updates the selected bias
        UpdateHamExt()          Updates everything that changes when the extended hamiltonian is changed
        
        UpdateGate(gate)        Updates the selected gate voltage
        UpdateAtomSel(iAtom)    Updates the selected atom
        UpdateOrbitalSel(iOrb)  Updates the selected orbital
        UpdateSelection()       Updates everything that changes after one of the selections has changed

    """

    def __init__(self):
        self.Consistency = 'Not self consistent'
        self.Bias = 0.1
        self.Gate = None
        self.OrbitalSel = None
        self.fig, (self.axBias, self.axTrans, self.axIVCurve) = plt.subplots(3,1)
        self.fig.patch.set_facecolor('ghostwhite')
        plt.subplots_adjust(left=0.3)
        pos = self.axBias.get_position()
        self.axBias.set_position ([pos.x0, 0.55, pos.width, 0.40])
        self.axTrans.set_position([pos.x0, 0.05, pos.width, 0.40])
        self.axIVCurve.set_position([0.05, 0.05, 0.2, 0.3])
        self.axCM = self.fig.add_axes([0.94, 0.55, 0.01, 0.35])

        self.fig.canvas.mpl_connect('button_press_event', self.OnClick)
        self.fig.canvas.mpl_connect('pick_event', self.OnPick)
        self.fig.canvas.mpl_connect('key_press_event', self.OnPress)

        self.InitMolecule()
        self.InitBias()
        self.InitTrans()
        self.InitOrbitals()
        self.InitIVCurve()
        
        self.axSC = plt.axes([0.05, 0.85, 0.15, 0.10], axisbg='white')
        self.cbSC = RadioButtons(self.axSC, ('Not self consistent', 'Hubbard', 'PPP'))
        self.cbSC.on_clicked(self.UpdateConsistency)

        self.axOptions1 = plt.axes([0.05, 0.7, 0.15, 0.10], axisbg='white')
        self.cbOptions1 = CheckButtons(self.axOptions1, ('Overlap', 'Show Local Density','Show Local Currents'), (False, False, True))
        self.cbOptions1.on_clicked(self.Options1)
        
        self.axOptions2 = plt.axes([0.05, 0.5, 0.15, 0.15], axisbg='white')
        self.cbOptions2 = CheckButtons(self.axOptions2, ('Show Transmission', 'Show Current', 'Show DOS', 'Show Orbitals', 'Show Phase'), (True, True, False, False, False))
        self.cbOptions2.on_clicked(self.Options2)
        c = ['seagreen', 'b', 'darkorange', 'lightsteelblue', 'm']    
        [rec.set_facecolor(c[i]) for i, rec in enumerate(self.cbOptions2.rectangles)]
        
        self.axGleft  = plt.axes([0.05, 0.43, 0.15, 0.02], axisbg='white')
        self.axGright = plt.axes([0.05, 0.40, 0.15, 0.02], axisbg='white')
        self.sGleft   = Slider(self.axGleft,  'Gl', 0.0, 1.0, valinit = gLeft)
        self.sGright  = Slider(self.axGright, 'Gr', 0.0, 1.0, valinit = gRight)
        self.sGleft.on_changed(self.UpdateG)
        self.sGright.on_changed(self.UpdateG)
        
        self.axSave = plt.axes([0.92, 0.95, 0.07, 0.04])
        self.bSave = Button(self.axSave, 'Save')
        self.bSave.on_clicked(self.Save)

    def OnPick(self, event):
        if isinstance(event.artist, Rectangle):
            self.OnPickOrbital(event)
        else:
            self.OnPickMolecule(event)
#.........这里部分代码省略.........
开发者ID:TimGebraad,项目名称:TN2953_Bachelor_EindProject,代码行数:103,代码来源:Graphics.py

示例10: CheckButtons

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
        for j in iterHulls[i]:
            if j.get_visible():
                legLine.append(j)
                legLabel.append(j.get_label())

    font=FontProperties(size='small')
    if (len(legLine) > 0):
        ax.legend(legLine, legLabel, loc=options.lpos, shadow=True, prop=font)
    else:
        ax.legend(("",),loc=options.lpos, shadow=True, prop=font)
    plt.draw()

if not options.outfile:
    rax = plt.axes([0.05, 0.15, 0.15, 0.6])
    check = CheckButtons(rax, ['scatter', 'all', 'config'] + itervars.keys(), (scatterPoints.get_visible(), allHull.get_visible(), options.configs) + tuple(itervarsenabled.values()))
    check.on_clicked(toggleHullVisibility)

toggleHullVisibility("")
if options.zoom:
    limits = options.zoom.split(",");
    if len(limits) != 4:
        print "-z parameter needs 4 comma-seperated float values!"
        exit(-1)
    ax.set_xlim(float(limits[0]), float(limits[1]))
    ax.set_ylim(float(limits[2]), float(limits[3]))

plt.show()

if options.outfile:
#    fig.savefig(options.outfile)
    # Write gnuplot script
开发者ID:nguyenquynh1993,项目名称:multi-p2p,代码行数:33,代码来源:scatterplot.py

示例11: animate

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
def animate(sources, reflect=False):
    fig = plt.figure()

    # create reflection images of sources
    if reflect:
        reflectedSources = []
        for src in sources:
            reflSrc = deepcopy(src)
            reflSrc.pos = -src.pos
            reflectedSources.append(reflSrc)

            
    # subplot for every source
    lines = []
    for i, src in enumerate(sources):
        # pressure on left y axis
        ax1 = fig.add_subplot(len(sources)+1, 1, i+1)
        ax1.set_xlim([0, xMax])
        yLim = src.pAmpl * 1.3 * (1+reflect)
        ax1.set_ylim([-yLim, yLim])
        ax1.set_ylabel('p')
        line_pSrc, = plt.plot([], [], 'r--', lw=1)
        line_pRefl, = plt.plot([], [], 'r:', lw=1)
        line_p, = plt.plot([], [], 'r', lw=1, label='p')
        ax1.legend(loc='upper left')
                
        # velocity on right y axis
        ax2 = ax1.twinx()
        ax2.set_xlim([0, xMax])
        yLim = src.uAmpl * 2  * (1+reflect)
        ax2.set_ylim([-yLim, yLim])
        ax2.set_ylabel('u')
        line_uSrc, = plt.plot([], [], 'b--', lw=1)
        line_uRefl, = plt.plot([], [], 'b:', lw=1)
        line_u, = plt.plot([], [], 'b', lw=1, label='u')
        ax2.legend(loc='upper right')

        ax1.set_title(src.name)
        lines.append([line_pSrc, line_uSrc, line_pRefl, line_uRefl, line_p, line_u])

    # subplot for total pressure and velocity
    # pressure on left y axis
    ax1 = fig.add_subplot(len(sources)+1, 1, len(sources)+1)
    ax1.set_xlim([0, xMax])
    yLim = sum([src.pAmpl for src in sources]) * 1.3 * (1+reflect)
    ax1.set_ylim([-yLim, yLim])
    ax1.set_ylabel('p')
    line_p, = plt.plot([], [], 'r', lw=1, label='p')
    ax1.legend(loc='upper left')

    # velocity on right y axis
    ax2 = ax1.twinx()
    ax2.set_xlim([0, xMax])
    yLim = sum([src.uAmpl for src in sources]) * 2 * (1+reflect)
    ax2.set_ylim([-yLim, yLim])
    ax2.set_ylabel('u')
    line_u, = plt.plot([], [], 'b', lw=1, label='u')
    ax2.legend(loc='upper right')

    ax1.set_title('Sum of all sources')
    lineSum = [line_p, line_u]

    
    # interactive plots :)
    plt.subplots_adjust(left=0.15, top=0.9)
    showVelocity = [not reflect]  # value in list - a hack to use nonlocal in Python 2
    showPressure = [True]
    checkAx = plt.axes([0.05, 0.6, 0.05, 0.15])
    checkButtons = CheckButtons(checkAx, ('p', 'v'), (True, showVelocity[0]))
    def toggleLines(label):
        if label == 'p': 
            showPressure[0] = not showPressure[0]
        elif label == 'v':
            showVelocity[0] = not showVelocity[0]
    checkButtons.on_clicked(toggleLines)

    resetAnimation = [False]
    buttonAx = plt.axes([0.05, 0.85, 0.05, 0.04])
    button = Button(buttonAx, 'Reset', hovercolor='0.975')
    def reset(event):
        resetAnimation[0] = True
    button.on_clicked(reset)
    

    

    def drawBackground():
        for iSrc, src in enumerate(sources):
            lines[iSrc][0].set_data([src.pos, src.pos],
                                    [-src.pAmpl * 3, src.pAmpl * 3])
            for line in lines[iSrc][1:]:
                line.set_data([], [])
        
        lineSum[0].set_data([], [])
        lineSum[1].set_data([], [])
        
        return tuple(itertools.chain(*lines)) + tuple(lineSum)
        
    def drawFrame(i):
        t = i * SPEED
#.........这里部分代码省略.........
开发者ID:matejfroebe,项目名称:duct-ANC,代码行数:103,代码来源:duct.py

示例12: HilbertGUI

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]

#.........这里部分代码省略.........
            fn = self.config['data'][i]['filename']
            label = '%s' % (os.path.basename(fn))
            self.check_labels.append(label)
            self.check_display.append(self.mappables[i])

        self.checks = CheckButtons(self.check_ax, self.check_labels, \
                                   self.check_display)
        
    def _init_radio(self):
        # For controlling log/linear color scale
        self.radio = RadioButtons(
            self.radio_ax,
            labels=['log', 'linear'],
            active=1)

    def _make_connections(self):
        # Alpha sliders
        for i in range(self.n):
            self.sliders[i].on_changed(
                self._slider_callback_factory(
                    self.mappables[i], self.cbars[i]))

        """
        # Min sliders change thresh
        self.min_slider1.on_changed(
            self._min_slider_callback_factory(
                self.h1, self.mappable1, self.cbar1))
        self.min_slider2.on_changed(
            self._min_slider_callback_factory(
                self.h2, self.mappable2, self.cbar2))
        """

        # Radio callback changes color scale
        self.radio.on_clicked(self._radio_callback)
        #Checkbox callback changes what hilberts are shown
        self.checks.on_clicked(self._check_callback)
        
        self.fig.canvas.mpl_connect('motion_notify_event', self._coord_tracker)
        self.fig.canvas.mpl_connect('pick_event', self._coord_callback)

    def plot(self):
        """
        Does most of the work to set up the figure, axes, and widgets.
        """
        # These methods construct axes in the right places
        self._make_main_axes()
        self._make_colorbar_axes()
        self._make_alpha_slider_axes()
        self._make_min_slider_axes()
        self._make_annotation_axes()
        self._make_radio_axes()
        self._make_checkbox_axes()

        # Plot the matrices and their colorbars
        self._imshow_matrices()
        self._matrix_colorbars()

        # Initialize the various widgets
        self._init_alpha_sliders()
        self._init_min_sliders()
        self._init_radio()
        self._init_checks()

        # Connect callbacks to events
        self._make_connections()
开发者ID:ml4wc,项目名称:scurgen,代码行数:69,代码来源:plotting.py

示例13: scmoplot

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
def scmoplot(root_path, user_ps):

    ps = dict(default_ps)
    ps.update(user_ps)

    ng = NameGleaner(scan=r'scan=(\d+)', x=r'x=(\d+)', y=r'y=(\d+)',
                     averaged=r'(averaged)')

    tfmr = Transformer(gleaner=ng)
    tfmr.add(10, tfms.scale, params={'xsc': 0.1})
    tfmr.add(20, tfms.flatten_saturation, 
              params={'threshold': ps['thresh'], 'polarity': '+'})
    tfmr.add(25, tfms.center)
    tfmr.add(30, tfms.wrapped_medfilt, params={'ks': ps['filt_ks']})
    tfmr.add(40, tfms.saturation_normalize, params={'thresh': ps['thresh']})
    
    tfmr2 = Transformer(gleaner=ng)
    tfmr2.add(10, tfms.scale, params={'xsc': 0.1})
    tfmr2.add(30, tfms.wrapped_medfilt, params={'ks': ps['filt_ks']})
    tfmr2.add(40, tfms.clean)

    clust = Cluster(join(root_path, 'parameters.xml')).to_dict()
    gx, gy = (clust['Rows'], clust['Cols'])

    fig, axarr = plt.subplots(ncols=gx, nrows=gy, 
                              figsize=(10, 10))

    for row in axarr:
        for ax in row:
            ax.xaxis.set_ticklabels([])
            ax.yaxis.set_ticklabels([])
            #ax.set_xlim(-ps['xlim'], ps['xlim'])
            #ax.set_ylim(-ps['ylim'], ps['ylim'])

    Hcs = [[None for i in range(gx)] for i in range(gy)]
    Mrs = [[None for i in range(gx)] for i in range(gy)]
    for f in listdir(root_path):
        gleaned = ng.glean(f)
        if gleaned['averaged']:
            print('Plotting %s' % f)
            x, y = int(gleaned['x']), int(gleaned['y'])
            ax = axarr[y, x]
            Bi, Vi = np.loadtxt(join(root_path, f), usecols=(0, 1), unpack=True, 
                              skiprows=7)
                              
                              
            B,V = tfmr((Bi,Vi),f)             
            B2, V2 = tfmr2((Bi, Vi), f)
            
                
            ##data set 2 graphs
            lslope,rslope,tan=tfms.x0slope(B2,V2)
            lsat,rsat=tfms.sat_field(B2,V2)
            area = tfms.loop_area(B2,V2)
            data = ax.plot(B2,V2,'k')
            tanlines = ax.plot(tan[0],tan[1],'r',tan[2],tan[3],'y*',tan[4],tan[5],'b',tan[6],tan[7], 'y*')
            satfields = ax.plot(B2[lsat],V2[lsat],'ro',B2[rsat],V2[rsat],'go')
            areatext = ax.text(B2.min(),V2.max(), ("loop area: "+str(area+.0005)[0:6]))
            
            rax = plt.axes([0.05, 0.4, 0.1, 0.15])
            check = CheckButtons(rax, ('data', 'tangent lines',
                'saturation points', 'loop area'), (True, True, True, True))
            def func(label):
                if label == 'data': toggle(data)
                elif label == 'tangent lines': toggle(tanlines)
                elif label == 'saturation points': toggle(satfields)
                elif label == 'loop area': areatext.set_visible(not areatext.get_visible())
                plt.draw()
            check.on_clicked(func)
            
            try:
                Hc = tfms.Hc_of(B, V, fit_int=(ps['thresh'], ps['max']))
                Hcs[y][x] = Hc
                Mr = tfms.Mrem_of(B, V, fit_int=(ps['thresh'], ps['max']))
                Mrs[y][x] = Mr
                zs = np.zeros(3)
                ax.plot(zs, Mr, 'ro', ms=7)
                ax.plot(Hc, zs, 'ro', ms=7)
            except Exception as e:
                print('\t{}'.format(e))
                Hcs[y][x] = 0.0
                Mrs[y][x] = 0.0
                
          

    plt.tight_layout(w_pad=0, h_pad=0)
    plt.show()

    Hcs = np.array([x[1] for row in Hcs for x in row]).reshape(gy, gx)
    Mrs = np.array([x[1] for row in Mrs for x in row]).reshape(gy, gx)

    gs = GridSpec(10, 10)
    ax0 = plt.subplot(gs[0:9, :5])
    ax1 = plt.subplot(gs[9, :5])
    ax2 = plt.subplot(gs[0:9, 5:])
    ax3 = plt.subplot(gs[9, 5:])
    fig = ax0.get_figure()
    fig.set_size_inches(12, 8)

# Plot Hc pcolor map
#.........这里部分代码省略.........
开发者ID:UW-Physics-RzchLab,项目名称:scmoplot,代码行数:103,代码来源:main.py

示例14: RadioButtons

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]
rb1_axes = plt.axes([0.70, 0.62, 0.10, 0.15], axisbg=axcolor)
radio1 = RadioButtons(rb1_axes, ('A', 'B', 'C'))
def rb_1(label):
  print 'radio button 1'  

radio1.on_clicked(rb_1)


rax = plt.axes([0.70, 0.3, 0.2, 0.25])
labels=['Type 1','Type 2', 'Type 4', 'Other']
check = CheckButtons(rax, (labels[0], labels[1], labels[2], labels[3]), 
 (False, False, False, False))

def func(label):
    if label == labels[0]: check_text=labels[0]
    elif label == labels[1]: check_text=labels[1]
    elif label == labels[2]: check_text=labels[2]
    elif label == labels[3]: check_text=labels[3]
    print 'checked: ', check_text
check.on_clicked(func)


ax.text=(0.9, 0.9, 'ax.text 0.5')
fig.text=(0.9, 0.9, 'fig.text 0.5')


plt.show()


#if __name__=='__main__':
开发者ID:richardgmcmahon,项目名称:matplotlib_examples,代码行数:32,代码来源:gui_buttons_slider.py

示例15: evaluateKineticsGroupValues

# 需要导入模块: from matplotlib.widgets import CheckButtons [as 别名]
# 或者: from matplotlib.widgets.CheckButtons import on_clicked [as 别名]

#.........这里部分代码省略.........
            
            print "Test set {0} contained {1} rates.".format(testSetLabel, count)
            print 'Confidence interval at T = {0:g} K for test set "{1}" = 10^{2:g}'.format(T, testSetLabel, ci)
        
            # Add this test set to the plot
            lines.append(ax.loglog(kdata, kmodel, 'o', picker=5)[0])
            legend.append(testSetLabel)
        
        stdev_total = math.sqrt(stdev_total / (count_total - 1))
        ci_total = scipy.stats.t.ppf(0.975, count_total - 1) * stdev_total
        
        print 'Total confidence interval at T = {0:g} K for all test sets = 10^{1:g}'.format(T, ci_total)
                
        # Finish plots
        xlim = pylab.xlim()
        ylim = pylab.ylim()
        lim = (min(xlim[0], ylim[0])*0.1, max(xlim[1], ylim[1])*10)
        ax.loglog(lim, lim, '-k')
        ax.loglog(lim, [lim[0] * 10**ci_total, lim[1] * 10**ci_total], '--k')
        ax.loglog(lim, [lim[0] / 10**ci_total, lim[1] / 10**ci_total], '--k')
        pylab.xlabel('Actual rate coefficient ({0})'.format(kunits))
        pylab.ylabel('Predicted rate coefficient ({0})'.format(kunits))
        if len(testSets) > 1:
            pylab.legend(legend, loc=4, numpoints=1)
        pylab.title('%s, T = %g K' % (family.label, T))
        pylab.xlim(lim)
        pylab.ylim(lim)
        
        plot_range = math.log10(lim[1] / lim[0])
        if plot_range > 25:
            majorLocator = matplotlib.ticker.LogLocator(1e5)
            minorLocator = matplotlib.ticker.LogLocator(1e5, subs=[1, 10, 100, 1000, 10000])
        elif plot_range > 20:
            majorLocator = matplotlib.ticker.LogLocator(1e4)
            minorLocator = matplotlib.ticker.LogLocator(1e4, subs=[1, 10, 100, 1000])
        elif plot_range > 15:
            majorLocator = matplotlib.ticker.LogLocator(1e3)
            minorLocator = matplotlib.ticker.LogLocator(1e3, subs=[1, 10, 100])
        elif plot_range > 10:
            majorLocator = matplotlib.ticker.LogLocator(1e2)
            minorLocator = matplotlib.ticker.LogLocator(1e2, subs=[1, 10])
        else:
            majorLocator = matplotlib.ticker.LogLocator(1e1)
            minorLocator = None   
        ax.xaxis.set_major_locator(majorLocator)
        ax.yaxis.set_major_locator(majorLocator)
        if minorLocator:
            ax.xaxis.set_minor_locator(minorLocator)
            ax.yaxis.set_minor_locator(minorLocator)
        
        def onpick(event):
            index = lines.index(event.artist)
            xdata = event.artist.get_xdata()
            ydata = event.artist.get_ydata()
            testSetLabel, testSet = testSets[index]
            for ind in event.ind:
                reaction, template, entry, krule, kgroup, kdata = testSet[ind]
                kunits = 'm^3/(mol*s)' if len(reaction.reactants) == 2 else 's^-1'
                print testSetLabel
                print 'template = [{0}]'.format(', '.join([g.label for g in template]))
                print 'entry = {0!r}'.format(entry)
                print str(reaction)
                print 'k_data   = {0:9.2e} {1}'.format(xdata[ind], kunits)
                print 'k_model  = {0:9.2e} {1}'.format(ydata[ind], kunits)
                print krule
                if kgroup: print kgroup
                print krule.comment
                if kgroup: print kgroup.comment
                print
                
        connection_id = fig.canvas.mpl_connect('pick_event', onpick)
        
        if plot == 'interactive':
            rax = plt.axes([0.15, 0.65, 0.2, 0.2])
            check = CheckButtons(rax, legend, [True for label in legend])
            
            def func(label):
                for index in range(len(lines)):
                    if legend[index] == label:
                        lines[index].set_visible(not lines[index].get_visible())
                plt.draw()
            check.on_clicked(func)
            
            fig.subplots_adjust(left=0.10, bottom=0.10, right=0.97, top=0.95, wspace=0.20, hspace=0.20)

        else:
            fig.subplots_adjust(left=0.15, bottom=0.14, right=0.95, top=0.93, wspace=0.20, hspace=0.20)
            filename = '{0}_{1:g}'.format(family.label, T)
            if method == 'rate rules':
                filename += '_rules'
            elif method == 'group additivity':
                filename += '_groups'
            if exactOnly:
                filename += '_exact'
            elif estimateOnly:
                filename += '_estimate'
            pylab.savefig('{0}.pdf'.format(filename))
            pylab.savefig('{0}.png'.format(filename), dpi=200)
          
        pylab.show()
开发者ID:KEHANG,项目名称:RMG-database,代码行数:104,代码来源:kineticsGroups.py


注:本文中的matplotlib.widgets.CheckButtons.on_clicked方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。