Python matplotlib.rc_context() Examples
The following are 30 code examples for showing how to use matplotlib.rc_context(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
matplotlib
, or try the search function
.
Example 1
Project: nata Author: GoLP-IST File: axes.py License: MIT License | 6 votes |
def update_backend(self): with mpl.rc_context(fname=self.fig.fname, rc=self.fig.rc): ax = self.ax ax.set_xscale(self.xscale) ax.set_yscale(self.yscale) if self.xlim[0] != self.xlim[1]: ax.set_xlim(self.xlim) if self.ylim[0] != self.ylim[1]: ax.set_ylim(self.ylim) # set axes labels ax.set_xlabel(self.xlabel) ax.set_ylabel(self.ylabel) # set title ax.set_title(label=self.title) # set aspect ratio ax.set_aspect(self.aspect)
Example 2
Project: nata Author: GoLP-IST File: figure.py License: MIT License | 6 votes |
def save( self, path, format: Optional[str] = None, dpi: Optional[float] = 150 ): """Saves the figure to a file. Parameters ---------- path: ``tuple`` of ``float``, optional Path in which to store the file. format: ``str``, optional File format, e.g. ``'png'``, ``'pdf'``, ``'svg'``. If not provided, the output format is inferred from the extension of ``path``. dpi: ``float``, optional Resolution in dots per inch. If not provided, defaults to ``150``. """ with mpl.rc_context(fname=self.fname, rc=self.rc): self.fig.savefig(path, dpi=dpi, bbox_inches="tight")
Example 3
Project: neural-network-animation Author: miloharper File: test_rcparams.py License: MIT License | 6 votes |
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
Example 4
Project: neural-network-animation Author: miloharper File: test_rcparams.py License: MIT License | 6 votes |
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. if sys.version_info[:2] >= (2, 7): from collections import OrderedDict else: raise SkipTest("Test can only be run in Python >= 2.7 as it requires OrderedDict") 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
Example 5
Project: python3_ios Author: holzschu File: test_rcparams.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 pytest.raises(KeyError): with mpl.rc_context(rc=OrderedDict([('text.usetex', True), ('test.blah', True)])): pass assert mpl.rcParams['text.usetex'] is False
Example 6
Project: python3_ios Author: holzschu File: test_axes.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_rc_grid(): fig = plt.figure() rc_dict0 = { 'axes.grid': True, 'axes.grid.axis': 'both' } rc_dict1 = { 'axes.grid': True, 'axes.grid.axis': 'x' } rc_dict2 = { 'axes.grid': True, 'axes.grid.axis': 'y' } dict_list = [rc_dict0, rc_dict1, rc_dict2] i = 1 for rc_dict in dict_list: with matplotlib.rc_context(rc_dict): fig.add_subplot(3, 1, i) i += 1
Example 7
Project: python3_ios Author: holzschu File: test_axes.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_rc_tick(): d = {'xtick.bottom': False, 'xtick.top': True, 'ytick.left': True, 'ytick.right': False} with plt.rc_context(rc=d): fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) xax = ax1.xaxis yax = ax1.yaxis # tick1On bottom/left assert not xax._major_tick_kw['tick1On'] assert xax._major_tick_kw['tick2On'] assert not xax._minor_tick_kw['tick1On'] assert xax._minor_tick_kw['tick2On'] assert yax._major_tick_kw['tick1On'] assert not yax._major_tick_kw['tick2On'] assert yax._minor_tick_kw['tick1On'] assert not yax._minor_tick_kw['tick2On']
Example 8
Project: python3_ios Author: holzschu File: test_axes.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_rc_major_minor_tick(): d = {'xtick.top': True, 'ytick.right': True, # Enable all ticks 'xtick.bottom': True, 'ytick.left': True, # Selectively disable 'xtick.minor.bottom': False, 'xtick.major.bottom': False, 'ytick.major.left': False, 'ytick.minor.left': False} with plt.rc_context(rc=d): fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) xax = ax1.xaxis yax = ax1.yaxis # tick1On bottom/left assert not xax._major_tick_kw['tick1On'] assert xax._major_tick_kw['tick2On'] assert not xax._minor_tick_kw['tick1On'] assert xax._minor_tick_kw['tick2On'] assert not yax._major_tick_kw['tick1On'] assert yax._major_tick_kw['tick2On'] assert not yax._minor_tick_kw['tick1On'] assert yax._minor_tick_kw['tick2On']
Example 9
Project: python3_ios Author: holzschu File: test_ticker.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_minorticks_rc(): fig = plt.figure() def minorticksubplot(xminor, yminor, i): rc = {'xtick.minor.visible': xminor, 'ytick.minor.visible': yminor} with plt.rc_context(rc=rc): ax = fig.add_subplot(2, 2, i) assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor minorticksubplot(False, False, 1) minorticksubplot(True, False, 2) minorticksubplot(False, True, 3) minorticksubplot(True, True, 4)
Example 10
Project: python3_ios Author: holzschu File: test_colorbar.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_colorbar_closed_patch(): fig = plt.figure(figsize=(8, 6)) ax1 = fig.add_axes([0.05, 0.85, 0.9, 0.1]) ax2 = fig.add_axes([0.1, 0.65, 0.75, 0.1]) ax3 = fig.add_axes([0.05, 0.45, 0.9, 0.1]) ax4 = fig.add_axes([0.05, 0.25, 0.9, 0.1]) ax5 = fig.add_axes([0.05, 0.05, 0.9, 0.1]) cmap = get_cmap("RdBu", lut=5) im = ax1.pcolormesh(np.linspace(0, 10, 16).reshape((4, 4)), cmap=cmap) values = np.linspace(0, 10, 5) with rc_context({'axes.linewidth': 16}): plt.colorbar(im, cax=ax2, cmap=cmap, orientation='horizontal', extend='both', extendfrac=0.5, values=values) plt.colorbar(im, cax=ax3, cmap=cmap, orientation='horizontal', extend='both', values=values) plt.colorbar(im, cax=ax4, cmap=cmap, orientation='horizontal', extend='both', extendrect=True, values=values) plt.colorbar(im, cax=ax5, cmap=cmap, orientation='horizontal', extend='neither', values=values)
Example 11
Project: python3_ios Author: holzschu File: test_colorbar.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_colorbar_autotickslog(): # Test new autotick modes... with rc_context({'_internal.classic_mode': False}): fig, ax = plt.subplots(2, 1) x = np.arange(-3.0, 4.001) y = np.arange(-4.0, 3.001) X, Y = np.meshgrid(x, y) Z = X * Y pcm = ax[0].pcolormesh(X, Y, 10**Z, norm=LogNorm()) cbar = fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical') pcm = ax[1].pcolormesh(X, Y, 10**Z, norm=LogNorm()) cbar2 = fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical', shrink=0.4) np.testing.assert_almost_equal(cbar.ax.yaxis.get_ticklocs(), 10**np.arange(-12, 12.2, 4.)) np.testing.assert_almost_equal(cbar2.ax.yaxis.get_ticklocs(), 10**np.arange(-12, 13., 12.))
Example 12
Project: ImageFusion Author: pfchai File: test_rcparams.py License: MIT License | 6 votes |
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
Example 13
Project: ImageFusion Author: pfchai File: test_rcparams.py License: MIT License | 6 votes |
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. if sys.version_info[:2] >= (2, 7): from collections import OrderedDict else: raise SkipTest("Test can only be run in Python >= 2.7 as it requires OrderedDict") 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
Example 14
Project: holoviews Author: holoviz File: plot.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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.traverse(lambda x: attach_streams(self, x.hmap, 2), [GenericElementPlot])
Example 15
Project: coffeegrindsize Author: jgagneastro File: test_rcparams.py License: MIT License | 6 votes |
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 pytest.raises(KeyError): with mpl.rc_context(rc=OrderedDict([('text.usetex', True), ('test.blah', True)])): pass assert mpl.rcParams['text.usetex'] is False
Example 16
Project: coffeegrindsize Author: jgagneastro File: test_axes.py License: MIT License | 6 votes |
def test_rc_grid(): fig = plt.figure() rc_dict0 = { 'axes.grid': True, 'axes.grid.axis': 'both' } rc_dict1 = { 'axes.grid': True, 'axes.grid.axis': 'x' } rc_dict2 = { 'axes.grid': True, 'axes.grid.axis': 'y' } dict_list = [rc_dict0, rc_dict1, rc_dict2] i = 1 for rc_dict in dict_list: with matplotlib.rc_context(rc_dict): fig.add_subplot(3, 1, i) i += 1
Example 17
Project: coffeegrindsize Author: jgagneastro File: test_axes.py License: MIT License | 6 votes |
def test_rc_tick(): d = {'xtick.bottom': False, 'xtick.top': True, 'ytick.left': True, 'ytick.right': False} with plt.rc_context(rc=d): fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) xax = ax1.xaxis yax = ax1.yaxis # tick1On bottom/left assert not xax._major_tick_kw['tick1On'] assert xax._major_tick_kw['tick2On'] assert not xax._minor_tick_kw['tick1On'] assert xax._minor_tick_kw['tick2On'] assert yax._major_tick_kw['tick1On'] assert not yax._major_tick_kw['tick2On'] assert yax._minor_tick_kw['tick1On'] assert not yax._minor_tick_kw['tick2On']
Example 18
Project: coffeegrindsize Author: jgagneastro File: test_axes.py License: MIT License | 6 votes |
def test_rc_major_minor_tick(): d = {'xtick.top': True, 'ytick.right': True, # Enable all ticks 'xtick.bottom': True, 'ytick.left': True, # Selectively disable 'xtick.minor.bottom': False, 'xtick.major.bottom': False, 'ytick.major.left': False, 'ytick.minor.left': False} with plt.rc_context(rc=d): fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) xax = ax1.xaxis yax = ax1.yaxis # tick1On bottom/left assert not xax._major_tick_kw['tick1On'] assert xax._major_tick_kw['tick2On'] assert not xax._minor_tick_kw['tick1On'] assert xax._minor_tick_kw['tick2On'] assert not yax._major_tick_kw['tick1On'] assert yax._major_tick_kw['tick2On'] assert not yax._minor_tick_kw['tick1On'] assert yax._minor_tick_kw['tick2On']
Example 19
Project: coffeegrindsize Author: jgagneastro File: test_ticker.py License: MIT License | 6 votes |
def test_minorticks_rc(): fig = plt.figure() def minorticksubplot(xminor, yminor, i): rc = {'xtick.minor.visible': xminor, 'ytick.minor.visible': yminor} with plt.rc_context(rc=rc): ax = fig.add_subplot(2, 2, i) assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor minorticksubplot(False, False, 1) minorticksubplot(True, False, 2) minorticksubplot(False, True, 3) minorticksubplot(True, True, 4)
Example 20
Project: recruit Author: Frank-qlu File: test_frame.py License: Apache License 2.0 | 5 votes |
def test_rcParams_bar_colors(self): import matplotlib as mpl color_tuples = [(0.9, 0, 0, 1), (0, 0.9, 0, 1), (0, 0, 0.9, 1)] with mpl.rc_context( rc={'axes.prop_cycle': mpl.cycler("color", color_tuples)}): barplot = pd.DataFrame([[1, 2, 3]]).plot(kind="bar") assert color_tuples == [c.get_facecolor() for c in barplot.patches]
Example 21
Project: ehtplot Author: liamedeiros File: figure.py License: GNU General Public License v3.0 | 5 votes |
def __call__(self, **kwargs): """Figure realizer The Figure class only keeps track of a root panel. It does not contain an actual matplotlib Figure instance. Whenever a figure needs to be created, Figure creates a new matplotlib Figure in order to drew/rendered/realized the figure. Args: **kwargs (dict): Arbitrary Figure-specific keyworded arguments that are used to construct the matplotlib Figure. """ kwprops = merge_dict(self.kwprops, kwargs) style = kwprops.pop('style') with mpl.rc_context(): mpl.rcdefaults() plt.style.use(style) imode = mpl.is_interactive() if imode: plt.ioff() fig = plt.figure(**kwprops) ax = newaxes(fig) yield fig, ax if imode: plt.ion()
Example 22
Project: vnpy_crypto Author: birforce File: test_frame.py License: MIT License | 5 votes |
def test_rcParams_bar_colors(self): import matplotlib as mpl color_tuples = [(0.9, 0, 0, 1), (0, 0.9, 0, 1), (0, 0, 0.9, 1)] try: # mpl 1.5 with mpl.rc_context( rc={'axes.prop_cycle': mpl.cycler("color", color_tuples)}): barplot = pd.DataFrame([[1, 2, 3]]).plot(kind="bar") except (AttributeError, KeyError): # mpl 1.4 with mpl.rc_context(rc={'axes.color_cycle': color_tuples}): barplot = pd.DataFrame([[1, 2, 3]]).plot(kind="bar") assert color_tuples == [c.get_facecolor() for c in barplot.patches]
Example 23
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 5 votes |
def rc_context(rc=None, fname=None): return matplotlib.rc_context(rc, fname)
Example 24
Project: Mastering-Elasticsearch-7.0 Author: PacktPublishing File: core.py License: MIT License | 5 votes |
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
Example 25
Project: nata Author: GoLP-IST File: axes.py License: MIT License | 5 votes |
def init_backend(self): with mpl.rc_context(fname=self.fig.fname, rc=self.fig.rc): self.ax = self.fig.fig.add_subplot( self.fig.nrows, self.fig.ncols, self.index )
Example 26
Project: nata Author: GoLP-IST File: axes.py License: MIT License | 5 votes |
def init_legend(self): if self.legend_show: handles, labels = self.ax.get_legend_handles_labels() with mpl.rc_context(fname=self.fig.fname, rc=self.fig.rc): # show legend self.legend = self.ax.legend( handles=handles, labels=labels, loc=self.legend_loc, frameon=self.legend_frameon, )
Example 27
Project: nata Author: GoLP-IST File: axes.py License: MIT License | 5 votes |
def init_colorbar(self, plot: PlotTypes): if self.cb_show: with mpl.rc_context(fname=self.fig.fname, rc=self.fig.rc): # show colorbar self.cb = self.ax.get_figure().colorbar(plot.h, aspect=30) # set colorbar title) self.cb.set_label(label=plot.cb_title)
Example 28
Project: nata Author: GoLP-IST File: figure.py License: MIT License | 5 votes |
def open(self): with mpl.rc_context(fname=self.fname, rc=self.rc): self.fig = plt.figure(figsize=self.figsize) if self.figsize is None: size = self.fig.get_size_inches() self.fig.set_size_inches( size[0] * self.ncols, size[1] * self.nrows )
Example 29
Project: matplotlib-4-abaqus Author: Solid-Mechanics File: pyplot.py License: MIT License | 5 votes |
def rc_context(rc=None, fname=None): return matplotlib.rc_context(rc, fname)
Example 30
Project: neural-network-animation Author: miloharper File: test_rcparams.py License: MIT License | 5 votes |
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")