Python matplotlib.pyplot() Examples

The following are 30 code examples of matplotlib.pyplot(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib , or try the search function .
Example #1
Source File: pylabtools.py    From Computable with MIT License 6 votes vote down vote up
def activate_matplotlib(backend):
    """Activate the given backend and set interactive to True."""

    import matplotlib
    matplotlib.interactive(True)
    
    # Matplotlib had a bug where even switch_backend could not force
    # the rcParam to update. This needs to be set *before* the module
    # magic of switch_backend().
    matplotlib.rcParams['backend'] = backend

    import matplotlib.pyplot
    matplotlib.pyplot.switch_backend(backend)

    # This must be imported last in the matplotlib series, after
    # backend/interactivity choices have been made
    import matplotlib.pylab as pylab

    pylab.show._needmain = False
    # We need to detect at runtime whether show() is called by the user.
    # For this, we wrap it into a decorator which adds a 'called' flag.
    pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) 
Example #2
Source File: SpectraLearnPredict.py    From SpectralMachine with GNU General Public License v3.0 6 votes vote down vote up
def plotProb(clf, R):
    prob = clf.predict_proba(R)[0].tolist()
    print(' Probabilities of this sample within each class: \n')
    for i in range(0,clf.classes_.shape[0]):
        print(' ' + str(clf.classes_[i]) + ': ' + str(round(100*prob[i],2)) + '%')
    import matplotlib.pyplot as plt
    print('\n Stand by: Plotting probabilities for each class... \n')
    plt.title('Probability density per class')
    for i in range(0, clf.classes_.shape[0]):
        plt.scatter(clf.classes_[i], round(100*prob[i],2), label='probability', c = 'red')
    plt.grid(True)
    plt.xlabel('Class')
    plt.ylabel('Probability [%]')
    plt.show()


#************************************ 
Example #3
Source File: dynamical_imaging.py    From eht-imaging with GNU General Public License v3.0 6 votes vote down vote up
def Cont(imG):
#This is meant to create plots similar to the ones from
#https://www.bu.edu/blazars/VLBA_GLAST/3c454.html
#for the visual comparison

    import matplotlib.pyplot as plt
    plt.figure()
    Z = np.reshape(imG.imvec,(imG.xdim,imG.ydim))
    pov = imG.xdim*imG.psize
    pov_mas = pov/(RADPERUAS*1.e3)
    Zmax = np.amax(Z)
    print(Zmax)

    levels = np.array((-0.00125*Zmax,0.00125*Zmax,0.0025*Zmax, 0.005*Zmax, 0.01*Zmax,
                        0.02*Zmax, 0.04*Zmax, 0.08*Zmax, 0.16*Zmax, 0.32*Zmax, 0.64*Zmax))
    CS = plt.contour(Z, levels,
                     origin='lower',
                     linewidths=2,
                     extent=(-pov_mas/2., pov_mas/2., -pov_mas/2., pov_mas/2.))
    plt.show() 
Example #4
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def cortex_cmap_plot_2D(the_map, zs, cmap, vmin=None, vmax=None, axes=None, triangulation=None):
    '''
    cortex_cmap_plot_2D(map, zs, cmap, axes) plots the given cortical map values zs on the given
      axes using the given given color map and yields the resulting polygon collection object.
    cortex_cmap_plot_2D(map, zs, cmap) uses matplotlib.pyplot.gca() for the axes.

    The following options may be passed:
      * triangulation (None) may specify the triangularion object for the mesh if it has already
        been created; otherwise it is generated fresh.
      * axes (None) specify the axes on which to plot; if None, then matplotlib.pyplot.gca() is
        used. If Ellipsis, then a tuple (triangulation, z, cmap) is returned; to recreate the plot,
        one would call:
          axes.tripcolor(triangulation, z, cmap, shading='gouraud', vmin=vmin, vmax=vmax)
      * vmin (default: None) specifies the minimum value for scaling the property when one is passed
        as the color option. None means to use the min value of the property.
      * vmax (default: None) specifies the maximum value for scaling the property when one is passed
        as the color option. None means to use the max value of the property.
    '''
    if triangulation is None:
        triangulation = matplotlib.tri.Triangulation(the_map.coordinates[0], the_map.coordinates[1],
                                                     triangles=the_map.tess.indexed_faces.T)
    if axes is Ellipsis: return (triangulation, zs, cmap)
    return axes.tripcolor(triangulation, zs, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax) 
Example #5
Source File: simple_functions.py    From Ensemble-Bayesian-Optimization with MIT License 6 votes vote down vote up
def plot_f(f, filenm='test_function.eps'):
    # only for 2D functions
    import matplotlib.pyplot as plt
    import matplotlib
    font = {'size': 20}
    matplotlib.rc('font', **font)

    delta = 0.005
    x = np.arange(0.0, 1.0, delta)
    y = np.arange(0.0, 1.0, delta)
    nx = len(x)
    X, Y = np.meshgrid(x, y)

    xx = np.array((X.ravel(), Y.ravel())).T
    yy = f(xx)

    plt.figure()
    plt.contourf(X, Y, yy.reshape(nx, nx), levels=np.linspace(yy.min(), yy.max(), 40))
    plt.xlim([0, 1])
    plt.ylim([0, 1])
    plt.colorbar()
    plt.scatter(f.argmax[0], f.argmax[1], s=180, color='k', marker='+')
    plt.savefig(filenm) 
Example #6
Source File: Flight Analysis.py    From Cheapest-Flights-bot with MIT License 6 votes vote down vote up
def task_3_IQR(flight_data):
    plot=plt.boxplot(flight_data['Price'],patch_artist=True)
    for median in plot['medians']:
        median.set(color='#fc0004', linewidth=2)
    for flier in plot['fliers']:
        flier.set(marker='+', color='#e7298a')
    for whisker in plot['whiskers']:
        whisker.set(color='#7570b3', linewidth=2)
    for cap in plot['caps']:
        cap.set(color='#7570b3', linewidth=2)
    for box in plot['boxes']:
        box.set(color='#7570b3', linewidth=2)
        box.set(facecolor='#1b9e77')
    plt.matplotlib.pyplot.savefig('task_3_iqr.png')
    clean_data=[]
    for index,row in flight_data.loc[flight_data['Price'].isin(plot['fliers'][0].get_ydata())].iterrows():
        clean_data.append([row['Price'],row['Date_of_Flight']])
    return pd.DataFrame(clean_data, columns=['Price', 'Date_of_Flight']) 
Example #7
Source File: SpectraLearnPredict.py    From SpectralMachine with GNU General Public License v3.0 6 votes vote down vote up
def plotMaps(X, Y, A, label):
    print(' Plotting ' + label + ' Map...\n')
    import scipy.interpolate
    xi = np.linspace(min(X), max(X))
    yi = np.linspace(min(Y), max(Y))
    xi, yi = np.meshgrid(xi, yi)

    rbf = scipy.interpolate.Rbf(Y, -X, A, function='linear')
    zi = rbf(xi, yi)
    import matplotlib.pyplot as plt
    plt.imshow(zi, vmin=A.min(), vmax=A.max(), origin='lower',label='data',
               extent=[X.min(), X.max(), Y.min(), Y.max()])
    plt.title(label)
    plt.xlabel('X [um]')
    plt.ylabel('Y [um]')
    plt.show()


#################################################################### 
Example #8
Source File: tsne_visualizer.py    From linguistic-style-transfer with Apache License 2.0 6 votes vote down vote up
def plot_coordinates(coordinates, plot_path, markers, label_names, fig_num):
    matplotlib.use('svg')
    import matplotlib.pyplot as plt

    plt.figure(fig_num)
    for i in range(len(markers) - 1):
        plt.scatter(x=coordinates[markers[i]:markers[i + 1], 0],
                    y=coordinates[markers[i]:markers[i + 1], 1],
                    marker=plot_markers[i % len(plot_markers)],
                    c=colors[i % len(colors)],
                    label=label_names[i], alpha=0.75)

    plt.legend(loc='upper right', fontsize='x-large')
    plt.axis('off')
    plt.savefig(fname=plot_path, format="svg", bbox_inches='tight', transparent=True)
    plt.close() 
Example #9
Source File: pyplot.py    From Computable with MIT License 6 votes vote down vote up
def polar(*args, **kwargs):
    """
    Make a polar plot.

    call signature::

      polar(theta, r, **kwargs)

    Multiple *theta*, *r* arguments are supported, with format
    strings, as in :func:`~matplotlib.pyplot.plot`.

    """
    ax = gca(polar=True)
    ret = ax.plot(*args, **kwargs)
    draw_if_interactive()
    return ret 
Example #10
Source File: pyplot.py    From Computable with MIT License 6 votes vote down vote up
def xlabel(s, *args, **kwargs):
    """
    Set the *x* axis label of the current axis.

    Default override is::

      override = {
          'fontsize'            : 'small',
          'verticalalignment'   : 'top',
          'horizontalalignment' : 'center'
          }

    .. seealso::

        :func:`~matplotlib.pyplot.text`
            For information on how override and the optional args work
    """
    l =  gca().set_xlabel(s, *args, **kwargs)
    draw_if_interactive()
    return l 
Example #11
Source File: test_plot.py    From mars with Apache License 2.0 6 votes vote down vote up
def assert_is_valid_plot_return_object(objs):  # pragma: no cover
    import matplotlib.pyplot as plt

    if isinstance(objs, (pd.Series, np.ndarray)):
        for el in objs.ravel():
            msg = (
                "one of 'objs' is not a matplotlib Axes instance, "
                "type encountered {}".format(repr(type(el).__name__))
            )
            assert isinstance(el, (plt.Axes, dict)), msg
    else:
        msg = (
            "objs is neither an ndarray of Artist instances nor a single "
            "ArtistArtist instance, tuple, or dict, 'objs' is a {}".format(
                repr(type(objs).__name__))
        )
        assert isinstance(objs, (plt.Artist, tuple, dict)), msg 
Example #12
Source File: pyplot.py    From Computable with MIT License 6 votes vote down vote up
def draw():
    """
    Redraw the current figure.

    This is used in interactive mode to update a figure that
    has been altered using one or more plot object method calls;
    it is not needed if figure modification is done entirely
    with pyplot functions, if a sequence of modifications ends
    with a pyplot function, or if matplotlib is in non-interactive
    mode and the sequence of modifications ends with :func:`show` or
    :func:`savefig`.

    A more object-oriented alternative, given any
    :class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
    was created using a :mod:`~matplotlib.pyplot` function, is::

        fig.canvas.draw()


    """
    get_current_fig_manager().canvas.draw() 
Example #13
Source File: utils.py    From nussl with MIT License 6 votes vote down vote up
def visualize_waveform(audio_signal, ch=0, do_mono=False, x_axis='time', **kwargs):
    """
    Wrapper around `librosa.display.waveplot` for usage with AudioSignals.
    
    Args:
        audio_signal (AudioSignal): AudioSignal to plot
        ch (int, optional): Which channel to plot. Defaults to 0.
        do_mono (bool, optional): Make the AudioSignal mono. Defaults to False.
        x_axis (str, optional): x_axis argument to librosa.display.waveplot. Defaults to 'time'.
        kwargs: Additional keyword arguments to librosa.display.waveplot.
    """
    import librosa.display
    import matplotlib.pyplot as plt

    if do_mono:
        audio_signal = audio_signal.to_mono(overwrite=False)
    
    data = np.asfortranarray(audio_signal.audio_data[ch])
    librosa.display.waveplot(data, sr=audio_signal.sample_rate, x_axis=x_axis, **kwargs)
    plt.ylabel('Amplitude') 
Example #14
Source File: loading_utils.py    From Dropout_BBalpha with MIT License 6 votes vote down vote up
def plot_images(ax, images, shape, color = False):
     # finally save to file
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    # flip 0 to 1
    images = 1.0 - images

    images = reshape_and_tile_images(images, shape, n_cols=len(images))
    if color:
        from matplotlib import cm
        plt.imshow(images, cmap=cm.Greys_r, interpolation='nearest')
    else:
        plt.imshow(images, cmap='Greys')
    ax.axis('off') 
Example #15
Source File: renderer.py    From btgym with GNU Lesser General Public License v3.0 6 votes vote down vote up
def initialize_pyplot(self):
        """
        Call me before use!
        [Supposed to be done inside already running server process]
        """
        if not self.ready:
            from multiprocessing import Pipe
            self.out_pipe, self.in_pipe = Pipe()

            if self.plt is None:
                import matplotlib
                matplotlib.use(self.plt_backend, force=True)
                import matplotlib.pyplot as plt

            self.plt = plt
            self.ready = True 
Example #16
Source File: test_var.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_plot_irf(self):
        import matplotlib.pyplot as plt
        self.irf.plot()
        plt.close('all')
        self.irf.plot(plot_stderr=False)
        plt.close('all')

        self.irf.plot(impulse=0, response=1)
        plt.close('all')
        self.irf.plot(impulse=0)
        plt.close('all')
        self.irf.plot(response=0)
        plt.close('all')

        self.irf.plot(orth=True)
        plt.close('all')
        self.irf.plot(impulse=0, response=1, orth=True)
        close_plots() 
Example #17
Source File: utils.py    From ngraph-python with Apache License 2.0 6 votes vote down vote up
def save_plot(niters, loss, args):
    print('Saving training loss-iteration figure...')
    try:
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt

        name = 'Train-{}_hs-{}_lr-{}_bs-{}'.format(args.train_file, args.hs,
                                                   args.lr, args.batch_size)
        plt.title(name)
        plt.plot(niters, loss)
        plt.xlabel('iteration')
        plt.ylabel('loss')
        plt.savefig(name + '.jpg')
        print('{} saved!'.format(name + '.jpg'))

    except ImportError:
        print('matplotlib not installed and no figure is saved.') 
Example #18
Source File: starwarps.py    From eht-imaging with GNU General Public License v3.0 5 votes vote down vote up
def movie(im_List, out='movie.mp4', fps=10, dpi=120):
    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation

    fig = plt.figure()
    frame = im_List[0].imvec #read_auto(filelist[len(filelist)/2])
    fov = im_List[0].psize*im_List[0].xdim
    extent = fov * np.array((1,-1,-1,1)) / 2.
    maxi = np.max(frame)
    im = plt.imshow( np.reshape(frame,[im_List[0].xdim, im_List[0].xdim]) , cmap='hot', extent=extent) #inferno
    plt.colorbar()
    im.set_clim([0,maxi])
    fig.set_size_inches([5,5])
    plt.tight_layout()

    def update_img(n):
        sys.stdout.write('\rprocessing image %i of %i ...' % (n,len(im_List)) )
        sys.stdout.flush()
        im.set_data(np.reshape(im_List[n].imvec, [im_List[n].xdim, im_List[n].xdim]) )
        return im

    ani = animation.FuncAnimation(fig,update_img,len(im_List),interval=1e3/fps)
    writer = animation.writers['ffmpeg'](fps=max(20, fps), bitrate=1e6)
    ani.save(out,writer=writer,dpi=dpi) 
Example #19
Source File: ipython_directive.py    From Computable with MIT License 5 votes vote down vote up
def ensure_pyplot(self):
        if self._pyplot_imported:
            return
        self.process_input_line('import matplotlib.pyplot as plt',
                                store_history=False) 
Example #20
Source File: scrapers.py    From sphinx-gallery with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _import_matplotlib():
    """Import matplotlib safely."""
    # make sure that the Agg backend is set before importing any
    # matplotlib
    import matplotlib
    matplotlib.use('agg')
    matplotlib_backend = matplotlib.get_backend().lower()

    filterwarnings("ignore", category=UserWarning,
                   message='Matplotlib is currently using agg, which is a'
                           ' non-GUI backend, so cannot show the figure.')

    if matplotlib_backend != 'agg':
        raise ExtensionError(
            "Sphinx-Gallery relies on the matplotlib 'agg' backend to "
            "render figures and write them to files. You are "
            "currently using the {} backend. Sphinx-Gallery will "
            "terminate the build now, because changing backends is "
            "not well supported by matplotlib. We advise you to move "
            "sphinx_gallery imports before any matplotlib-dependent "
            "import. Moving sphinx_gallery imports at the top of "
            "your conf.py file should fix this issue"
            .format(matplotlib_backend))

    import matplotlib.pyplot as plt
    return matplotlib, plt 
Example #21
Source File: deep_autoencoder.py    From WannaPark with GNU General Public License v3.0 5 votes vote down vote up
def plot_helper(x):
    import matplotlib
    import matplotlib.pyplot as plt
    x = np.reshape(x, (-1, 28))
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.matshow(x, cmap = matplotlib.cm.binary)
    plt.xticks(np.array([]))
    plt.yticks(np.array([]))
    plt.show() 
Example #22
Source File: backend_template.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def show(*, block=None):
    """
    For image backends - is not required.
    For GUI backends - show() is usually the last line of a pyplot script and
    tells the backend that it is time to draw.  In interactive mode, this
    should do nothing.
    """
    for manager in Gcf.get_all_fig_managers():
        # do something to display the GUI
        pass 
Example #23
Source File: utils.py    From nussl with MIT License 5 votes vote down vote up
def visualize_gradient_flow(named_parameters, n_bins=50):
    """
    Visualize the gradient flow through the named parameters of a PyTorch model. 

    Plots the gradients flowing through different layers in the net during training.
    Can be used for checking for possible gradient vanishing / exploding problems.

    Usage: Plug this function in Trainer class after loss.backwards() as 
    "visualize_gradient_flow(self.model.named_parameters())" to visualize 
    the gradient flow
    
    Args:
        named_parameters (generator): Generator object yielding name and parameters
          for each layer in a PyTorch model.
        n_bins (int): Number of bins to use for each histogram. Defaults to 50.
    """
    import matplotlib.pyplot as plt

    data = []

    for n, p in named_parameters:
        if p.requires_grad and "bias" not in n:
            if p.grad is not None:
                _data = p.grad.cpu().data.numpy().flatten()
                lower = np.percentile(_data, 10)
                upper = np.percentile(_data, 90)
                _data = _data[_data >= lower]
                _data = _data[_data <= upper]
                n = n.split('layers.')[-1]
                data.append((n, _data, np.abs(_data).mean()))

    _data = [d[1] for d in sorted(data, key=lambda x: x[-1])]
    _names = [d[0] for d in sorted(data, key=lambda x: x[-1])]

    plt.hist(_data, len(_data) * n_bins, histtype='step', fill=False,
             stacked=True, label=_names)

    plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2) 
Example #24
Source File: wl_fig.py    From Wordless with GNU General Public License v3.0 5 votes vote down vote up
def show_fig():
    if platform.system() in ['Windows', 'Linux']:
        matplotlib.pyplot.get_current_fig_manager().window.showMaximized()
    # Do not maximize the window to avoid segfault on macOS
    elif platform.system() == 'Darwin':
        matplotlib.pyplot.show() 
Example #25
Source File: testing.py    From cesiumpy with Apache License 2.0 5 votes vote down vote up
def _skip_if_no_matplotlib():
    try:
        import matplotlib
        matplotlib.use('Agg')
    except ImportError:
        import nose
        raise nose.SkipTest("no matplotlib.pyplot module") 
Example #26
Source File: SpectraLearnPredict.py    From SpectralMachine with GNU General Public License v3.0 5 votes vote down vote up
def plotTrainData(A, En, R, plotAllSpectra, learnFileRoot):
    import matplotlib.pyplot as plt
    if plotDef.plotAllSpectra == True:
        step = 1
        learnFileRoot = learnFileRoot + '_full-set'
    else:
        step = plotDef.stepSpectraPlot
        learnFileRoot = learnFileRoot + '_partial-' + str(step)

    print(' Plotting Training dataset in: ' + learnFileRoot + '.png\n')
    if preprocDef.Ynorm ==True:
        plt.title('Normalized Training Data')
    else:
        plt.title('Training Data')
    for i in range(0,A.shape[0], step):
        plt.plot(En, A[i,:], label='Training data')
    plt.plot(En, R[0,:], linewidth = 4, label='Sample data')
    plt.xlabel('Raman shift [1/cm]')
    plt.ylabel('Raman Intensity [arb. units]')

    plt.savefig(learnFileRoot + '.png', dpi = 160, format = 'png')  # Save plot

    if plotDef.showTrainingDataPlot == True:
        plt.show()

    plt.close()


#************************************ 
Example #27
Source File: neuagent.py    From dl4ir-webnav with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def vis_att(pages_idx, query, alpha, wiki, vocab, idx):
    rows = [prm.root_page.title()]
    for pageidx in pages_idx[:-1]:
        if pageidx != -1:
            rows.append(wiki.get_article_title(pageidx).decode('utf-8', 'ignore').title())
        else:
            break
            #rows.append('Stop')

    rows = rows[::-1]

    columns = []
    for word in wordpunct_tokenize(query):
        if word.lower() in vocab:
            columns.append(str(word))
    columns = columns[:prm.max_words_query*prm.n_consec]

    alpha = alpha[:len(rows),:len(columns)]
    alpha = alpha[::-1]

    fig,ax=plt.subplots(figsize=(27,10))
    #Advance color controls
    norm = matplotlib.colors.Normalize(0,1)
    im = ax.pcolor(alpha,cmap=plt.cm.gray,edgecolors='w',norm=norm)
    fig.colorbar(im)
    ax.set_xticks(np.arange(0,len(columns))+0.5)
    ax.set_yticks(np.arange(0,len(rows))+0.5)
    ax.tick_params(axis='x', which='minor', pad=15)
    # Here we position the tick labels for x and y axis
    ax.xaxis.tick_bottom()
    ax.yaxis.tick_left()
    ax.axis('tight') # correcting pyplot bug that add extra white columns.
    plt.xticks(rotation=90)
    fig.subplots_adjust(bottom=0.2)
    fig.subplots_adjust(left=0.2)
    #Values against each labels
    ax.set_xticklabels(columns,minor=False,fontsize=18)
    ax.set_yticklabels(rows,minor=False,fontsize=18)
    plt.savefig('vis' + str(idx) + '.svg')
    plt.close() 
Example #28
Source File: SOMPlots.py    From susi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_estimation_map(estimation_map, cbar_label="Variable in unit",
                        cmap="viridis", fontsize=20):
    """[summary]

    Parameters
    ----------
    estimation_map : np.array
        Estimation map of the size (n_rows, n_columns)
    cbar_label : str, optional
        Label of the colorbar, by default "Variable in unit"
    cmap : str, optional (default="viridis")
        Colormap
    fontsize : int, optional (default=20)
        Fontsize of the labels

    Returns
    -------
    ax : pyplot.axis
        Plot axis

    """
    _, ax = plt.subplots(1, 1, figsize=(7, 5))
    img = ax.imshow(estimation_map, cmap=cmap)
    ax.set_xlabel("SOM columns", fontsize=fontsize)
    ax.set_ylabel("SOM rows", fontsize=fontsize)
    # ax.set_xticklabels(fontsize=fontsize)
    # ax.set_yticklabels(fontsize=fontsize)
    ax.tick_params(axis='both', which='major', labelsize=fontsize)

    # colorbar
    cbar = plt.colorbar(img, ax=ax)
    cbar.ax.tick_params(labelsize=fontsize)
    cbar.ax.set_ylabel(cbar_label, fontsize=fontsize, labelpad=10)
    for label in cbar.ax.xaxis.get_ticklabels()[::2]:
        label.set_visible(False)

    plt.grid(b=False)

    return ax 
Example #29
Source File: viz.py    From libTLDA with MIT License 5 votes vote down vote up
def plotc(parameters, ax=[], color='k', gridsize=(101, 101)):
    """
    Plot a linear classifier in a 2D scatterplot.

    INPUT   (1) tuple 'parameters': consists of a list of class proportions
                (1 by K classes), an array of class means (K classes by
                D features), an array of class-covariance matrices (D features
                by D features by K classes)
            (2) object 'ax': axes of a pyplot figure or subject (def: empty)
            (3) str 'colors': colors of the contours in the plot (def: 'k')
            (4) tuple 'gridsize': number of points in the grid
                (def: (101, 101))
    OUTPUT  None
    """
    # Check for figure object
    if fig:
        ax = fig.gca()
    else:
        fig, ax = plt.subplots()

    # Get axes limits
    xl = ax.get_xlim()
    yl = ax.get_ylim()

    # Define grid
    gx = np.linspace(xl[0], xl[1], gridsize[0])
    gy = np.linspace(yl[0], yl[1], gridsize[1])
    x, y = np.meshgrid(gx, gy)
    xy = np.vstack((x.ravel(), y.ravel())).T

    # Values of grid
    z = np.dot(xy, parameters[:-1, :]) + parameters[-1, :]
    z = np.reshape(z[:, 0] - z[:, 1], gridsize)

    # Plot grid
    ax.contour(x, y, z, levels=0, colors=colors) 
Example #30
Source File: pyplot.py    From Computable with MIT License 5 votes vote down vote up
def rcdefaults():
    matplotlib.rcdefaults()
    draw_if_interactive()


# The current "image" (ScalarMappable) is retrieved or set
# only via the pyplot interface using the following two
# functions: