Python matplotlib.org() Examples

The following are 30 code examples for showing how to use matplotlib.org(). 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: kvae   Author: simonkamronn   File: plotting.py    License: MIT License 6 votes vote down vote up
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'):
    # https://matplotlib.org/examples/color/colormaps_reference.html
    patches = []
    for pos in var:
        if shape == 'c':
            patches.append(mpatches.Circle(pos, r))
        elif shape == 'r':
            patches.append(mpatches.RegularPolygon(pos, 4, r))
        elif shape == 's':
            patches.append(mpatches.RegularPolygon(pos, 6, r))

    colors = np.linspace(start_color, .9, len(patches))
    collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.)
    collection.set_array(np.array(colors))
    collection.set_clim(0, 1)
    return collection 
Example 2
Project: stdpopsim   Author: popsim-consortium   File: validation.py    License: GNU General Public License v3.0 6 votes vote down vote up
def custom_violinplot(ax, data, labels):
    """
    Violin plot with a colour scheme shown in the matplotlib gallery.
    https://matplotlib.org/3.1.3/gallery/statistics/customized_violin.html
    """
    inds = list(range(1, len(labels)+1))
    quartile1, medians, quartile3 = np.percentile(data, [25, 50, 75], axis=1)
    parts = ax.violinplot(data, vert=False)
    collections = [parts[x] for x in parts.keys() if x != "bodies"] + parts["bodies"]
    for pc in collections:
        pc.set_facecolor("#D43F3A")
        pc.set_edgecolor("black")
        pc.set_alpha(1)
    ax.scatter(medians, inds, marker='o', fc="white", ec="black", s=30, zorder=3)
    ax.hlines(inds, quartile1, quartile3, color='k', linestyle='-', lw=5)
    ax.set_yticks(inds)
    ax.set_yticklabels(labels) 
Example 3
Project: synthesizer   Author: irmen   File: keyboard_gui.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def do_plot(self, osc):
        if not matplotlib:
            self.statusbar["text"] = "Cannot plot! To plot things, you need to have matplotlib installed!"
            return
        o = self.create_osc(None, None, osc.input_freq.get(), osc, all_oscillators=self.oscillators).blocks()
        blocks = list(itertools.islice(o, self.synth.samplerate//params.norm_osc_blocksize))
        # integrating matplotlib in tikinter, see http://matplotlib.org/examples/user_interfaces/embedding_in_tk2.html
        fig = Figure(figsize=(8, 2), dpi=100)
        axis = fig.add_subplot(111)
        axis.plot(sum(blocks, []))
        axis.set_title("Waveform")
        self.do_close_waveform()
        canvas = FigureCanvasTkAgg(fig, master=self.waveform_area)
        canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        canvas.draw()
        close_waveform = tk.Button(self.waveform_area, text="Close waveform", command=self.do_close_waveform)
        close_waveform.pack(side=tk.RIGHT) 
Example 4
Project: aggregation   Author: zooniverse   File: aggregation_api.py    License: Apache License 2.0 6 votes vote down vote up
def __plot_image__(self,subject_id,axes):
        # TODO - still learning about Matplotlib and axes
        # see http://matplotlib.org/users/artists.html
        fname = self.__image_setup__(subject_id)

        exception = None
        for i in range(10):
            try:
                # fig = plt.figure()
                # ax = fig.add_subplot(1, 1, 1)
                image_file = cbook.get_sample_data(fname)
                image = plt.imread(image_file)
                # fig, ax = plt.subplots()
                im = axes.imshow(image)

                return self.__get_subject_dimension__(subject_id)
            except IOError as e:
                # try downloading that image again
                os.remove(fname)
                self.__image_setup__(subject_id)
                exception = e

        raise exception or Exception('Failed to plot image') 
Example 5
def arg_parse_params():
    """
    SEE: https://docs.python.org/3/library/argparse.html
    :return dict:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-imgs', '--path_images', type=str, required=False,
                        help='path to dir and image pattern', default=PATH_IMAGES)
    parser.add_argument('-csv', '--path_csv', type=str, required=False,
                        help='path to the CSV directory', default=PATH_CSV)
    parser.add_argument('-info', '--path_info', type=str, required=False,
                        help='path to file with complete info', default=None)
    params = vars(parser.parse_args())
    for k in (k for k in params if 'path' in k):
        if not params[k]:
            continue
        params[k] = os.path.abspath(os.path.expanduser(params[k]))
        p = os.path.dirname(params[k]) if '*' in params[k] else params[k]
        assert os.path.exists(p), 'missing: %s' % p
    logging.info('ARG PARAMETERS: \n %r', params)
    return params 
Example 6
Project: wxGlade   Author: wxGlade   File: matplotlib_example.py    License: MIT License 6 votes vote down vote up
def on_button_plot_circle(self, event):
        # draw a circle; canvas coordinates / pixels
        # https://matplotlib.org/api/_as_gen/matplotlib.patches.Circle.html
        x,y,radius = self._get_floats("text_plot_circle_",("x","y","radius"))
        if None in (x,y,radius):
            return None

        axes = self.get_axes()
        colour, width, style = self._get_styles()
        circle = matplotlib.patches.Circle((x,y), radius, figure=self.canvas.figure,
                                color=colour, linewidth=width, linestyle=style)
        circle.set_picker(5)  # enable picking, i.e. the user can select this with the mouse
        axes.add_patch(circle)
        axes.autoscale(True, 'both', True)  # ensure that it is visible
        # show the updates
        self.canvas.draw()
        self.set_history_buttons()

    ####################################################################################################################
    # draw elements on canvas (by pixels)
    # see https://matplotlib.org/api/artist_api.html
    # rectangles, arrows, circles: https://matplotlib.org/api/patches_api.html 
Example 7
Project: wxGlade   Author: wxGlade   File: matplotlib_example.py    License: MIT License 6 votes vote down vote up
def on_button_draw_circle(self, event):
        # draw a circle; canvas coordinates / pixels
        # https://matplotlib.org/api/_as_gen/matplotlib.patches.Circle.html
        x,y,radius = self._get_floats("text_circle_",("x","y","radius"))
        if None in (x,y,radius):
            return None

        colour, width, style = self._get_styles()
        # implement method? self.matplotlib_canvas.draw_rectangle( (x,y), width, height, angle )
        patch = matplotlib.patches.Circle((x,y), radius, figure=self.canvas.figure,
                                color=colour, linewidth=width, linestyle=style)
        patch.set_picker(5)  # enable picking, i.e. the user can select this with the mouse
        self.canvas.figure.patches.append(patch)
        # show the updates
        self.canvas.draw()
        self.set_history_buttons()

    ####################################################################################################################
    # helpers 
Example 8
Project: corrscope   Author: corrscope   File: renderer.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_frame(self) -> ByteBuffer:
        """Returns bytes with shape (h, w, self.bytes_per_pixel).
        The actual return value's shape may be flat.
        """
        self._redraw_over_background()

        canvas = self._fig.canvas

        # Agg is the default noninteractive backend except on OSX.
        # https://matplotlib.org/faq/usage_faq.html
        if not isinstance(canvas, self._canvas_type):
            raise RuntimeError(
                f"oh shit, cannot read data from {obj_name(canvas)} != {self._canvas_type.__name__}"
            )

        buffer_rgb = self._canvas_to_bytes(canvas)
        assert len(buffer_rgb) == self.w * self.h * self.bytes_per_pixel

        return buffer_rgb

    # Pre-rendered background 
Example 9
Project: cate   Author: CCI-Tools   File: plot.py    License: MIT License 6 votes vote down vote up
def plot_data_frame(df: pd.DataFrame,
                    plot_type: str = 'line',
                    file: str = None,
                    **kwargs) -> Figure:
    """
    Plot a data frame.
    This is a wrapper of pandas.DataFrame.plot() function.
    For further documentation please see
    http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html
    :param df: A pandas dataframe to plot
    :param plot_type: Plot type
    :param file: path to a file in which to save the plot
    :param kwargs: Keyword arguments to pass to the underlying
                   pandas.DataFrame.plot function
    """
    if not isinstance(df, pd.DataFrame):
        raise ValidationError('"df" must be of type "pandas.DataFrame"')

    ax = df.plot(kind=plot_type, figsize=(8, 4), **kwargs)
    figure = ax.get_figure()
    if file:
        figure.savefig(file)

    return figure if not in_notebook() else None 
Example 10
Project: kaggle-dr   Author: ilyakava   File: plot_occluded_activations.py    License: MIT License 5 votes vote down vote up
def accumulate_patches_into_heatmaps(self, all_test_output, outpath_prefix=''):
        outpath = "plots/%s_%s.png" % (outpath_prefix, path.splitext(path.basename(self.test_imagepath))[0])
        # http://matplotlib.org/examples/axes_grid/demo_axes_grid.html
        fig = plt.figure()
        grid = AxesGrid(fig, 143, # similar to subplot(143)
                    nrows_ncols = (1, 1))
        orig_img = imread(self.test_imagepath+'.png')
        grid[0].imshow(orig_img)
        grid = AxesGrid(fig, 144, # similar to subplot(144)
                    nrows_ncols = (2, 2),
                    axes_pad = 0.15,
                    label_mode = "1",
                    share_all = True,
                    cbar_location="right",
                    cbar_mode="each",
                    cbar_size="7%",
                    cbar_pad="2%",
                    )

        for klass in xrange(all_test_output.shape[1]):
            accumulator = numpy.zeros(self.ds.image_shape[:2])
            normalizer = numpy.zeros(self.ds.image_shape[:2])
            for n in xrange(self.num_patch_centers):
                i_start,i_end,j_start,j_end = self.nth_patch(n)

                accumulator[i_start:i_end, j_start:j_end] += all_test_output[n,klass]
                normalizer[i_start:i_end, j_start:j_end] += 1
            normalized_img = accumulator / normalizer
            im = grid[klass].imshow(normalized_img, interpolation="nearest", vmin=0, vmax=1)
            grid.cbar_axes[klass].colorbar(im)
        grid.axes_llc.set_xticks([])
        grid.axes_llc.set_yticks([])
        print("Saving figure as: %s" % outpath)
        plt.savefig(outpath, dpi=600, bbox_inches='tight') 
Example 11
Project: AlphaPy   Author: ScottfreeLLC   File: plots.py    License: Apache License 2.0 5 votes vote down vote up
def plot_distribution(df, target, tag='eda', directory=None):
    r"""Display a Distribution Plot.

    Parameters
    ----------
    df : pandas.DataFrame
        The dataframe containing the ``target`` feature.
    target : str
        The target variable for the distribution plot.
    tag : str
        Unique identifier for the plot.
    directory : str, optional
        The full specification of the plot location.

    Returns
    -------
    None : None.

    References
    ----------

    http://seaborn.pydata.org/generated/seaborn.distplot.html

    """

    logger.info("Generating Distribution Plot")

    # Generate the distribution plot

    dist_plot = sns.distplot(df[target])
    dist_fig = dist_plot.get_figure()

    # Save the plot
    write_plot('seaborn', dist_fig, 'distribution_plot', tag, directory)


#
# Function plot_box
# 
Example 12
Project: AlphaPy   Author: ScottfreeLLC   File: plots.py    License: Apache License 2.0 5 votes vote down vote up
def plot_time_series(df, target, tag='eda', directory=None):
    r"""Plot time series data.

    Parameters
    ----------
    df : pandas.DataFrame
        The dataframe containing the ``target`` feature.
    target : str
        The target variable for the time series plot.
    tag : str
        Unique identifier for the plot.
    directory : str, optional
        The full specification of the plot location.

    Returns
    -------
    None : None.

    References
    ----------

    http://seaborn.pydata.org/generated/seaborn.tsplot.html

    """

    logger.info("Generating Time Series Plot")

    # Generate the time series plot

    ts_plot = sns.tsplot(data=df[target])
    ts_fig = ts_plot.get_figure()

    # Save the plot
    write_plot('seaborn', ts_fig, 'time_series_plot', tag, directory)


#
# Function plot_candlestick
# 
Example 13
Project: imageatm   Author: idealo   File: evaluation.py    License: Apache License 2.0 5 votes vote down vote up
def _is_in_ipython_mode(self):
        try:
            __IPYTHON__
            return True

        except NameError:
            ## TODO: Is this obsolete? Please remove!
            # Suppress figure window in terminal
            # https://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear
            import matplotlib
            matplotlib.use('Agg')

            return False 
Example 14
Project: aggregation   Author: zooniverse   File: aggregation_api.py    License: Apache License 2.0 5 votes vote down vote up
def __image_setup__(self,subject_id,download=True):
        """
        get the local file name for a given subject id and downloads that image if necessary
        :param subject_id:
        :return:
        """

        data = self.__panoptes_call__("subjects/"+str(subject_id)+"?")

        # url = str(data["subjects"][0]["locations"][0]["image/jpeg"])

        image_paths = []
        for image in data["subjects"][0]["locations"]:
            if "image/jpeg" in image:
                url = image["image/jpeg"]
            elif "image/png" in image:
                url = image["image/png"]
            else:
                raise Exception('Unknown image type: %s' % image)

            slash_index = url.rfind("/")
            fname = url[slash_index+1:]
            url = "http://zooniverse-static.s3.amazonaws.com/panoptes-uploads.zooniverse.org/production/subject_location/"+url[slash_index+1:]

            path = base_directory+"/Databases/images/"+fname
            image_paths.append(path)

            if not(os.path.isfile(path)):
                if download:
                    print("downloading",url,path)
                    urllib.urlretrieve(url, path)
                # raise ImageNotDownloaded()

        return image_paths 
Example 15
def draw_figure(canvas, figure, loc = (0,0)):

    figure_canvas_agg = FigureCanvasAgg(figure) 
    figure_canvas_agg.draw()
    figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
    canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
    return photo


#------------ Matplotlib code ----------------------
#see https://matplotlib.org/ 
Example 16
Project: dynamo-release   Author: aristoteleo   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_colorbar(ax):
    """https://matplotlib.org/3.1.0/gallery/axes_grid1/demo_colorbar_with_inset_locator.html"""
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes

    axins = inset_axes(ax,
                       width="2.5%",  # width = 5% of parent_bbox width
                       height="20%",  # height : 50%
                       # loc='lower left',
                       # bbox_to_anchor=(1.05, 0., 1, 1),
                       # bbox_transform=ax.transAxes,
                       # borderpad=0,
                       )
    return axins 
Example 17
Project: chemml   Author: hachmannlab   File: visualization.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def matplotlib_font(self, family='DejaVu Sans', size=18, weight='normal', style='normal', variant='normal'):
        """
        The matplotlib_font function sets custom font properties.

        Notes
        -----
        Changing these parameters wil affect all the plots in your working session.

        Parameters
        ----------
        family: string, optional (default = 'normal')
            check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html
        size: integer or string, optional (default = 18)
            check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html
        weight: string, optional (default = 'normal')
            check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html
        style: string, optional (default = 'normal')
            check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html
        variant: string, optional (default = 'normal')
            check this example: https://matplotlib.org/examples/pylab_examples/fonts_demo.html

        Returns
        -------

        """
        matplotlib.rcParams.update(
            {'font.size': size, 'font.weight': weight, 'font.family': family, 'font.style': style,
             'font.variant': variant}) 
Example 18
Project: MAST-ML   Author: uw-cmg   File: plot_helper.py    License: MIT License 5 votes vote down vote up
def make_fig_ax(aspect_ratio=0.5, x_align=0.65, left=0.10):
    """
    Method to make matplotlib figure and axes objects. Using Object Oriented interface from https://matplotlib.org/gallery/api/agg_oo_sgskip.html

    Args:

        aspect_ratio: (float), aspect ratio for figure and axes creation

        x_align: (float), x position to draw edge of figure. Needed so can display stats alongside plot

        left: (float), the leftmost position to draw edge of figure

    Returns:

        fig: (matplotlib fig object), a matplotlib figure object with the specified aspect ratio

        ax: (matplotlib ax object), a matplotlib axes object with the specified aspect ratio

    """
    # Set image aspect ratio:
    w, h = figaspect(aspect_ratio)
    fig = Figure(figsize=(w,h))
    FigureCanvas(fig)

    # Set custom positioning, see this guide for more details:
    # https://python4astronomers.github.io/plotting/advanced.html
    #left   = 0.10
    bottom = 0.15
    right  = 0.01
    top    = 0.05
    width = x_align - left - right
    height = 1 - bottom - top
    ax = fig.add_axes((left, bottom, width, height), frameon=True)
    fig.set_tight_layout(False)
    
    return fig, ax 
Example 19
Project: MAST-ML   Author: uw-cmg   File: plot_helper.py    License: MIT License 5 votes vote down vote up
def make_fig_ax_square(aspect='equal', aspect_ratio=1):
    """
    Method to make square shaped matplotlib figure and axes objects. Using Object Oriented interface from

    https://matplotlib.org/gallery/api/agg_oo_sgskip.html

    Args:

        aspect: (str), 'equal' denotes x and y aspect will be equal (i.e. square)

        aspect_ratio: (float), aspect ratio for figure and axes creation

    Returns:

        fig: (matplotlib fig object), a matplotlib figure object with the specified aspect ratio

        ax: (matplotlib ax object), a matplotlib axes object with the specified aspect ratio

    """
    # Set image aspect ratio:
    w, h = figaspect(aspect_ratio)
    fig = Figure(figsize=(w,h))
    FigureCanvas(fig)
    ax = fig.add_subplot(111, aspect=aspect)

    return fig, ax 
Example 20
Project: corrscope   Author: corrscope   File: renderer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _save_background(self) -> None:
        """ Draw static background. """
        # https://stackoverflow.com/a/8956211
        # https://matplotlib.org/api/animation_api.html#funcanimation
        fig = self._fig

        fig.canvas.draw()
        self.bg_cache = fig.canvas.copy_from_bbox(fig.bbox) 
Example 21
Project: viscm   Author: matplotlib   File: gui.py    License: MIT License 5 votes vote down vote up
def save_colormap(self, filepath):
        with open(filepath, 'w') as f:
            xp, yp, fixed = self.control_point_model.get_control_points()
            rgb, _ = self.cmap_model.get_sRGB(num=256)
            hex_blob = ""
            for color in rgb:
                for component in color:
                    hex_blob += "%02x" % (int(round(component * 255)))
            usage_hints = ["red-green-colorblind-safe", "greyscale-safe"]
            if self.cmtype == "diverging":
                usage_hints.append("diverging")
            elif self.cmtype == "linear":
                usage_hints.append("sequential")
            xp, yp, fixed = self.control_point_model.get_control_points()
            extensions = {"min_Jp" : self.min_Jp,
                          "max_Jp" : self.max_Jp,
                          "xp" : xp,
                          "yp" : yp,
                          "fixed" : fixed,
                          "filter_k" : self.cmap_model.filter_k,
                          "cmtype" : self.cmtype,
                          "uniform_colorspace" : self._uniform_space,
                          "spline_method" : self.method
            }
            json.dump({"content-type": "application/vnd.matplotlib.colormap-v1+json",
                       "name": self.name,
                       "license":"http://creativecommons.org/publicdomain/zero/1.0/",
                       "usage-hints": usage_hints,
                       "colorspace" : "sRGB",
                       "domain" : "continuous",
                       "colors" : hex_blob,
                       "extensions" : {"https://matplotlib.org/viscm" : extensions}
                        },
                        f, indent=4)
        print("Saved") 
Example 22
Project: code-jam-5   Author: python-discord   File: plot.py    License: MIT License 5 votes vote down vote up
def get_color_maps():
        # https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html
        color_maps = ["seismic", "coolwarm", "bwr", "gnuplot2", "jet"]
        return color_maps 
Example 23
Project: code-jam-5   Author: python-discord   File: plot.py    License: MIT License 5 votes vote down vote up
def get_map_format():
        """
        Source:
            https://matplotlib.org/basemap/api/basemap_api.html
        Returns:
            Basemap: Constructed world basemap
        """
        world_map = Basemap(projection="cyl", llcrnrlat=-90, urcrnrlat=90,
                            llcrnrlon=-180, urcrnrlon=180, resolution="c")
        Plotter.draw_map_details(world_map)
        return world_map 
Example 24
Project: dials   Author: dials   File: cluster_unit_cell.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def do_cluster_analysis(crystal_symmetries, params):
    ucs = Cluster.from_crystal_symmetries(crystal_symmetries)

    if params.plot.show or params.plot.name is not None:
        if not params.plot.show:
            import matplotlib

            # http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear
            matplotlib.use("Agg")  # use a non-interactive backend
        import matplotlib.pyplot as plt

        plt.figure("Andrews-Bernstein distance dendogram", figsize=(12, 8))
        ax = plt.gca()
        clusters, cluster_axes = ucs.ab_cluster(
            params.threshold,
            log=params.plot.log,
            ax=ax,
            write_file_lists=False,
            doplot=True,
        )
        print(unit_cell_info(clusters))
        plt.tight_layout()
        if params.plot.name is not None:
            plt.savefig(params.plot.name)
        if params.plot.show:
            plt.show()

    else:
        clusters, cluster_axes = ucs.ab_cluster(
            params.threshold, log=params.plot.log, write_file_lists=False, doplot=False
        )
        print(unit_cell_info(clusters))

    return clusters 
Example 25
def stereographic_projection(points, reference_poles):
    # https://doi.org/10.1107/S0021889868005029
    # J. Appl. Cryst. (1968). 1, 68-70
    # The construction of stereographic projections by computer
    # G. K. Stokes, S. R. Keown and D. J. Dyson

    assert len(reference_poles) == 3
    r_0, r_1, r_2 = reference_poles

    projections = flex.vec2_double()

    for p in points:
        r_i = matrix.col(p)
        # theta is the angle between r_i and the plane normal, r_0
        cos_theta = r_i.cos_angle(r_0)
        if cos_theta < 0:
            r_i = -r_i
            cos_theta = r_i.cos_angle(r_0)

        # alpha is the angle between r_i and r_1
        cos_alpha = r_i.cos_angle(r_1)
        theta = math.acos(cos_theta)
        cos_phi = cos_alpha / math.sin(theta)
        if abs(cos_phi) > 1:
            cos_phi = math.copysign(1, cos_phi)
        phi = math.acos(cos_phi)

        N = r_i.dot(r_2)
        r = math.tan(theta / 2)
        x = r * cos_phi
        y = r * math.sin(phi)
        y = math.copysign(y, N)

        projections.append((x, y))

    return projections 
Example 26
Project: HiCExplorer   Author: deeptools   File: hicPlotAverageRegions.py    License: GNU General Public License v3.0 4 votes vote down vote up
def parse_arguments(args=None):

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        add_help=False,
        description="""
        hicPlotAverage regions plots the data computed by hicAverageRegions. It shows the summed up and averaged regions around
        all given reference points. This tool is useful to plot differences at certain reference points as for example TAD boundaries between samples.
""")

    parserRequired = parser.add_argument_group('Required arguments')

    parserRequired.add_argument('--matrix', '-m',
                                help='The averaged regions file computed by hicAverageRegions (npz file).',
                                required=True)
    parserRequired.add_argument('--outputFile', '-o',
                                help='The averaged regions plot.',
                                required=True)

    parserOpt = parser.add_argument_group('Optional arguments')
    parserOpt.add_argument('--log1p',
                           help='Plot log1p of the matrix values.',
                           action='store_true')

    parserOpt.add_argument('--log',
                           help='Plot log of the matrix values.',
                           action='store_true')
    parserOpt.add_argument('--colorMap',
                           help='Color map to use for the heatmap. Available '
                           'values can be seen here: '
                           'http://matplotlib.org/examples/color/colormaps_reference.html',
                           default='hot_r')
    parserOpt.add_argument('--vMin',
                           help='Minimum score value.',
                           type=float,
                           default=None)

    parserOpt.add_argument('--vMax',
                           help='Maximum score value.',
                           type=float,
                           default=None)
    parserOpt.add_argument('--dpi',
                           help='Resolution of image if'
                           'ouput is a raster graphics image (e.g png, jpg).',
                           type=int,
                           default=300)
    parserOpt.add_argument('--help', '-h', action='help', help='show this help message and exit')

    parserOpt.add_argument('--version', action='version',
                           version='%(prog)s {}'.format(__version__))

    return parser 
Example 27
Project: self_driving_pi_car   Author: felipessalvatore   File: util.py    License: MIT License 4 votes vote down vote up
def plot_confusion_matrix(cm,
                          classes,
                          title,
                          normalize=False,
                          cmap=plt.cm.Oranges,
                          path="confusion_matrix.png"):
    """
    This function plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    'cmap' controls the color plot. colors:

    https://matplotlib.org/1.3.1/examples/color/colormaps_reference.html

    :param cm: confusion matrix
    :type cm: np array
    :param classes: number of classes
    :type classes: int
    :param title: image title
    :type title: str
    :param cmap: plt color map
    :type cmap: plt.cm
    :param path: path to save image
    :type path: str
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    plt.figure(figsize=(9, 9))
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title, fontsize=24, fontweight='bold')
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label', fontweight='bold')
    plt.xlabel('Predicted label', fontweight='bold')
    plt.savefig(path) 
Example 28
Project: learnable-triangulation-pytorch   Author: karfly   File: vis.py    License: MIT License 4 votes vote down vote up
def draw_voxels(voxels, ax, shape=(8, 8, 8), norm=True, alpha=0.1):
    # resize for visualization
    zoom = np.array(shape) / np.array(voxels.shape)
    voxels = skimage.transform.resize(voxels, shape, mode='constant', anti_aliasing=True)
    voxels = voxels.transpose(2, 0, 1)

    if norm and voxels.max() - voxels.min() > 0:
        voxels = (voxels - voxels.min()) / (voxels.max() - voxels.min())

    filled = np.ones(voxels.shape)

    # facecolors
    cmap = plt.get_cmap("Blues")

    facecolors_a = cmap(voxels, alpha=alpha)
    facecolors_a = facecolors_a.reshape(-1, 4)

    facecolors_hex = np.array(list(map(lambda x: matplotlib.colors.to_hex(x, keep_alpha=True), facecolors_a)))
    facecolors_hex = facecolors_hex.reshape(*voxels.shape)

    # explode voxels to perform 3d alpha rendering (https://matplotlib.org/devdocs/gallery/mplot3d/voxels_numpy_logo.html)
    def explode(data):
        size = np.array(data.shape) * 2
        data_e = np.zeros(size - 1, dtype=data.dtype)
        data_e[::2, ::2, ::2] = data
        return data_e

    filled_2 = explode(filled)
    facecolors_2 = explode(facecolors_hex)

    # shrink the gaps
    x, y, z = np.indices(np.array(filled_2.shape) + 1).astype(float) // 2
    x[0::2, :, :] += 0.05
    y[:, 0::2, :] += 0.05
    z[:, :, 0::2] += 0.05
    x[1::2, :, :] += 0.95
    y[:, 1::2, :] += 0.95
    z[:, :, 1::2] += 0.95

    # draw voxels
    ax.voxels(x, y, z, filled_2, facecolors=facecolors_2)

    ax.set_xlabel("z"); ax.set_ylabel("x"); ax.set_zlabel("y")
    ax.invert_xaxis(); ax.invert_zaxis() 
Example 29
Project: BrainRender   Author: BrancoLab   File: colors.py    License: MIT License 4 votes vote down vote up
def colorMap(value, name="jet", vmin=None, vmax=None):
    """Map a real value in range [vmin, vmax] to a (r,g,b) color scale.

    :param value: scalar value to transform into a color
    :type value: float, list
    :param name: color map name (Default value = "jet")
    :type name: str, matplotlib.colors.LinearSegmentedColormap
    :param vmin:  (Default value = None)
    :param vmax:  (Default value = None)
    :returns: return: (r,g,b) color, or a list of (r,g,b) colors.
    .. note:: Most frequently used color maps:
        |colormaps|
        Matplotlib full list:
        .. image:: https://matplotlib.org/1.2.1/_images/show_colormaps.png
    .. tip:: Can also use directly a matplotlib color map:
        :Example:
            .. code-block:: python
                from vtkplotter import colorMap
                import matplotlib.cm as cm
                print( colorMap(0.2, cm.flag, 0, 1) )
                (1.0, 0.809016994374948, 0.6173258487801733)

    """
    if not _mapscales:
        print("-------------------------------------------------------------------")
        print("WARNING : cannot import matplotlib.cm (colormaps will show up gray).")
        print("Try e.g.: sudo apt-get install python3-matplotlib")
        print("     or : pip install matplotlib")
        print("     or : build your own map (see example in basic/mesh_custom.py).")
        return (0.5, 0.5, 0.5)

    if isinstance(name, matplotlib.colors.LinearSegmentedColormap):
        mp = name
    else:
        mp = cm_mpl.get_cmap(name=name)

    if _isSequence(value):
        values = np.array(value)
        if vmin is None:
            vmin = np.min(values)
        if vmax is None:
            vmax = np.max(values)
        values = np.clip(values, vmin, vmax)
        values -= vmin
        values = values / (vmax - vmin)
        cols = []
        mp = cm_mpl.get_cmap(name=name)
        for v in values:
            cols.append(mp(v)[0:3])
        return np.array(cols)
    else:
        value -= vmin
        value /= vmax - vmin
        if value > 0.999:
            value = 0.999
        elif value < 0:
            value = 0
        return mp(value)[0:3] 
Example 30
Project: AlphaPy   Author: ScottfreeLLC   File: plots.py    License: Apache License 2.0 4 votes vote down vote up
def plot_partial_dependence(est, X, features, fnames, tag,
                            n_jobs=-1, verbosity=0, directory=None):
    r"""Display a Partial Dependence Plot.

    Parameters
    ----------
    est : estimator
        The scikit-learn estimator for calculating partial dependence.
    X : numpy array
        The data on which the estimator was trained.
    features : list of int
        Feature numbers of ``X``.
    fnames : list of str
        The feature names to plot.
    tag : str
        Unique identifier for the plot
    n_jobs : int, optional
        The maximum number of parallel jobs.
    verbosity : int, optional
        The amount of logging from 0 (minimum) and higher.
    directory : str
        Directory where the plot will be stored.

    Returns
    -------
    None : None.

    References
    ----------

    http://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html#sphx-glr-auto-examples-ensemble-plot-partial-dependence-py

    """

    logger.info("Generating Partial Dependence Plot")

    # Plot partial dependence

    fig, axs = plot_partial_dependence(est, X, features, feature_names=fnames,
                                       grid_resolution=50, n_jobs=n_jobs,
                                       verbose=verbosity)
    title = "Partial Dependence Plot"
    fig.suptitle(title)
    plt.subplots_adjust(top=0.9)  # tight_layout causes overlap with suptitle

    # Save the plot
    write_plot(model, 'matplotlib', plt, 'partial_dependence', tag, directory)


#
# Function plot_scatter
#