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


Python matplotlib.org方法代码示例

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


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

示例1: construct_ball_trajectory

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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 
开发者ID:simonkamronn,项目名称:kvae,代码行数:18,代码来源:plotting.py

示例2: custom_violinplot

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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) 
开发者ID:popsim-consortium,项目名称:stdpopsim,代码行数:19,代码来源:validation.py

示例3: do_plot

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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) 
开发者ID:irmen,项目名称:synthesizer,代码行数:19,代码来源:keyboard_gui.py

示例4: __plot_image__

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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') 
开发者ID:zooniverse,项目名称:aggregation,代码行数:25,代码来源:aggregation_api.py

示例5: arg_parse_params

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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 
开发者ID:Borda,项目名称:pyImSegm,代码行数:23,代码来源:gui_annot_center_correction.py

示例6: on_button_plot_circle

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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 
开发者ID:wxGlade,项目名称:wxGlade,代码行数:24,代码来源:matplotlib_example.py

示例7: on_button_draw_circle

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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 
开发者ID:wxGlade,项目名称:wxGlade,代码行数:21,代码来源:matplotlib_example.py

示例8: get_frame

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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 
开发者ID:corrscope,项目名称:corrscope,代码行数:23,代码来源:renderer.py

示例9: plot_data_frame

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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 
开发者ID:CCI-Tools,项目名称:cate,代码行数:26,代码来源:plot.py

示例10: accumulate_patches_into_heatmaps

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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') 
开发者ID:ilyakava,项目名称:kaggle-dr,代码行数:36,代码来源:plot_occluded_activations.py

示例11: plot_distribution

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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
# 
开发者ID:ScottfreeLLC,项目名称:AlphaPy,代码行数:41,代码来源:plots.py

示例12: plot_time_series

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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
# 
开发者ID:ScottfreeLLC,项目名称:AlphaPy,代码行数:41,代码来源:plots.py

示例13: _is_in_ipython_mode

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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 
开发者ID:idealo,项目名称:imageatm,代码行数:15,代码来源:evaluation.py

示例14: __image_setup__

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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 
开发者ID:zooniverse,项目名称:aggregation,代码行数:36,代码来源:aggregation_api.py

示例15: draw_figure

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import org [as 别名]
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/ 
开发者ID:PySimpleGUI,项目名称:PySimpleGUI,代码行数:16,代码来源:10a PSG Plot (Matplotlib numpy pyplot(y=sinx)) .py


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