當前位置: 首頁>>代碼示例>>Python>>正文


Python pyplot.rcParams方法代碼示例

本文整理匯總了Python中matplotlib.pyplot.rcParams方法的典型用法代碼示例。如果您正苦於以下問題:Python pyplot.rcParams方法的具體用法?Python pyplot.rcParams怎麽用?Python pyplot.rcParams使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在matplotlib.pyplot的用法示例。


在下文中一共展示了pyplot.rcParams方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: plot

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def plot(token_counts, title='MSR語料庫詞頻統計', ylabel='詞頻'):
    from matplotlib import pyplot as plt
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用來正常顯示中文標簽
    plt.rcParams['axes.unicode_minus'] = False  # 用來正常顯示負號
    fig = plt.figure(
        # figsize=(8, 6)
    )
    ax = fig.add_subplot(111)
    token_counts = list(zip(*token_counts))
    num_elements = np.arange(len(token_counts[0]))
    top_offset = max(token_counts[1]) + len(str(max(token_counts[1])))
    ax.set_title(title)
    ax.set_xlabel('詞語')
    ax.set_ylabel(ylabel)
    ax.xaxis.set_label_coords(1.05, 0.015)
    ax.set_xticks(num_elements)
    ax.set_xticklabels(token_counts[0], rotation=55, verticalalignment='top')
    ax.set_ylim([0, top_offset])
    ax.set_xlim([-1, len(token_counts[0])])
    rects = ax.plot(num_elements, token_counts[1], linewidth=1.5)
    plt.show() 
開發者ID:hankcs,項目名稱:pyhanlp,代碼行數:23,代碼來源:zipf_law.py

示例2: _external_legend

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def _external_legend(save_path, legend_styles, legend_height):
    with plt.style.context([vis_styles.STYLES[style] for style in legend_styles]):
        width, height = plt.rcParams["figure.figsize"]
        height = legend_height
        legend_fig = plt.figure(figsize=(width, height))

        handles, labels = _make_handles()
        legend_fig.legend(
            handles=handles,
            labels=labels,
            loc="lower left",
            mode="expand",
            ncol=len(handles),
            bbox_to_anchor=(0.0, 0.0, 1.0, 1.0),
        )
        legend_fig.savefig(save_path)
        plt.close(legend_fig) 
開發者ID:HumanCompatibleAI,項目名稱:adversarial-policies,代碼行數:19,代碼來源:visualize.py

示例3: heatmap_one_col

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def heatmap_one_col(single_env, col, cbar, xlabel, ylabel, cmap="Blues"):
    width, height = plt.rcParams["figure.figsize"]
    if xlabel:
        height += 0.17
    fig = plt.figure(figsize=(width, height))

    cbar_width = 0.15 if cbar else 0.0
    gridspec_kw = {
        "left": 0.2,
        "right": 0.98 - cbar_width,
        "bottom": 0.28,
        "top": 0.95,
        "wspace": 0.05,
        "hspace": 0.05,
    }
    single_env *= 100 / num_episodes(single_env)  # convert to percentages

    _pretty_heatmap(
        single_env, col, cmap, fig, gridspec_kw, xlabel=xlabel, ylabel=ylabel, cbar_width=cbar_width
    )
    return fig 
開發者ID:HumanCompatibleAI,項目名稱:adversarial-policies,代碼行數:23,代碼來源:util.py

示例4: split_long_title

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def split_long_title(title: str) -> str:
    """Splits a long title around the middle comma
    """
    if len(title) <= 60:
        return title
    comma_indices = np.where(np.array([c for c in title]) == ",")[0]
    if not comma_indices.size:
        return title
    best_index = comma_indices[np.argmin(abs(comma_indices - len(title) // 2))]
    title = title[: (best_index + 1)] + "\n" + title[(best_index + 1):]
    return title


# @contextlib.contextmanager
# def xticks_on_top() -> tp.Iterator[None]:
#     values_for_top = {'xtick.bottom': False, 'xtick.labelbottom': False,
#                       'xtick.top': True, 'xtick.labeltop': True}
#     defaults = {x: plt.rcParams[x] for x in values_for_top if x in plt.rcParams}
#     plt.rcParams.update(values_for_top)
#     yield
#     plt.rcParams.update(defaults) 
開發者ID:facebookresearch,項目名稱:nevergrad,代碼行數:23,代碼來源:plotting.py

示例5: vis

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def vis(embed, vis_alg='PCA', pool_alg='REDUCE_MEAN'):
    plt.close()
    fig = plt.figure()
    plt.rcParams['figure.figsize'] = [21, 7]
    for idx, ebd in enumerate(embed):
        ax = plt.subplot(2, 6, idx + 1)
        vis_x = ebd[:, 0]
        vis_y = ebd[:, 1]
        plt.scatter(vis_x, vis_y, c=subset_label, cmap=ListedColormap(["blue", "green", "yellow", "red"]), marker='.',
                    alpha=0.7, s=2)
        ax.set_title('pool_layer=-%d' % (idx + 1))
    plt.tight_layout()
    plt.subplots_adjust(bottom=0.1, right=0.95, top=0.9)
    cax = plt.axes([0.96, 0.1, 0.01, 0.3])
    cbar = plt.colorbar(cax=cax, ticks=range(num_label))
    cbar.ax.get_yaxis().set_ticks([])
    for j, lab in enumerate(['ent.', 'bus.', 'sci.', 'heal.']):
        cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center', rotation=270)
    fig.suptitle('%s visualization of BERT layers using "bert-as-service" (-pool_strategy=%s)' % (vis_alg, pool_alg),
                 fontsize=14)
    plt.show() 
開發者ID:hanxiao,項目名稱:bert-as-service,代碼行數:23,代碼來源:example7.py

示例6: _anim_rst

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def _anim_rst(anim, image_path, gallery_conf):
    from matplotlib.animation import ImageMagickWriter
    # output the thumbnail as the image, as it will just be copied
    # if it's the file thumbnail
    fig = anim._fig
    image_path = image_path.replace('.png', '.gif')
    fig_size = fig.get_size_inches()
    thumb_size = gallery_conf['thumbnail_size']
    use_dpi = round(
        min(t_s / f_s for t_s, f_s in zip(thumb_size, fig_size)))
    # FFmpeg is buggy for GIFs
    if ImageMagickWriter.isAvailable():
        writer = 'imagemagick'
    else:
        writer = None
    anim.save(image_path, writer=writer, dpi=use_dpi)
    html = anim._repr_html_()
    if html is None:  # plt.rcParams['animation.html'] == 'none'
        html = anim.to_jshtml()
    html = indent(html, '         ')
    return _ANIMATION_RST.format(html) 
開發者ID:sphinx-gallery,項目名稱:sphinx-gallery,代碼行數:23,代碼來源:scrapers.py

示例7: print_figure

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def print_figure(fig, fmt='png'):
    """Convert a figure to svg or png for inline display."""
    from matplotlib import rcParams
    # When there's an empty figure, we shouldn't return anything, otherwise we
    # get big blank areas in the qt console.
    if not fig.axes and not fig.lines:
        return

    fc = fig.get_facecolor()
    ec = fig.get_edgecolor()
    bytes_io = BytesIO()
    dpi = rcParams['savefig.dpi']
    if fmt == 'retina':
        dpi = dpi * 2
        fmt = 'png'
    fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight',
                            facecolor=fc, edgecolor=ec, dpi=dpi)
    data = bytes_io.getvalue()
    return data 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:21,代碼來源:pylabtools.py

示例8: activate_matplotlib

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
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) 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:24,代碼來源:pylabtools.py

示例9: mpl_style_cb

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def mpl_style_cb(key):
    import sys
    from pandas.tools.plotting import mpl_stylesheet
    global style_backup

    val = cf.get_option(key)

    if 'matplotlib' not in sys.modules.keys():
        if not(val):  # starting up, we get reset to None
            return val
        raise Exception("matplotlib has not been imported. aborting")

    import matplotlib.pyplot as plt

    if val == 'default':
        style_backup = dict([(k, plt.rcParams[k]) for k in mpl_stylesheet])
        plt.rcParams.update(mpl_stylesheet)
    elif not val:
        if style_backup:
            plt.rcParams.update(style_backup)

    return val 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:24,代碼來源:config_init.py

示例10: analysis_mobile

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def analysis_mobile(self):
        # self.record_result('<strong style="color: black; font-size: 24px;">正在分析該商品不同省份的購買量...</strong>')

        fig_size = plt.rcParams["figure.figsize"]
        plt.figure(figsize = (2.4, 2.4))

        obj = self.data_frame['is_mobile']
        obj = obj.value_counts()

        obj = obj.rename({1: '移動端', 0: 'PC'})
        plt.pie(x = obj.values, autopct = '%.0f%%', radius = 0.7, labels = obj.index, startangle = 180)

        plt.title('該商品移動/ PC 購買比例')

        plt.tight_layout()
        filename = '%s_mobile.png' % self.product_id
        plt.savefig('%s/%s' % (utils.get_save_image_path(), filename))
        plt.figure(figsize = fig_size)
        plt.clf()
        result = utils.get_image_src(filename = filename)
        self.record_result(result, type = 'image')

    # 分析購買後評論的時間分布 
開發者ID:awolfly9,項目名稱:jd_analysis,代碼行數:25,代碼來源:analysis_jd_item.py

示例11: _default_color_cycle

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def _default_color_cycle():
    c = plt.rcParams['axes.prop_cycle']
    colors = c.by_key().get("color")
    if not colors:
        colors = [
            '#1f77b4',
            '#ff7f0e',
            '#2ca02c',
            '#d62728',
            '#9467bd',
            '#8c564b',
            '#e377c2',
            '#7f7f7f',
            '#bcbd22',
            '#17becf'
        ]
    return colors 
開發者ID:mobiusklein,項目名稱:ms_deisotope,代碼行數:19,代碼來源:plot.py

示例12: setup_latex_env_notebook

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def setup_latex_env_notebook(pf, latexExists):
    """ This is needed for use of the latex_envs notebook extension
    which allows the use of environments in Markdown.

    Parameters
    -----------
    pf: str (platform)
        output of determine_platform()
    """
    import os
    from matplotlib import rc
    import matplotlib.pyplot as plt
    plt.rc('font', family='serif')
    plt.rc('text', usetex=latexExists)
    if latexExists:
        latex_preamble = r'\usepackage{amsmath}\usepackage{amsfonts}\usepackage[T1]{fontenc}'
        latexdefs_path = os.getcwd()+'/latexdefs.tex'
        if os.path.isfile(latexdefs_path):
            latex_preamble = latex_preamble+r'\input{'+latexdefs_path+r'}'
        else: # the required latex_envs package needs this file to exist even if it is empty
            from pathlib import Path
            Path(latexdefs_path).touch()
        plt.rcParams['text.latex.preamble'] = latex_preamble 
開發者ID:econ-ark,項目名稱:HARK,代碼行數:25,代碼來源:utilities.py

示例13: plot_row_colors

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def plot_row_colors(C, fig_size=6, title=None):
    """
    Plot rows of C as colors (RGB)

    :param C: An array N x 3 where the rows are considered as RGB colors.
    :return:
    """
    assert isinstance(C, np.ndarray), "C must be a numpy array."
    assert C.ndim == 2, "C must be 2D."
    assert C.shape[1] == 3, "C must have 3 columns."

    N = C.shape[0]
    range255 = C.max() > 1.0  # quick check to see if we have an image in range [0,1] or [0,255].
    plt.rcParams['figure.figsize'] = (fig_size, fig_size)
    for i in range(N):
        if range255:
            plt.plot([0, 1], [N - 1 - i, N - 1 - i], c=C[i] / 255, linewidth=20)
        else:
            plt.plot([0, 1], [N - 1 - i, N - 1 - i], c=C[i], linewidth=20)
    if title is not None:
        plt.title(title)
    plt.axis("off")
    plt.axis([0, 1, -0.5, N-0.5]) 
開發者ID:Peter554,項目名稱:StainTools,代碼行數:25,代碼來源:visualization.py

示例14: plot_image

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def plot_image(image, show=True, fig_size=10, title=None):
    """
    Plot an image (np.array).
    Caution: Rescales image to be in range [0,1].

    :param image: RGB uint8
    :param show: plt.show() now?
    :param fig_size: Size of largest dimension
    :param title: Image title
    :return:
    """
    image = image.astype(np.float32)
    m, M = image.min(), image.max()
    if fig_size is not None:
        plt.rcParams['figure.figsize'] = (fig_size, fig_size)
    else:
        plt.imshow((image - m) / (M - m))
    if title is not None:
        plt.title(title)
    plt.axis("off")
    if show:
        plt.show() 
開發者ID:Peter554,項目名稱:StainTools,代碼行數:24,代碼來源:visualization.py

示例15: plot_colored_circles

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import rcParams [as 別名]
def plot_colored_circles(ax, prng, nb_samples=15):
    """Plot circle patches.

    NB: draws a fixed amount of samples, rather than using the length of
    the color cycle, because different styles may have different numbers
    of colors.
    """
    for sty_dict, j in zip(plt.rcParams['axes.prop_cycle'], range(nb_samples)):
        ax.add_patch(plt.Circle(prng.normal(scale=3, size=2),
                                radius=1.0, color=sty_dict['color']))
    # Force the limits to be the same across the styles (because different
    # styles may have different numbers of available colors).
    ax.set_xlim([-4, 8])
    ax.set_ylim([-5, 6])
    ax.set_aspect('equal', adjustable='box')  # to plot circles as circles
    return ax 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:18,代碼來源:style_sheets_reference.py


注:本文中的matplotlib.pyplot.rcParams方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。