Python matplotlib.pyplot() Examples

The following are 30 code examples for showing how to use matplotlib.pyplot(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib , or try the search function .

Example 1
Project: neuropythy   Author: noahbenson   File: core.py    License: 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 2
Project: Cheapest-Flights-bot   Author: PhoenixDD   File: Flight Analysis.py    License: 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 3
Project: linguistic-style-transfer   Author: vineetjohn   File: tsne_visualizer.py    License: 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 4
Project: mars   Author: mars-project   File: test_plot.py    License: 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 5
Project: Dropout_BBalpha   Author: YingzhenLi   File: loading_utils.py    License: 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 6
Project: vnpy_crypto   Author: birforce   File: test_var.py    License: 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 7
Project: ngraph-python   Author: NervanaSystems   File: utils.py    License: 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 8
Project: btgym   Author: Kismuz   File: renderer.py    License: 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 9
Project: nussl   Author: nussl   File: utils.py    License: 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 10
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: 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 11
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: 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 12
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: 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 13
Project: Computable   Author: ktraunmueller   File: pylabtools.py    License: 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 14
Project: Ensemble-Bayesian-Optimization   Author: zi-w   File: simple_functions.py    License: 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 15
Project: eht-imaging   Author: achael   File: dynamical_imaging.py    License: 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 16
Project: SpectralMachine   Author: feranick   File: SpectraLearnPredict.py    License: 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 17
Project: SpectralMachine   Author: feranick   File: SpectraLearnPredict.py    License: 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 18
Project: libTLDA   Author: wmkouw   File: viz.py    License: 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 19
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pair_visual(original, adversarial, figure=None):
    """
    This function displays two images: the original and the adversarial sample
    :param original: the original input
    :param adversarial: the input after perterbations have been applied
    :param figure: if we've already displayed images, use the same plot
    :return: the matplot figure to reuse for future samples
    """
    import matplotlib.pyplot as plt

    # Squeeze the image to remove single-dimensional entries from array shape
    original = np.squeeze(original)
    adversarial = np.squeeze(adversarial)

    # Ensure our inputs are of proper shape
    assert(len(original.shape) == 2 or len(original.shape) == 3)

    # To avoid creating figures per input sample, reuse the sample plot
    if figure is None:
        plt.ion()
        figure = plt.figure()
        figure.canvas.set_window_title('Cleverhans: Pair Visualization')

    # Add the images to the plot
    perterbations = adversarial - original
    for index, image in enumerate((original, perterbations, adversarial)):
        figure.add_subplot(1, 3, index + 1)
        plt.axis('off')

        # If the image is 2D, then we have 1 color channel
        if len(image.shape) == 2:
            plt.imshow(image, cmap='gray')
        else:
            plt.imshow(image)

        # Give the plot some time to update
        plt.pause(0.01)

    # Draw the plot and return
    plt.show()
    return figure 
Example 20
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def grid_visual(data):
    """
    This function displays a grid of images to show full misclassification
    :param data: grid data of the form;
        [nb_classes : nb_classes : img_rows : img_cols : nb_channels]
    :return: if necessary, the matplot figure to reuse
    """
    import matplotlib.pyplot as plt

    # Ensure interactive mode is disabled and initialize our graph
    plt.ioff()
    figure = plt.figure()
    figure.canvas.set_window_title('Cleverhans: Grid Visualization')

    # Add the images to the plot
    num_cols = data.shape[0]
    num_rows = data.shape[1]
    num_channels = data.shape[4]
    current_row = 0
    for y in xrange(num_rows):
        for x in xrange(num_cols):
            figure.add_subplot(num_rows, num_cols, (x + 1) + (y * num_cols))
            plt.axis('off')

            if num_channels == 1:
                plt.imshow(data[x, y, :, :, 0], cmap='gray')
            else:
                plt.imshow(data[x, y, :, :, :])

    # Draw the plot and return
    plt.show()
    return figure 
Example 21
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def cortex_rgba_plot_2D(the_map, rgba, axes=None, triangulation=None):
    '''
    cortex_rgba_plot_2D(map, rgba, axes) plots the given cortical map on the given axes using the
      given (n x 4) matrix of vertex colors and yields the resulting polygon collection object.
    cortex_rgba_plot_2D(map, rgba) uses matplotlib.pyplot.gca() for the axes.

    The option triangulation may also be passed if the triangularion object has already been
    created; otherwise it is generated fresh.
    '''
    cmap = colors_to_cmap(rgba)
    zs = np.linspace(0.0, 1.0, the_map.vertex_count)
    return cortex_cmap_plot_2D(the_map, zs, cmap, axes=axes, triangulation=triangulation) 
Example 22
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def end(self, success=True):
        from neuropythy import path_trace
        # we've finished; clean up and make the line
        if success:
            if len(self.xs) < 1: raise ValueError('Drawn line has no points')
            pts = np.transpose([self.xs, self.ys])
            # remove us from the trace meta-data if we're in it
            rd = self.trace.meta_data.get('roi_drawer')
            if rd is self: self.trace.meta_data = self.trace.meta_data.discard('roi_drawer')
            self.trace.persist()
        else: self.trace = None
        if self.line:
            for conn in self.connections:
                self.line.figure.canvas.mpl_disconnect(conn)
        # redraw the final version:
        if self.closed:
            self.xs.append(self.xs[0])
            self.ys.append(self.ys[0])
            self.line.set_data(self.xs, self.ys)
            self.line.figure.canvas.draw()
        matplotlib.pyplot.close(self.line.figure)
        # clear everything
        self.connection = None
        self.line = None
        self.xs = None
        self.ys = None 
Example 23
Project: yatsm   Author: ceholden   File: console.py    License: MIT License 5 votes vote down vote up
def open_interpreter(model, message=None, variables=None, funcs=None):
    """ Opens an (I)Python interpreter

    Args:
        model (YATSM model): Pass YATSM model to work with
        message (str, optional): Additional message to pass to user in banner
        variables (dict of objects, optional): Variables available in (I)Python
            session
        funcs (dict of callable, optional): Functions available in (I)Python
            session

    """
    local = dict(_funcs, model=model, np=np, plt=plt)
    if variables:
        local.update(variables)
    if funcs:
        local.update(funcs)

    banner = """\
        YATSM {yver} Interactive Interpreter (Python {pver})
        Type "help(model)" for info on YATSM model methods.
        NumPy and matplotlib.pyplot are already imported as "np" and "plt".
    """.format(
        yver=__version__,
        pver='.'.join(map(str, sys.version_info[:3])),
        funcs='\n\t'.join([k for k in local])
    )
    banner = textwrap.dedent(banner)
    if isinstance(message, str):
        banner += '\n' + message

    try:
        import IPython
        IPython.InteractiveShell.banner1 = banner
        IPython.start_ipython(argv=[], user_ns=local)
    except:
        code.interact(banner, local=local) 
Example 24
Project: recruit   Author: Frank-qlu   File: style.py    License: Apache License 2.0 5 votes vote down vote up
def _mpl(func):
    if has_mpl:
        yield plt, colors
    else:
        raise ImportError(no_mpl_message.format(func.__name__)) 
Example 25
Project: info-flow-experiments   Author: tadatitam   File: plot.py    License: GNU General Public License v3.0 5 votes vote down vote up
def treatment_feature_histogram(X,y,feat, names):
	obs = np.array([[0.]*len(X[0])]*2)
	for i in range(0, len(y)):
		obs[y[i]] += X[i]
	colors = ['b', 'r', 'g', 'm', 'k']							# Can plot upto 5 different colors
	pos = np.arange(1, len(obs[0])+1)
	width = 0.1     # gives histogram aspect to the bar diagram
	gridLineWidth=0.1
	fig, ax = plt.subplots()
# 	ax.xaxis.grid(True, zorder=0)
# 	ax.yaxis.grid(True, zorder=0)
	matplotlib.rc('xtick', labelsize=1)
# 	matplotlib.gca().tight_layout()
	for i in range(0, len(obs)):
# 		lbl = "treatment "+str(i)
		plt.bar(pos+i*width, obs[i], width, color=colors[i], alpha=0.5, label=names[i])
# 	plt.bar(pos, obs[0], width, color=colors[0], alpha=0.5)
	plt.xticks(pos+width, feat.data, rotation="vertical")		# useful only for categories
	#plt.axis([-1, len(obs[2]), 0, len(ran1)/2+10])
	plt.ylabel("# agents")
	feat.display()
	print obs[0]
	plt.legend()
	# saving:
	(matplotlib.pyplot).tight_layout()
	fig.savefig("./plots/"+"+".join(names)+".eps")
# 	plt.show() 
Example 26
Project: mars   Author: mars-project   File: test_plot.py    License: Apache License 2.0 5 votes vote down vote up
def close(fignum=None):  # pragma: no cover
    from matplotlib.pyplot import get_fignums, close as _close

    if fignum is None:
        for fignum in get_fignums():
            _close(fignum)
    else:
        _close(fignum) 
Example 27
Project: mars   Author: mars-project   File: test_plot.py    License: Apache License 2.0 5 votes vote down vote up
def _check_plot_works(f, filterwarnings="always", **kwargs):  # pragma: no cover
    import matplotlib.pyplot as plt

    ret = None
    with warnings.catch_warnings():
        warnings.simplefilter(filterwarnings)
        try:
            try:
                fig = kwargs["figure"]
            except KeyError:
                fig = plt.gcf()

            plt.clf()

            kwargs.get("ax", fig.add_subplot(211))
            ret = f(**kwargs)

            assert_is_valid_plot_return_object(ret)

            if f is pd.plotting.bootstrap_plot:
                assert "ax" not in kwargs
            else:
                kwargs["ax"] = fig.add_subplot(212)

            ret = f(**kwargs)
            assert_is_valid_plot_return_object(ret)

            with tempfile.TemporaryFile() as path:
                plt.savefig(path)
        finally:
            close(fig)

        return ret 
Example 28
Project: westpa   Author: westpa   File: plotting.py    License: MIT License 5 votes vote down vote up
def __init__(self):
        global matplotlib, pyplot
        
        super(PlottingMixin,self).__init__()
        
        self.matplotlib_avail = (matplotlib is not None and pyplot is not None) 
Example 29
Project: ivre   Author: cea-sec   File: plotdb.py    License: GNU General Public License v3.0 5 votes vote down vote up
def graph3d(mainflt=db.db.nmap.flt_empty, alertflt=None):
    h, p = getgraph(flt=mainflt)
    fig = matplotlib.pyplot.figure()
    if matplotlib.__version__.startswith('0.99'):
        ax = Axes3D(fig)
    else:
        ax = fig.add_subplot(111, projection='3d')
    ax.plot([x / 65535 for x in h], [x % 65535 for x in h],
            [math.log(x, 10) for x in p], '.')
    if alertflt is not None:
        h, p = getgraph(flt=db.db.nmap.flt_and(mainflt, alertflt))
        if h:
            ax.plot([x / 65535 for x in h], [x % 65535 for x in h],
                    [math.log(x, 10) for x in p], '.', c='r')
    matplotlib.pyplot.show() 
Example 30
Project: ivre   Author: cea-sec   File: plotdb.py    License: GNU General Public License v3.0 5 votes vote down vote up
def graph2d(mainflt=db.db.nmap.flt_empty, alertflt=None):
    h, p = getgraph(flt=mainflt)
    fig = matplotlib.pyplot.figure()
    ax = fig.add_subplot(111)
    ax.semilogy(h, p, '.')
    if alertflt is not None:
        h, p = getgraph(flt=db.db.nmap.flt_and(mainflt, alertflt))
        if h:
            ax.semilogy(h, p, '.', c='r')
    matplotlib.pyplot.show()