Python matplotlib.rc_context() Examples
The following are 30
code examples of matplotlib.rc_context().
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 also want to check out all available functions/classes of the module
matplotlib
, or try the search function
.
Example #1
Source File: axes.py From nata with MIT License | 7 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
Source File: test_ticker.py From coffeegrindsize with 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 #3
Source File: figure.py From nata with 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 #4
Source File: test_rcparams.py From neural-network-animation with 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 #5
Source File: test_rcparams.py From neural-network-animation with 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 #6
Source File: test_rcparams.py From python3_ios with 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 #7
Source File: test_axes.py From python3_ios with 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 #8
Source File: test_axes.py From python3_ios with 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 #9
Source File: test_axes.py From python3_ios with 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 #10
Source File: test_colorbar.py From python3_ios with 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
Source File: test_rcparams.py From ImageFusion with 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 #12
Source File: test_ticker.py From python3_ios with 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 #13
Source File: test_axes.py From coffeegrindsize with 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 #14
Source File: test_axes.py From coffeegrindsize with 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 #15
Source File: test_axes.py From coffeegrindsize with 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 #16
Source File: test_rcparams.py From coffeegrindsize with 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 #17
Source File: plot.py From holoviews with 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 #18
Source File: test_rcparams.py From ImageFusion with 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 #19
Source File: test_colorbar.py From python3_ios with 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 #20
Source File: test_rcparams.py From ImageFusion with MIT License | 5 votes |
def test_Bug_2543_newer_python(): # only split from above because of the usage of assert_raises # as a context manager, which only works in 2.7 and above if sys.version_info[:2] < (2, 7): raise nose.SkipTest("assert_raises as context manager not supported with Python < 2.7") from matplotlib.rcsetup import validate_bool_maybe_none, validate_bool with assert_raises(ValueError): validate_bool_maybe_none("blah") with assert_raises(ValueError): validate_bool(None) with assert_raises(ValueError): with mpl.rc_context(): mpl.rcParams['svg.fonttype'] = True
Example #21
Source File: core.py From coffeegrindsize with 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 #22
Source File: test_frame.py From elasticintel with GNU General Public License v3.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)] 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
Source File: plot.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, layout, keys=None, **params): super(LayoutPlot, self).__init__(layout=layout, keys=keys, **params) with mpl.rc_context(rc=self.fig_rcparams): self.subplots, self.subaxes, self.layout = self._compute_gridspec(layout) if self.top_level: self.traverse(lambda x: attach_streams(self, x.hmap, 2), [GenericElementPlot])
Example #24
Source File: axes.py From nata with 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 #25
Source File: test_ticker.py From ImageFusion with MIT License | 5 votes |
def test_use_offset(): for use_offset in [True, False]: with matplotlib.rc_context({'axes.formatter.useoffset': use_offset}): tmp_form = mticker.ScalarFormatter() nose.tools.assert_equal(use_offset, tmp_form.get_useOffset())
Example #26
Source File: axes.py From nata with 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
Source File: io_utils.py From gnn-model-explainer with Apache License 2.0 | 5 votes |
def plot_cmap(cmap, ncolor): """ A convenient function to plot colors of a matplotlib cmap Credit goes to http://gvallver.perso.univ-pau.fr/?p=712 Args: ncolor (int): number of color to show cmap: a cmap object or a matplotlib color name """ if isinstance(cmap, str): name = cmap try: cm = plt.get_cmap(cmap) except ValueError: print("WARNINGS :", cmap, " is not a known colormap") cm = plt.cm.gray else: cm = cmap name = cm.name with matplotlib.rc_context(matplotlib.rcParamsDefault): fig = plt.figure(figsize=(12, 1), frameon=False) ax = fig.add_subplot(111) ax.pcolor(np.linspace(1, ncolor, ncolor).reshape(1, ncolor), cmap=cm) ax.set_title(name) xt = ax.set_xticks([]) yt = ax.set_yticks([]) return fig
Example #28
Source File: ggplot.py From plotnine with GNU General Public License v2.0 | 5 votes |
def _draw(self, return_ggplot=False): # Prevent against any modifications to the users # ggplot object. Do the copy here as we may/may not # assign a default theme self = deepcopy(self) self._build() # If no theme we use the default self.theme = self.theme or theme_get() try: with mpl.rc_context(): # setup & rcparams theming self.theme.apply_rcparams() figure, axs = self._create_figure() self._setup_parameters() self._resize_panels() # Drawing self._draw_layers() self._draw_labels() self._draw_breaks_and_labels() self._draw_legend() self._draw_title() self._draw_watermarks() # Artist object theming self._apply_theme() # !! except Exception as err: if self.figure is not None: plt.close(self.figure) raise err if return_ggplot: output = self.figure, self else: output = self.figure return output
Example #29
Source File: ggplot.py From plotnine with GNU General Public License v2.0 | 5 votes |
def _draw_using_figure(self, figure, axs): """ Draw onto already created figure and axes This is can be used to draw animation frames, or inset plots. It is intended to be used after the key plot has been drawn. Parameters ---------- figure : ~matplotlib.figure.Figure Matplotlib figure axs : array_like Array of Axes onto which to draw the plots """ self = deepcopy(self) self._build() self.theme = self.theme or theme_get() self.figure = figure self.axs = axs try: with mpl.rc_context(): self.theme.apply_rcparams() self._setup_parameters() self._draw_layers() self._draw_breaks_and_labels() self._draw_legend() self._apply_theme() except Exception as err: if self.figure is not None: plt.close(self.figure) raise err return self
Example #30
Source File: test_frame.py From predictive-maintenance-using-machine-learning with 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]