當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。