本文整理匯總了Python中matplotlib.rc_context方法的典型用法代碼示例。如果您正苦於以下問題:Python matplotlib.rc_context方法的具體用法?Python matplotlib.rc_context怎麽用?Python matplotlib.rc_context使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib
的用法示例。
在下文中一共展示了matplotlib.rc_context方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: update_backend
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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)
示例2: save
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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")
示例3: test_rcparams
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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
示例4: test_rcparams_reset_after_fail
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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
示例5: test_rcparams_reset_after_fail
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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
示例6: test_rc_grid
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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
示例7: test_rc_tick
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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']
示例8: test_rc_major_minor_tick
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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']
示例9: test_minorticks_rc
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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)
示例10: test_colorbar_closed_patch
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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)
示例11: test_colorbar_autotickslog
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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.))
示例12: __init__
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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])
示例13: test_rcParams_bar_colors
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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]
示例14: __call__
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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()
示例15: test_rcParams_bar_colors
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import rc_context [as 別名]
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]