• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python matplotlib.rc_context函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test_Bug_2543

def test_Bug_2543():
    # Test that it possible to add all values to itself / deepcopy
    # This was not possible because validate_bool_maybe_none did not
    # accept None as an argument.
    # https://github.com/matplotlib/matplotlib/issues/2543
    # We filter warnings at this stage since a number of them are raised
    # for deprecated rcparams as they should. We don't want these in the
    # printed in the test suite.
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore',
                                category=MatplotlibDeprecationWarning)
        with mpl.rc_context():
            _copy = mpl.rcParams.copy()
            for key in _copy:
                mpl.rcParams[key] = _copy[key]
        with mpl.rc_context():
            _deep_copy = copy.deepcopy(mpl.rcParams)
        # real test is that this does not raise
        assert validate_bool_maybe_none(None) is None
        assert validate_bool_maybe_none("none") is None

    with pytest.raises(ValueError):
        validate_bool_maybe_none("blah")
    with pytest.raises(ValueError):
        validate_bool(None)
    with pytest.raises(ValueError):
        with mpl.rc_context():
            mpl.rcParams['svg.fonttype'] = True
开发者ID:jklymak,项目名称:matplotlib,代码行数:28,代码来源:test_rcparams.py


示例2: test_Bug_2543

def test_Bug_2543():
    # Test that it possible to add all values to itself / deepcopy
    # This was not possible because validate_bool_maybe_none did not
    # accept None as an argument.
    # https://github.com/matplotlib/matplotlib/issues/2543
    # We filter warnings at this stage since a number of them are raised
    # for deprecated rcparams as they should. We dont want these in the
    # printed in the test suite.
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore',
                                message='.*(deprecated|obsolete)',
                                category=UserWarning)
        with mpl.rc_context():
            _copy = mpl.rcParams.copy()
            for key in six.iterkeys(_copy):
                mpl.rcParams[key] = _copy[key]
            mpl.rcParams['text.dvipnghack'] = None
        with mpl.rc_context():
            from copy import deepcopy
            _deep_copy = deepcopy(mpl.rcParams)
        # real test is that this does not raise
        assert_true(validate_bool_maybe_none(None) is None)
        assert_true(validate_bool_maybe_none("none") is None)
        _fonttype = mpl.rcParams['svg.fonttype']
        assert_true(_fonttype == mpl.rcParams['svg.embed_char_paths'])
        with mpl.rc_context():
            mpl.rcParams['svg.embed_char_paths'] = False
            assert_true(mpl.rcParams['svg.fonttype'] == "none")
开发者ID:CallaJun,项目名称:hackprince,代码行数:28,代码来源:test_rcparams.py


示例3: test_rcparams

def test_rcparams():

    usetex = mpl.rcParams['text.usetex']
    linewidth = mpl.rcParams['lines.linewidth']

    # test context given dictionary
    with mpl.rc_context(rc={'text.usetex': not usetex}):
        assert mpl.rcParams['text.usetex'] == (not usetex)
    assert mpl.rcParams['text.usetex'] == usetex

    # test context given filename (mpl.rc sets linewdith to 33)
    with mpl.rc_context(fname=fname):
        assert mpl.rcParams['lines.linewidth'] == 33
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context given filename and dictionary
    with mpl.rc_context(fname=fname, rc={'lines.linewidth': 44}):
        assert mpl.rcParams['lines.linewidth'] == 44
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test rc_file
    try:
        mpl.rc_file(fname)
        assert mpl.rcParams['lines.linewidth'] == 33
    finally:
        mpl.rcParams['lines.linewidth'] = linewidth
开发者ID:123jefferson,项目名称:MiniBloq-Sparki,代码行数:26,代码来源:test_rcparams.py


示例4: test_rcparams

def test_rcparams():
    mpl.rc('text', usetex=False)
    mpl.rc('lines', linewidth=22)

    usetex = mpl.rcParams['text.usetex']
    linewidth = mpl.rcParams['lines.linewidth']
    fname = os.path.join(os.path.dirname(__file__), 'test_rcparams.rc')

    # test context given dictionary
    with mpl.rc_context(rc={'text.usetex': not usetex}):
        assert mpl.rcParams['text.usetex'] == (not usetex)
    assert mpl.rcParams['text.usetex'] == usetex

    # test context given filename (mpl.rc sets linewidth to 33)
    with mpl.rc_context(fname=fname):
        assert mpl.rcParams['lines.linewidth'] == 33
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context given filename and dictionary
    with mpl.rc_context(fname=fname, rc={'lines.linewidth': 44}):
        assert mpl.rcParams['lines.linewidth'] == 44
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test rc_file
    mpl.rc_file(fname)
    assert mpl.rcParams['lines.linewidth'] == 33
开发者ID:jklymak,项目名称:matplotlib,代码行数:26,代码来源:test_rcparams.py


示例5: test_to_string

 def test_to_string(self):
     # test without latex
     with rc_context(rc={'text.usetex': False}):
         assert to_string('test') == 'test'
         assert to_string(4.0) == '4.0'
         assert to_string(8) == '8'
     with rc_context(rc={'text.usetex': True}):
         assert to_string('test') == 'test'
         assert to_string(2000) == r'2\!\!\times\!\!10^{3}'
         assert to_string(8) == '8'
开发者ID:stefco,项目名称:gwpy,代码行数:10,代码来源:test_plotter.py


示例6: test_rcparams_reset_after_fail

def test_rcparams_reset_after_fail():

    # There was previously a bug that meant that if rc_context failed and
    # raised an exception due to issues in the supplied rc parameters, the
    # global rc parameters were left in a modified state.

    with mpl.rc_context(rc={'text.usetex': False}):

        assert mpl.rcParams['text.usetex'] is False

        with assert_raises(KeyError):
            with mpl.rc_context(rc=OrderedDict([('text.usetex', True),('test.blah', True)])):
                pass

        assert mpl.rcParams['text.usetex'] is False
开发者ID:Jajauma,项目名称:dotfiles,代码行数:15,代码来源:test_rcparams.py


示例7: _init_axis

    def _init_axis(self, fig, axis):
        """
        Return an axis which may need to be initialized from
        a new figure.
        """
        if not fig and self._create_fig:
            rc_params = self.fig_rcparams
            if self.fig_latex:
                rc_params['text.usetex'] = True
            with mpl.rc_context(rc=rc_params):
                fig = plt.figure()
                l, b, r, t = self.fig_bounds
                inches = self.fig_inches
                fig.subplots_adjust(left=l, bottom=b, right=r, top=t)
                fig.patch.set_alpha(self.fig_alpha)
                if isinstance(inches, (tuple, list)):
                    inches = list(inches)
                    if inches[0] is None:
                        inches[0] = inches[1]
                    elif inches[1] is None:
                        inches[1] = inches[0]
                    fig.set_size_inches(list(inches))
                else:
                    fig.set_size_inches([inches, inches])
                axis = fig.add_subplot(111, projection=self.projection)
                axis.set_aspect('auto')

        return fig, axis
开发者ID:dhomeier,项目名称:holoviews,代码行数:28,代码来源:plot.py


示例8: plot_dA_dphi_vs_t

def plot_dA_dphi_vs_t(df, extras, figax=None, rcParams={}, filename=None):
    if figax is None:
        with mpl.rc_context(rcParams):
            fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
    else:
        fig, (ax1, ax2) = figax

    df_sorted = df.sort_values('phi_at_tp [rad]')

    control = df_sorted.loc['control']
    f0 = control['f0 [Hz]'].median()

    td = control['phi_at_tp [rad]']/(2*np.pi*f0) * 1e6
    ax1.plot(td, control['dA [nm]'], 'b.')
    ax1.plot(td, offset_cos(control['phi_at_tp [rad]'], *extras['popt_A']))

    ax2.plot(td, control['dphi_tp_end [cyc]']*1e3, 'b.')
    ax2.plot(td, offset_cos(control['phi_at_tp [rad]'], *extras['popt_phi'])*1e3)

    ax1.grid()
    ax2.grid()
    ax1.set_xlabel(r'$\tau_\mathrm{d} \; [\mu\mathrm{s}]$')
    ax1.set_ylabel(r'$\Delta A \; [\mathrm{nm}]$')
    ax2.set_ylabel(r'$\Delta \phi \; [\mathrm{mcyc.}]$')

    if filename is not None:
        fig.savefig(filename, bbox_inches='tight')
    return fig, (ax1, ax2)
开发者ID:ryanpdwyer,项目名称:pmefm,代码行数:28,代码来源:phasekick.py


示例9: test_embed_limit

def test_embed_limit(method_name, caplog):
    with mpl.rc_context({"animation.embed_limit": 1e-6}):  # ~1 byte.
        getattr(make_animation(frames=1), method_name)()
    assert len(caplog.records) == 1
    record, = caplog.records
    assert (record.name == "matplotlib.animation"
            and record.levelname == "WARNING")
开发者ID:pganssle,项目名称:matplotlib,代码行数:7,代码来源:test_animation.py


示例10: test_plot

 def test_plot(self, instance):
     with rc_context(rc={'text.usetex': False}):
         plot = instance.plot(figsize=(6.4, 3.8))
         assert isinstance(plot, SegmentPlot)
         assert isinstance(plot.gca(), SegmentAxes)
         with tempfile.NamedTemporaryFile(suffix='.png') as f:
             plot.save(f.name)
开发者ID:stefco,项目名称:gwpy,代码行数:7,代码来源:test_segments.py


示例11: __init__

    def __init__(self, port, baud, check = False):
        """
            Initialize the main display: a single figure
            :port: serial port index or name (eg.: COM4)
            :paud: baud rate (eg.: 115200)
        """
        self.frame = IM_Frame()
        self.new_frame = False
        self.lock = threading.Lock()
        self.check = check

        # disable figure toolbar, bind close event and open serial port
        with mpl.rc_context({'toolbar':False}):
            self.fig = plt.figure()
            self.serial_port = serial.Serial(port, baud, timeout=0.25,bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=False)
            self.serial_port.flush()
            self.fig.canvas.mpl_connect('close_event', self.close_display)
            self.fig.canvas.mpl_connect('resize_event', self.resize_display)
            self.fig.canvas.set_window_title('pyIM')

            # window position is set before state to maximized in update_graph
            w,h=getVirtualScreenSize()
            plt.get_current_fig_manager().window.wm_geometry(("+%d+%d"%(w-1,0)))

            # create timer for updating display using a rs232 polling callback
            timer = self.fig.canvas.new_timer(interval=250)
            timer.add_callback(self.update_graphs) # then arg if needed
            timer.start()

            # launch figure
            plt.show(block = True)

            # close correctly serial port
            self.close_display()
开发者ID:mathieu-girard,项目名称:pyIM,代码行数:34,代码来源:pyIM.py


示例12: plot_weight_comparisons

def plot_weight_comparisons(gd_file, mal_file,
                            malicious_behaviour="Selfish", s="bella_static",
                            excluded=None, show_title=True, figsize=None,
                            labels=None, prefix="img/", extension="pdf"):
    if labels is None:
        labels = ["Fair", "Selfish"]

    if excluded is None:
        excluded = []

    mtfm_args = ('n0', 'n1', ['n2', 'n3'], ['n4', 'n5'])
    with mpl.rc_context(rc={'text.usetex': 'True'}):

        gd_trust, mal_trust = per_scenario_gd_mal_trusts(gd_file, mal_file)
        gd_tp, mal_tp = per_scenario_gd_mal_trust_perspective(gd_trust, mal_trust, s=s)

        gd_mtfm = Trust.generate_mtfm(gd_tp, *mtfm_args).sum(axis=1)
        mal_mtfm = Trust.generate_mtfm(mal_tp, *mtfm_args).sum(axis=1)

        plot_comparison(gd_mtfm, mal_mtfm, s=s,
                        show_title=show_title, keyword=malicious_behaviour,
                        figsize=figsize, labels=labels, prefix=prefix, extension=extension, show_grid=False)
        for i, mi in enumerate(trust_metrics):
            if mi not in excluded:
                gd_tp, mal_tp = per_scenario_gd_mal_trust_perspective(gd_trust, mal_trust, s=s,
                                                                      weight_vector=weight_for_metric(mi, 3))

                gd_mtfm = Trust.generate_mtfm(gd_tp, *mtfm_args).sum(axis=1)
                mal_mtfm = Trust.generate_mtfm(mal_tp, *mtfm_args).sum(axis=1)
                plot_comparison(gd_mtfm, mal_mtfm, s, metric=mi, show_title=show_title, prefix=prefix,
                                keyword=malicious_behaviour, figsize=figsize, labels=labels,
                                extension=extension, show_grid=False)
开发者ID:andrewbolster,项目名称:aietes,代码行数:32,代码来源:weight_comparisons.py


示例13: plot_phase

    def plot_phase(self, rcParams={}):
        if not hasattr(self, 'phi_lock_phase'):
            raise ValueError("set_filters before plotting phase")

        rcParams_ = self.rcParams

        rcParams_.update(rcParams)

        with mpl.rc_context(rcParams_):
            fig, ax = plt.subplots()
            phase = np.angle(self.phi_lock)
            ax.plot(self.tm, phase[self.m])
            if hasattr(self, 'phase'):
                adjusted_phase = phase_err(self.phase - phase)
                ax.plot(self.tm, (phase + adjusted_phase)[self.m])
            if hasattr(self, 'm_fit'):
                ax.axvspan(np.min(self.t[self.m_fit]),
                           np.max(self.t[self.m_fit]),
                           alpha=0.5,
                           color='0.5')

            ax.set_xlabel('Time [s]')
            ax.set_ylabel('Phase [rad.]')

        return fig, ax
开发者ID:ryanpdwyer,项目名称:pmefm,代码行数:25,代码来源:pmefm.py


示例14: context

def context(style, after_reset=False):
    """Context manager for using style settings temporarily.

    Parameters
    ----------
    style : str, dict, or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `style.available`.       |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str or dict) applied from first |
        |      | to last in the list.                                        |
        +------+-------------------------------------------------------------+

    after_reset : bool
        If True, apply style after resetting settings to their defaults;
        otherwise, apply style on top of the current settings.
    """
    with mpl.rc_context():
        if after_reset:
            mpl.rcdefaults()
        use(style)
        yield
开发者ID:dopplershift,项目名称:matplotlib,代码行数:28,代码来源:core.py


示例15: __init__

    def __init__(self, layout, axis=None, create_axes=True, ranges=None,
                 layout_num=1, keys=None, **params):
        if not isinstance(layout, GridSpace):
            raise Exception("GridPlot only accepts GridSpace.")
        super(GridPlot, self).__init__(layout, layout_num=layout_num,
                                       ranges=ranges, keys=keys, **params)
        # Compute ranges layoutwise
        grid_kwargs = {}
        if axis is not None:
            bbox = axis.get_position()
            l, b, w, h = bbox.x0, bbox.y0, bbox.width, bbox.height
            grid_kwargs = {'left': l, 'right': l+w, 'bottom': b, 'top': b+h}
            self.position = (l, b, w, h)

        self.cols, self.rows = layout.shape
        self.fig_inches = self._get_size()
        self._layoutspec = gridspec.GridSpec(self.rows, self.cols, **grid_kwargs)

        with mpl.rc_context(rc=self.fig_rcparams):
            self.subplots, self.subaxes, self.layout = self._create_subplots(layout, axis,
                                                                             ranges, create_axes)
        if self.top_level:
            self.comm = self.init_comm()
            self.traverse(lambda x: setattr(x, 'comm', self.comm))
            self.traverse(lambda x: attach_streams(self, x.hmap, 2),
                          [GenericElementPlot])
开发者ID:basnijholt,项目名称:holoviews,代码行数:26,代码来源:plot.py


示例16: __init__

    def __init__(self, data, layout=(1, 1)):
        self._data = data
        self._layout = layout

        self._number_of_plots = len(data)
        self._plots_per_page = _numpy.product(layout)
        self._number_of_pages = (self._number_of_plots-1) / self._plots_per_page + 1
        self._current_page = 0

        with _matplotlib.rc_context({"toolbar": "None"}):
            self._fig = _matplotlib.pyplot.figure("Browser")
            self._fig.clear()
            #_matplotlib.pyplot.show()
        self._fig.set_facecolor("white")
        self._fig.subplots_adjust(left=0., bottom=0.1, right=1., top=0.95, wspace=0., hspace=0.05)

        self._axes = [self._fig.add_subplot(layout[0], layout[1], 1+i0*layout[1]+i1) for i0, i1 in _itertools.product(xrange(layout[0]), xrange(layout[1]))]

        ax_prev = self._fig.add_axes([0.1, 0.01, 0.3, 0.09])
        ax_next = self._fig.add_axes([0.6, 0.01, 0.3, 0.09])

        self._button_prev = _matplotlib.widgets.Button(ax_prev, "Previous")
        self._button_next = _matplotlib.widgets.Button(ax_next, "Next")
        self._button_prev.on_clicked(self._prev)
        self._button_next.on_clicked(self._next)

        self._page_text = self._fig.text(0.5, 0.05, "", va="center", ha="center")
        self._update_page_string()
        self._first_plot()
开发者ID:ekeberg,项目名称:Python-tools,代码行数:29,代码来源:matplotlib_tools.py


示例17: test_view_limits

 def test_view_limits(self):
     """
     Test basic behavior of view limits.
     """
     with matplotlib.rc_context({'axes.autolimit_mode': 'data'}):
         loc = mticker.MultipleLocator(base=3.147)
         assert_almost_equal(loc.view_limits(-5, 5), (-5, 5))
开发者ID:dstansby,项目名称:matplotlib,代码行数:7,代码来源:test_ticker.py


示例18: style

 def style(self):
     if self.rc_context is None:
         return EmptyContext()
     elif type(self.rc_context) is dict:
         return mpl.rc_context(self.rc_context)
     else:
         return self.rc_context
开发者ID:jahuth,项目名称:litus,代码行数:7,代码来源:figure.py


示例19: plot_phasekick_corrected

def plot_phasekick_corrected(df, extras, figax=None, rcParams={}, filename=None):
    if figax is None:
        with mpl.rc_context(rcParams):
            fig, ax = plt.subplots()
    else:
        fig, ax = figax

    data = df.loc['data']
    control = df.loc['control']

    if abs(data['dphi_corrected [cyc]']).max() > 0.15:
        units = 'cyc'
        scale = 1
    else:
        units = 'mcyc'
        scale = 1e3


    ax.plot(control.tp*1e3, control['dphi_corrected [cyc]']*scale, 'g.')
    ax.plot(data.tp*1e3, data['dphi_corrected [cyc]']*scale, 'b.')
    ax.plot(data.tp*1e3, phase_step(data.tp, *extras['popt_phase_corr'])*scale)

    ax.set_xlabel('Pulse time [ms]')
    ax.set_ylabel('Phase shift [{}.]'.format(units))
    if filename is not None:
        fig.savefig(filename, bbox_inches='tight')
    return fig, ax
开发者ID:ryanpdwyer,项目名称:pmefm,代码行数:27,代码来源:phasekick.py


示例20: plot_roc

    def plot_roc(self):
        """
        Plot receiver operating charactistic curve for this subject's classifier.
        """

        fpr, tpr, _ = roc_curve(self.res['y'], self.res['probs'])
        with plt.style.context('fivethirtyeight'):
            with mpl.rc_context({'ytick.labelsize': 16,
                                 'xtick.labelsize': 16}):
                plt.plot(fpr, tpr, lw=4, label='ROC curve (AUC = %0.2f)' % self.res['auc'])
                plt.plot([0, 1], [0, 1], color='k', lw=2, linestyle='--', label='_nolegend_')
                plt.xlim([0.0, 1.0])
                plt.ylim([0.0, 1.05])
                plt.xlabel('False Positive Rate', fontsize=24)
                plt.ylabel('True Positive Rate', fontsize=24)
                plt.legend(loc="lower right")
                if 'p_val' not in self.res:
                    title = 'ROC (AUC: {0:.3f})'.format(self.res['auc'])
                else:
                    p = self.res['p_val']
                    if p == 0:
                        p_str = '< {0:.2f}'.format(1 / self.num_iters)
                    else:
                        p_str = '= {0:.3f}'.format(p)
                    title = 'ROC (AUC: {0:.3f}, p{1})'.format(self.res['auc'], p_str)
                plt.title(title)
        plt.gcf().set_size_inches(12, 9)
开发者ID:jayfmil,项目名称:TH_python,代码行数:27,代码来源:subject_classifier.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python matplotlib.rc_file函数代码示例发布时间:2022-05-27
下一篇:
Python matplotlib.rc函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap