当前位置: 首页>>代码示例>>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;未经允许,请勿转载。