本文整理汇总了Python中matplotlib.style.context函数的典型用法代码示例。如果您正苦于以下问题:Python context函数的具体用法?Python context怎么用?Python context使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了context函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_context_with_badparam
def test_context_with_badparam():
original_value = 'gray'
other_value = 'blue'
d = OrderedDict([(PARAM, original_value), ('badparam', None)])
with style.context({PARAM: other_value}):
assert mpl.rcParams[PARAM] == other_value
x = style.context([d])
assert_raises(KeyError, x.__enter__)
assert mpl.rcParams[PARAM] == other_value
示例2: test_context_with_badparam
def test_context_with_badparam():
if sys.version_info[:2] >= (2, 7):
from collections import OrderedDict
else:
m = "Test can only be run in Python >= 2.7 as it requires OrderedDict"
raise SkipTest(m)
original_value = 'gray'
other_value = 'blue'
d = OrderedDict([(PARAM, original_value), ('badparam', None)])
with style.context({PARAM: other_value}):
assert mpl.rcParams[PARAM] == other_value
x = style.context([d])
assert_raises(KeyError, x.__enter__)
assert mpl.rcParams[PARAM] == other_value
示例3: test_stationlayout_api
def test_stationlayout_api():
'Test the StationPlot api'
setup_font()
with style.context(test_style):
fig = make_figure(figsize=(9, 9))
# testing data
x = np.array([1, 5])
y = np.array([2, 4])
data = dict()
data['temp'] = np.array([32., 212.]) * units.degF
data['u'] = np.array([2, 0]) * units.knots
data['v'] = np.array([0, 5]) * units.knots
data['stid'] = ['KDEN', 'KSHV']
data['cover'] = [3, 8]
# Set up the layout
layout = StationPlotLayout()
layout.add_barb('u', 'v', units='knots')
layout.add_value('NW', 'temp', fmt='0.1f', units=units.degC, color='darkred')
layout.add_symbol('C', 'cover', sky_cover, color='magenta')
layout.add_text((0, 2), 'stid', color='darkgrey')
layout.add_value('NE', 'dewpt', color='green') # This should be ignored
# Make the plot
sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12)
layout.plot(sp, data)
sp.ax.set_xlim(0, 6)
sp.ax.set_ylim(0, 6)
hide_tick_labels(sp.ax)
return fig
示例4: test_nws_layout
def test_nws_layout():
'Test metpy\'s NWS layout for station plots'
setup_font()
with style.context(test_style):
fig = make_figure(figsize=(3, 3))
# testing data
x = np.array([1])
y = np.array([2])
data = dict()
data['air_temperature'] = np.array([77]) * units.degF
data['dew_point_temperature'] = np.array([71]) * units.degF
data['air_pressure_at_sea_level'] = np.array([999.8]) * units('mbar')
data['eastward_wind'] = np.array([15.]) * units.knots
data['northward_wind'] = np.array([15.]) * units.knots
data['cloud_coverage'] = [7]
data['present_weather'] = [80]
data['high_cloud_type'] = [1]
data['medium_cloud_type'] = [3]
data['low_cloud_type'] = [2]
data['visibility_in_air'] = np.array([5.]) * units.mile
data['tendency_of_air_pressure'] = np.array([-0.3]) * units('mbar')
data['tendency_of_air_pressure_symbol'] = [8]
# Make the plot
sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12, spacing=16)
nws_layout.plot(sp, data)
sp.ax.set_xlim(0, 3)
sp.ax.set_ylim(0, 3)
hide_tick_labels(sp.ax)
return fig
示例5: test_skewt_gridspec
def test_skewt_gridspec():
'Test using SkewT on a sub-plot'
with style.context(test_style):
fig = make_figure(figsize=(9, 9))
gs = GridSpec(1, 2)
hide_tick_labels(SkewT(fig, subplot=gs[0, 1]).ax)
return fig
示例6: run
def run(self):
scan_loader = self._make_scan_loader()
gpsms = self._load_spectrum_matches()
if not os.path.exists(self.output_path):
os.makedirs(self.output_path)
n = len(gpsms)
self.log("%d Spectrum Matches" % (n,))
for i, gpsm in enumerate(gpsms):
scan = scan_loader.get_scan_by_id(gpsm.scan.scan_id)
gpep = gpsm.structure.convert()
if i % 10 == 0:
self.log("... %0.2f%%: %s @ %s" % (((i + 1) / float(n) * 100.0), gpep, scan.id))
with style.context(self._mpl_style):
fig = figure()
grid = plt.GridSpec(nrows=5, ncols=1)
ax1 = fig.add_subplot(grid[1, 0])
ax2 = fig.add_subplot(grid[2:, 0])
ax3 = fig.add_subplot(grid[0, 0])
match = CoverageWeightedBinomialModelTree.evaluate(scan, gpep)
ax3.text(0, 0.5, (
str(match.target) + '\n' + scan.id +
'\nscore=%0.3f q value=%0.3g' % (gpsm.score, gpsm.q_value)), va='center')
ax3.axis('off')
match.plot(ax=ax2)
glycopeptide_match_logo(match, ax=ax1)
fname = format_filename("%s_%s.pdf" % (scan.id, gpep))
path = os.path.join(self.output_path, fname)
abspath = os.path.abspath(path)
if len(abspath) > 259 and platform.system().lower() == 'windows':
abspath = '\\\\?\\' + abspath
fig.savefig(abspath, bbox_inches='tight')
plt.close(fig)
示例7: test_context
def test_context():
mpl.rcParams[PARAM] = 'gray'
with temp_style('test', DUMMY_SETTINGS):
with style.context('test'):
assert mpl.rcParams[PARAM] == VALUE
# Check that this value is reset after the exiting the context.
assert mpl.rcParams[PARAM] == 'gray'
示例8: test_simple_layout
def test_simple_layout():
'Test metpy\'s simple layout for station plots'
setup_font()
with style.context(test_style):
fig = make_figure(figsize=(9, 9))
# testing data
x = np.array([1, 5])
y = np.array([2, 4])
data = dict()
data['air_temperature'] = np.array([32., 212.]) * units.degF
data['dew_point_temperature'] = np.array([28., 80.]) * units.degF
data['air_pressure_at_sea_level'] = np.array([29.92, 28.00]) * units.inHg
data['eastward_wind'] = np.array([2, 0]) * units.knots
data['northward_wind'] = np.array([0, 5]) * units.knots
data['cloud_coverage'] = [3, 8]
data['present_weather'] = [65, 75]
data['unused'] = [1, 2]
# Make the plot
sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12)
simple_layout.plot(sp, data)
sp.ax.set_xlim(0, 6)
sp.ax.set_ylim(0, 6)
hide_tick_labels(sp.ax)
return fig
示例9: test_context_with_dict
def test_context_with_dict():
original_value = 'gray'
other_value = 'blue'
mpl.rcParams[PARAM] = original_value
with style.context({PARAM: other_value}):
assert mpl.rcParams[PARAM] == other_value
assert mpl.rcParams[PARAM] == original_value
示例10: test_alias
def test_alias(equiv_styles):
rc_dicts = []
for sty in equiv_styles:
with style.context(sty):
rc_dicts.append(dict(mpl.rcParams))
rc_base = rc_dicts[0]
for nm, rc in zip(equiv_styles[1:], rc_dicts[1:]):
assert rc_base == rc
示例11: test_use_url
def test_use_url(tmpdir):
path = Path(tmpdir, 'file')
path.write_text('axes.facecolor: adeade')
with temp_style('test', DUMMY_SETTINGS):
url = ('file:'
+ ('///' if sys.platform == 'win32' else '')
+ path.resolve().as_posix())
with style.context(url):
assert mpl.rcParams['axes.facecolor'] == "#adeade"
示例12: test_context_with_dict_after_namedstyle
def test_context_with_dict_after_namedstyle():
# Test dict after style name where dict modifies the same parameter.
original_value = 'gray'
other_value = 'blue'
mpl.rcParams[PARAM] = original_value
with temp_style('test', DUMMY_SETTINGS):
with style.context(['test', {PARAM: other_value}]):
assert mpl.rcParams[PARAM] == other_value
assert mpl.rcParams[PARAM] == original_value
示例13: __init__
def __init__(self, image_path, image_name, reltol=1,
adjust_tolerance=True, plt_close_all_enter=True,
plt_close_all_exit=True, style=None, no_uploads=False, *args,
**kwargs):
self.suffix = "." + image_name.split(".")[-1]
super(ImageComparison, self).__init__(suffix=self.suffix, *args,
**kwargs)
self.image_name = image_name
self.baseline_image = os.path.join(image_path, image_name)
self.keep_output = "OBSPY_KEEP_IMAGES" in os.environ
self.keep_only_failed = "OBSPY_KEEP_ONLY_FAILED_IMAGES" in os.environ
self.output_path = os.path.join(image_path, "testrun")
self.diff_filename = "-failed-diff.".join(self.name.rsplit(".", 1))
self.tol = reltol * 3.0
self.plt_close_all_enter = plt_close_all_enter
self.plt_close_all_exit = plt_close_all_exit
self.no_uploads = no_uploads
if (MATPLOTLIB_VERSION < [1, 4, 0] or
(MATPLOTLIB_VERSION[:2] == [1, 4] and style is None)):
# No good style support.
self.style = None
else:
import matplotlib.style as mstyle
self.style = mstyle.context(style or 'classic')
# Adjust the tolerance based on the matplotlib version. This works
# well enough and otherwise testing is just a pain.
#
# The test images were generated with matplotlib tag 291091c6eb267
# which is after https://github.com/matplotlib/matplotlib/issues/7905
# has been fixed.
#
# Thus test images should accurate for matplotlib >= 2.0.1 anf
# fairly accurate for matplotlib 1.5.x.
if adjust_tolerance:
# Really old versions.
if MATPLOTLIB_VERSION < [1, 3, 0]:
self.tol *= 30
# 1.3 + 1.4 have slightly different text positioning mostly.
elif [1, 3, 0] <= MATPLOTLIB_VERSION < [1, 5, 0]:
self.tol *= 15
# A few plots with mpl 1.5 have ticks and axis slightl shifted.
# This is especially true for ticks with exponential numbers.
# Thus the tolerance also has to be a bit higher here.
elif [1, 5, 0] <= MATPLOTLIB_VERSION < [2, 0, 0]:
self.tol *= 5.0
# Matplotlib 2.0.0 has a bug with the tick placement. This is
# fixed in 2.0.1 but the tolerance for 2.0.0 has to be much
# higher. 10 is an empiric value. The tick placement potentially
# influences the axis locations and then the misfit is really
# quite high.
elif [2, 0, 0] <= MATPLOTLIB_VERSION < [2, 0, 1]:
self.tol *= 10
示例14: test_hodograph_units
def test_hodograph_units():
'Test passing unit-ed quantities to Hodograph'
with style.context(test_style):
fig = make_figure(figsize=(9, 9))
ax = fig.add_subplot(1, 1, 1)
hodo = Hodograph(ax)
u = np.arange(10) * units.kt
v = np.arange(10) * units.kt
hodo.plot(u, v)
hodo.plot_colormapped(u, v, np.sqrt(u * u + v * v), cmap='Greys')
hide_tick_labels(ax)
return fig
示例15: test_hodograph_api
def test_hodograph_api():
'Basic test of Hodograph API'
with style.context(test_style):
fig = make_figure(figsize=(9, 9))
ax = fig.add_subplot(1, 1, 1)
hodo = Hodograph(ax, component_range=60)
hodo.add_grid(increment=5, color='k')
hodo.plot([1, 10], [1, 10], color='red')
hodo.plot_colormapped(np.array([1, 3, 5, 10]), np.array([2, 4, 6, 11]),
np.array([0.1, 0.3, 0.5, 0.9]), cmap='Greys')
hide_tick_labels(ax)
return fig