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


Python pyplot.isinteractive函数代码示例

本文整理汇总了Python中matplotlib.pyplot.isinteractive函数的典型用法代码示例。如果您正苦于以下问题:Python isinteractive函数的具体用法?Python isinteractive怎么用?Python isinteractive使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: ToSVGString

def ToSVGString(graph):
    """
    Convert as SVG file.

    Parameters
    ----------
    graph : object
        A Graph or Drawable object.

    Returns a SVG representation as string
    """

    # save interactive mode state
    ision = plt.isinteractive()
    plt.ioff()

    view = View(graph)
    output = io.BytesIO()
    view.save(output, format='svg')
    view.close()

    # restore interactive mode state
    if ision:
        plt.ion()

    svgBytes = output.getvalue()
    return svgBytes.decode('utf-8')
开发者ID:aurelieladier,项目名称:openturns,代码行数:27,代码来源:viewer.py

示例2: test16

 def test16(self):
     '''test that makes a real time graph resembling a sine graph 
     '''
     # note that by using list comprehension the first 20 points are auto plotted 
     fig = plt.figure(1)
     import math
     my = []
     t = range(-50, 50)
     for item in t:
         b = math.sin(item)
         my.append(b)
         mylist = array(my)
         
         plt.cla()
         plt.plot(my[-20:], '-r')
         #analyzing the plot components
         a = plt.get_backend()
         c = plt.isinteractive()
         
         # analyzing the axis commands
         z = plt.axis() 
         v =  plt.get_plot_commands() 
         #plt.draw()
         fig.canvas.draw()
         self.logger.debug("PLT.GET_NEXT_COMMANDS OUTPUT RESPONS: " + repr(v) )
     self.logger.debug("PLT.GET_BACKEND OUTPUT: " + repr(a) )
     #self.logger.debug("PLT.GET_NEXT_COMMANDS OUTPUT RESPONS: " + repr(d) )
     self.logger.debug("PLT.AXIS COMMAND OUTPUTANSWER TO PLT.AXIS: " + repr(z) )
开发者ID:amitsandhel,项目名称:PA273-Potentiostat-Software,代码行数:28,代码来源:test_graphclass.py

示例3: print_all

def print_all(fnames, freq, spec1, spec2, rms1, rms2, bw=(0,1600)):
    '''
    Print all power spectra to PDF files
    '''
    # Construct path for saving figures and notify
    base_dir = os.path.join(os.getcwd(), 'figures')
    if not os.path.exists(base_dir):
        os.mkdir(base_dir)
    print('\nsaving figures to {s} ... '.format(s=base_dir), flush=True)

    # Plot and save figures for each channel's spectrum
    on = plt.isinteractive()
    plt.ioff()
    for chan in range(spec1.shape[-1]):
        fig = comp_spectra(freq, spec1, spec2, channel=chan, bw=bw)
        plt.title('Channel {0:d}'.format(chan))
        plt.xlabel('Frequency (Hz)')
        plt.ylabel('Power')
        plt.legend(('Before', 'After'))
        print('figure {:02d}'.format(chan), flush=True)
        plt.savefig(os.path.join(base_dir, 'channel{0:02d}.png'.format(chan)), format='png')
        plt.close(fig)

    # Plot and save figure showing RMS ratio
    fig = plt.figure()
    plt.plot(rms2 / rms1, 'o')
    plt.title('RMS ratio (after / before)')
    plt.xlabel('Channel')
    plt.savefig(os.path.join(base_dir, 'rms_ratio.png'), format='png')
    plt.close(fig)

    # Notify
    plt.interactive(on)
    print('done.')
开发者ID:baccuslab,项目名称:plat,代码行数:34,代码来源:plat.py

示例4: plot_patches

def plot_patches(patches, fignum=None, low=0, high=0):
    """
    Given a stack of 2D patches indexed by the first dimension, plot the
    patches in subplots.

    'low' and 'high' are optional arguments to control which patches
    actually get plotted. 'fignum' chooses the figure to plot in.
    """
    try:
        istate = plt.isinteractive()
        plt.ioff()
        if fignum is None:
            fig = plt.gcf()
        else:
            fig = plt.figure(fignum)
        if high == 0:
            high = len(patches)
        pmin, pmax = patches.min(), patches.max()
        dims = np.ceil(np.sqrt(high - low))
        for idx in xrange(high - low):
            spl = plt.subplot(dims, dims, idx + 1)
            ax = plt.axis('off')
            im = plt.imshow(patches[idx], cmap=matplotlib.cm.gray)
            cl = plt.clim(pmin, pmax)
        plt.show()
    finally:
        plt.interactive(istate)
开发者ID:fred1234,项目名称:BigData,代码行数:27,代码来源:patches.py

示例5: _hinton

def _hinton(W, error=None, vmax=None, square=True):
    """
    Draws a Hinton diagram for visualizing a weight matrix. 

    Temporarily disables matplotlib interactive mode if it is on, 
    otherwise this takes forever.

    Originally copied from
    http://wiki.scipy.org/Cookbook/Matplotlib/HintonDiagrams
    """
    reenable = False
    if plt.isinteractive():
        plt.ioff()
        reenable = True
        
    #P.clf()
    W = misc.atleast_nd(W, 2)
    (height, width) = W.shape
    if not vmax:
        #vmax = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2))
        if error is not None:
            vmax = np.max(np.abs(W) + error)
        else:
            vmax = np.max(np.abs(W))

    plt.fill(0.5+np.array([0,width,width,0]),
             0.5+np.array([0,0,height,height]),
             'gray')
    plt.axis('off')
    if square:
        plt.axis('equal')
    plt.gca().invert_yaxis()
    for x in range(width):
        for y in range(height):
            _x = x+1
            _y = y+1
            w = W[y,x]
            _w = np.abs(w)
            if w > 0:
                _c = 'white'
            else:
                _c = 'black'
            if error is not None:
                e = error[y,x]
                if e < 0:
                    print(e, _w, vmax)
                    raise Exception("BUG? Negative error")
                if _w + e > vmax:
                    print(e, _w, vmax)
                    raise Exception("BUG? Value+error greater than max")
                _rectangle(_x,
                           _y, 
                           min(1, np.sqrt((_w+e)/vmax)),
                           min(1, np.sqrt((_w+e)/vmax)),
                           edgecolor=_c,
                           fill=False)
            _blob(_x, _y, min(1, _w/vmax), _c)
                
    if reenable:
        plt.ion()
开发者ID:viveksck,项目名称:bayespy,代码行数:60,代码来源:plot.py

示例6: lvmTwoDPlot

def lvmTwoDPlot(X, lbl=None, symbol=None):

    """Helper function for plotting the labels in 2-D.
    
    Description:
    
    lvmTwoDPlot(X, lbl, symbol) helper function for plotting an
     embedding in 2-D with symbols.
     Arguments:
      X - the data to plot.
      lbl - the labels of the data point.
      symbol - the symbols to use for the different labels.
        

    See also
    lvmScatterPlot, lvmVisualise


    Copyright (c) 2004, 2005, 2006, 2008, 2009 Neil D. Lawrence
    
    """

    if lbl=='connect':
        connect = True
        lbl = None
    else:
        connect = False
    
    if symbol is None:
        if lbl is None:
            symbol = ndlutil.getSymbols(1)
        else:
            symbol = ndlutil.getSymbols(lbl.shape[1])
    axisHand = pp.gca()
    returnVal = []
    holdState = axisHand.ishold()
    intState = pp.isinteractive()
    pp.interactive(False)
    for i in range(X.shape[0]):
        if i == 1:
            axisHand.hold(True)
        if lbl is not None:
            labelNo = np.flatnonzero(lbl[i])
        else:
            labelNo = 0

        try:
            returnVal.append(axisHand.plot([X[i, 0]], [X[i, 1]], symbol[labelNo], markersize=10, linewidth=2))
            if connect:
                if i>0:
                    axisHand.plot([X[i-1, 0], X[i, 0]], [X[i-1, 1], X[i, 1]], 'r')
            
        except(NotImplementedError):
            raise NotImplementedError('Only '+ str(len(symbol)) + ' labels supported (it''s easy to add more!)')
    axisHand.hold(holdState)
    if intState:
        pp.show()
    pp.interactive(intState)
    
    return returnVal
开发者ID:lawrennd,项目名称:mltools,代码行数:60,代码来源:mltools.py

示例7: five_by_four

def five_by_four(resonators, title="", xlabel='frequency [MHz]', ylabel='$|S_{21}|$ [dB]', sort=False, **kwds):
    if sort:
        resonators.sort(key = lambda r: r.f_0)
    interactive = plt.isinteractive()
    plt.ioff()
    fig = plt.figure(figsize=(4, 3))
    for n, r in enumerate(resonators):
        e = extract(r, **kwds)
        axis = fig.add_subplot(4, 5, n+1)
        _plot_on_axis(e, axis)
        axis.set_xlabel("")
        axis.set_ylabel("")
        axis.tick_params(right=False, top=False, direction='out', pad=1)
        xticks = [e['f_0']]
        axis.set_xticks(xticks)
        axis.set_xticklabels(['{:.3f}'.format(tick) for tick in xticks])
        yticks = [20*np.log10(np.abs(e['model_0'])), 20*np.log10(np.mean((np.abs(e['data'][0]), np.abs(e['data'][-1]))))]
        axis.set_yticks(yticks)
        axis.set_yticklabels(['{:.0f}'.format(tick) for tick in yticks])

    fig.text(0.3, 0.94, title, fontsize='medium', color='black')
    fig.text(0.02, 0.94, ylabel, fontsize='medium', color='black')
    fig.text(0.05, 0.04, xlabel, fontsize='medium', color='black')
    fig.text(0.4, 0.04, 'data', fontsize='medium', color='blue')
    fig.text(0.55, 0.04, 'masked', fontsize='medium', color='gray')
    fig.text(0.75, 0.04, 'fit and f_0', fontsize='medium', color='brown')
    fig.set_tight_layout({'pad': 0.5, 'h_pad': 0.2, 'w_pad': 0.3, 'rect': (0, 0.08, 1, 0.94)})
    if interactive:
        plt.ion()
        plt.show()
    return fig
开发者ID:braddober,项目名称:kid_readout,代码行数:31,代码来源:plot_resonator.py

示例8: interactive

def interactive(b):
    b_prev = plt.isinteractive()
    plt.interactive(b)
    try:
        yield
    finally:
        plt.interactive(b_prev)
开发者ID:ronniemaor,项目名称:timefit,代码行数:7,代码来源:misc.py

示例9: plot_paths

def plot_paths(results, which_to_label=None):
    import matplotlib
    import matplotlib.pyplot as plt
    plt.clf()
    interactive_state = plt.isinteractive()
    xvalues = -np.log(results.lambdas[1:])
    for index, path in enumerate(results.coefficients):
        if which_to_label and results.indices[index] in which_to_label:
            if which_to_label[results.indices[index]] is None:
                label = "$x_{%d}$" % results.indices[index]
            else:
                label = which_to_label[results.indices[index]]
        else:
            label = None


        if which_to_label and label is None:
            plt.plot(xvalues, path[1:], ':')
        else:
            plt.plot(xvalues, path[1:], label=label)

    plt.xlim(np.amin(xvalues), np.amax(xvalues))

    if which_to_label is not None:
        plt.legend(loc='upper left')
    plt.title('Regularization paths ($\\rho$ = %.2f)' % results.balance)
    plt.xlabel('$-\log(\lambda)$')
    plt.ylabel('Value of regression coefficient $\hat{\\beta}_i$')
    plt.show()
    plt.interactive(interactive_state)
开发者ID:samuelstjean,项目名称:glmnet-python,代码行数:30,代码来源:glmnet.py

示例10: plot_data_dict

def plot_data_dict(data_dict, plots = None, mode = 'static', hang = True, figure = None, size = None, **plot_preference_kwargs):
    """
    Make a plot of data in the format defined in data_dict
    :param data_dict: dict<str: plottable_data>
    :param plots: Optionally, a dict of <key: IPlot> identifying the plot objects to use (keys should
        be the same as those in data_dict).
    :return: The plots (same ones you provided if you provided them)
    """

    assert mode in ('live', 'static')
    if isinstance(data_dict, list):
        assert all(len(d) == 2 for d in data_dict), "You can provide data as a list of 2 tuples of (plot_name, plot_data)"
        data_dict = OrderedDict(data_dict)

    if plots is None:
        plots = {k: get_plot_from_data(v, mode = mode, **plot_preference_kwargs) for k, v in data_dict.items()}

    if figure is None:
        if size is not None:
            from pylab import rcParams
            rcParams['figure.figsize'] = size
        figure = plt.figure()
    n_rows, n_cols = vector_length_to_tile_dims(len(data_dict))
    for i, (k, v) in enumerate(data_dict.items()):
        plt.subplot(n_rows, n_cols, i + 1)
        plots[k].update(v)
        plots[k].plot()
        plt.title(k, fontdict = {'fontsize': 8})
    oldhang = plt.isinteractive()
    plt.interactive(not hang)
    plt.show()
    plt.interactive(oldhang)
    return figure, plots
开发者ID:QUVA-Lab,项目名称:artemis,代码行数:33,代码来源:easy_plotting.py

示例11: plot

    def plot(self, ax=None, unit="", maxval=None):
        """Scatter plot of estimates vs observations

        Parameters
        ----------
        ax : a matplotlib axes object to plot on
           if None, a new axes object will be created
        unit : string
           measurement unit of the observations / estimates
        maxval : maximum value for plot range, defaults to max(obs, est)
        """
        if self.n == 0:
            print("No valid data, no plot.")
            return None
        doplot = False
        if ax is None:
            fig = pl.figure()
            ax = fig.add_subplot(111, aspect=1.)
            doplot = True
        ax.plot(self.obs, self.est, mfc="None", mec="black", marker="o", lw=0)
        if maxval is None:
            maxval = np.max(np.append(self.obs, self.est))
        pl.xlim(xmin=0., xmax=maxval)
        pl.ylim(ymin=0., ymax=maxval)
        ax.plot([0, maxval], [0, maxval], "-", color="grey")
        pl.xlabel("Observations (%s)" % unit)
        pl.ylabel("Estimates (%s)" % unit)
        if (not pl.isinteractive()) and doplot:
            pl.show()
        return ax
开发者ID:Maxima86,项目名称:wradlib,代码行数:30,代码来源:verify.py

示例12: report

    def report(self, metrics=None, ax=None, unit="", maxval=None):
        """Pretty prints selected error metrics over a scatter plot

        Parameters
        ----------
        metrics : sequence of strings
           names of the metrics which should be included in the report
           defaults to ["rmse","r2","meanerr"]
        ax : a matplotlib axes object to plot on
           if None, a new axes object will be created
        unit : string
           measurement unit of the observations / estimates

        """
        if self.n == 0:
            print("No valid data, no report.")
            return None
        if metrics is None:
            metrics = ["rmse", "nash", "pbias"]
        doplot = False
        if ax is None:
            fig = pl.figure()
            ax = fig.add_subplot(111, aspect=1.)
            doplot = True
        ax = self.plot(ax=ax, unit=unit, maxval=maxval)
        if maxval is None:
            maxval = np.max(np.append(self.obs, self.est))
        xtext = 0.6 * maxval
        ytext = (0.1 + np.arange(0, len(metrics), 0.1)) * maxval
        mymetrics = self.all()
        for i, metric in enumerate(metrics):
            pl.text(xtext, ytext[i], "%s: %s" % (metric, mymetrics[metric]))
        if not pl.isinteractive() and doplot:
            pl.show()
开发者ID:Maxima86,项目名称:wradlib,代码行数:34,代码来源:verify.py

示例13: hinton

def hinton(W, max_weight=None):
    """ Draws a Hinton diagram for visualizing a weight matrix. 
    """
    if max_weight is None:
        max_weight = 2 ** np.ceil(np.log2(np.max(np.abs(W))))

    # Temporarily disable matplotlib interactive mode if it is on,
    # otherwise this takes forever.
    isinteractive = plt.isinteractive()
    if isinteractive:
        plt.ioff()

    height, width = W.shape
    plt.clf()
    plt.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), "gray")

    plt.axis("off")
    plt.axis("equal")
    for (y, x), w in np.ndenumerate(W):
        if w != 0:
            color = "white" if w > 0 else "black"
            area = min(1, np.abs(w) / max_weight)
            _blob(x + 0.5, height - y - 0.5, area, color)

    if isinteractive:
        plt.ion()
开发者ID:rmkatti,项目名称:surf_2012,代码行数:26,代码来源:hinton.py

示例14: draw_2D_slice_interactive

def draw_2D_slice_interactive(self, p_vals, x_variable, y_variable,
                              range_x, range_y, slider_ranges,
                              **kwargs):
    previous = plt.isinteractive()
    plt.ioff()
    number_of_sliders = len(slider_ranges)
    slider_block = 0.03*number_of_sliders
    fig = plt.figure()
    plt.clf()
    ax = plt.axes([0.1, 0.2+slider_block, 0.8, 0.7-slider_block])
    c_axs = list()
    cdict = dict()
    if 'color_dict' in kwargs:
        cdict.update(kwargs['color_dict'])
    j = 0
    sliders = dict()
    for i in slider_ranges:
        slider_ax = plt.axes([0.1, 0.1+j*0.03, 0.8, 0.02])
        slider = Slider(slider_ax, i, 
                        log10(slider_ranges[i][0]), log10(slider_ranges[i][1]), 
                        valinit=log10(p_vals[i]), color='#AAAAAA'
                        )
        j += 1
        sliders[i] = slider
    update = SliderCallback(self, sliders, c_axs, cdict, 
                            ax, p_vals, x_variable, y_variable, range_x, range_y,
                            **kwargs)
    update(1)
    for i in sliders:
        sliders[i].on_changed(update)
    plt.show()
    plt.interactive(previous)
开发者ID:jlomnitz,项目名称:python-design-space-interface,代码行数:32,代码来源:designspace_plot.py

示例15: plot

    def plot(self, *nodes):
        """
        Plot the distribution of the given nodes (or all nodes)
        """
        if len(nodes) == 0:
            nodes = self.model

        if not plt.isinteractive():
            plt.ion()
            redisable = True
        else:
            redisable = False

        for node in nodes:
            node = self[node]
            if node.has_plotter():
                try:
                    plt.figure(self._figures[node])
                except:
                    f = plt.figure()
                    self._figures[node] = f.number
                plt.clf()
                node.plot()
                plt.suptitle('q(%s)' % node.name)
                plt.draw()
                plt.show()

        if redisable:
            plt.ioff()
开发者ID:zhaoliangvaio,项目名称:bayespy,代码行数:29,代码来源:vmp.py


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