本文整理汇总了Python中matplotlib.ticker.MaxNLocator方法的典型用法代码示例。如果您正苦于以下问题:Python ticker.MaxNLocator方法的具体用法?Python ticker.MaxNLocator怎么用?Python ticker.MaxNLocator使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.ticker
的用法示例。
在下文中一共展示了ticker.MaxNLocator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_per_epoch
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def plot_per_epoch(ckpt_dir, title, measurements, y_label):
"""Plots stats (train/valid loss, avg PSNR, etc.)."""
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(1, len(measurements) + 1), measurements)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_xlabel('Epoch')
ax.set_ylabel(y_label)
ax.set_title(title)
plt.tight_layout()
fname = '{}.png'.format(title.replace(' ', '-').lower())
plot_fname = os.path.join(ckpt_dir, fname)
plt.savefig(plot_fname, dpi=200)
plt.close()
示例2: _autolev
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def _autolev(self, z, N):
"""
Select contour levels to span the data.
We need two more levels for filled contours than for
line contours, because for the latter we need to specify
the lower and upper boundary of each range. For example,
a single contour boundary, say at z = 0, requires only
one contour line, but two filled regions, and therefore
three levels to provide boundaries for both regions.
"""
if self.locator is None:
if self.logscale:
self.locator = ticker.LogLocator()
else:
self.locator = ticker.MaxNLocator(N + 1)
zmax = self.zmax
zmin = self.zmin
lev = self.locator.tick_values(zmin, zmax)
self._auto = True
if self.filled:
return lev
# For line contours, drop levels outside the data range.
return lev[(lev > zmin) & (lev < zmax)]
示例3: _select_locator
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def _select_locator(self, formatter):
'''
select a suitable locator
'''
if self.boundaries is None:
if isinstance(self.norm, colors.NoNorm):
nv = len(self._values)
base = 1 + int(nv/10)
locator = ticker.IndexLocator(base=base, offset=0)
elif isinstance(self.norm, colors.BoundaryNorm):
b = self.norm.boundaries
locator = ticker.FixedLocator(b, nbins=10)
elif isinstance(self.norm, colors.LogNorm):
locator = ticker.LogLocator()
else:
locator = ticker.MaxNLocator(nbins=5)
else:
b = self._boundaries[self._inside]
locator = ticker.FixedLocator(b) #, nbins=10)
self.cbar_axis.set_major_locator(locator)
示例4: test_constrained_layout6
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def test_constrained_layout6():
'Test constrained_layout for nested gridspecs'
fig = plt.figure(constrained_layout=True)
gs = fig.add_gridspec(1, 2, figure=fig)
gsl = gs[0].subgridspec(2, 2)
gsr = gs[1].subgridspec(1, 2)
axsl = []
for gs in gsl:
ax = fig.add_subplot(gs)
axsl += [ax]
example_plot(ax, fontsize=12)
ax.set_xlabel('x-label\nMultiLine')
axsr = []
for gs in gsr:
ax = fig.add_subplot(gs)
axsr += [ax]
pcm = example_pcolor(ax, fontsize=12)
fig.colorbar(pcm, ax=axsr,
pad=0.01, shrink=0.99, location='bottom',
ticks=ticker.MaxNLocator(nbins=5))
示例5: _plot_and_save_attention
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def _plot_and_save_attention(att_w, filename):
"""Plot and save an attention."""
# dynamically import matplotlib due to not found error
from matplotlib.ticker import MaxNLocator
import os
d = os.path.dirname(filename)
if not os.path.exists(d):
os.makedirs(d)
w, h = plt.figaspect(1.0 / len(att_w))
fig = plt.Figure(figsize=(w * 2, h * 2))
axes = fig.subplots(1, len(att_w))
if len(att_w) == 1:
axes = [axes]
for ax, aw in zip(axes, att_w):
# plt.subplot(1, len(att_w), h)
ax.imshow(aw, aspect="auto")
ax.set_xlabel("Input")
ax.set_ylabel("Output")
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
fig.tight_layout()
return fig
示例6: _plot_walk
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def _plot_walk(self, ax, parameter, data, truth=None, extents=None, convolve=None, color=None, log_scale=False): # pragma: no cover
if extents is not None:
ax.set_ylim(extents)
assert convolve is None or isinstance(convolve, int), "Convolve must be an integer pixel window width"
x = np.arange(data.size)
ax.set_xlim(0, x[-1])
ax.set_ylabel(parameter)
if color is None:
color = "#0345A1"
ax.scatter(x, data, c=color, s=2, marker=".", edgecolors="none", alpha=0.5)
max_ticks = self.parent.config["max_ticks"]
if log_scale:
ax.set_yscale("log")
ax.yaxis.set_major_locator(LogLocator(numticks=max_ticks))
else:
ax.yaxis.set_major_locator(MaxNLocator(max_ticks, prune="lower"))
if convolve is not None:
color2 = self.parent.color_finder.scale_colour(color, 0.5)
filt = np.ones(convolve) / convolve
filtered = np.convolve(data, filt, mode="same")
ax.plot(x[:-1], filtered[:-1], ls=":", color=color2, alpha=1)
示例7: make_map
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def make_map(axes):
import matplotlib.ticker as mticker
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
gl = axes.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=2, color='gray', alpha=0.5, linestyle='-')
axes.coastlines('10m')
gl.xlabels_top = False
gl.ylabels_right = False
gl.xlocator = mticker.MaxNLocator(nbins=5,min_n_ticks=3,steps=None)
gl.ylocator = mticker.MaxNLocator(nbins=5,min_n_ticks=3,steps=None)
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
#gl.xlabel_style = {'size': 15, 'color': 'gray'}
#gl.xlabel_style = {'color': 'red', 'weight': 'bold'}
return axes
示例8: plot_relative_lengths
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def plot_relative_lengths(data, fname):
# some panels will be empty for longer HPs so keep track of what lengths and bases are in each row/column
rows = sorted(data['ref_len'].unique())
cols = sorted(data['q_base'].unique())
fig, axes = plt.subplots(
ncols=len(cols), nrows=len(rows), sharex=True,
figsize=(4 * len(cols), 2 * len(rows)))
for rl, rl_df in data.groupby(['ref_len']):
i = rows.index(rl)
for qb, qb_df in rl_df.groupby('q_base'):
j = cols.index(qb)
ax = axes[i][j]
ax.bar(qb_df['rel_len'], qb_df['count'])
ax.set_title('{}{}'.format(qb, rl))
ax.xaxis.set_tick_params(which='both', labelbottom=True)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
for ax in axes[-1,:]:
ax.set_xlabel('Query length relative to reference')
for ax in axes[:, 0]:
ax.set_ylabel('Counts')
fig.tight_layout()
fig.savefig(fname)
示例9: place_plot
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def place_plot(self, axis) -> None:
self._axis = axis
for n, v in self._prev_values.items():
self._axis.scatter(v[1], v[0], label=n, c=self._colors[n])
self._axis.set_ylabel(self._handle)
self._axis.set_xlabel('epoch')
self._axis.xaxis.set_major_locator(MaxNLocator(integer=True))
self._axis.legend()
plt.grid()
示例10: _config_axes
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def _config_axes(self, ax, ax2):
# define the necessary colors
color_bg = self.get_color('bg', ColorHexCode.WHITE)
color_fg = self.get_color('fg', ColorHexCode.BLACK)
color_line_bg = self.get_color('line_bg', ColorHexCode.WHITE)
ax.tick_params(
axis='both',
which='both',
colors=color_fg,
top=False,
bottom=False
)
ax2.tick_params(
axis='both',
which='both',
colors=color_fg,
top=False,
bottom=False
)
ax.set_facecolor(color_line_bg)
ax2.set_facecolor(color_line_bg)
title = pyplot.title('Campaign Comparison', color=color_fg, size=self.markersize_scale * 1.75, loc='left')
title.set_position([0.075, 1.05])
ax.set_ylabel('Percent Visits/Credentials', color=color_fg, size=self.markersize_scale * 1.5)
ax.set_xlabel('Campaign Name', color=color_fg, size=self.markersize_scale * 1.5)
self._ax_hide_ticks(ax)
self._ax_hide_ticks(ax2)
ax2.set_ylabel('Messages', color=color_fg, size=self.markersize_scale * 1.25, rotation=270, labelpad=20)
self._ax_set_spine_color(ax, color_bg)
self._ax_set_spine_color(ax2, color_bg)
ax2.get_yaxis().set_major_locator(ticker.MaxNLocator(integer=True))
ax.tick_params(axis='x', labelsize=10, pad=5)
示例11: __init__
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def __init__(self,
transform,
extreme_finder=None,
grid_locator1=None,
grid_locator2=None,
tick_formatter1=None,
tick_formatter2=None):
"""
transform : transform from the image coordinate (which will be
the transData of the axes to the world coordinate.
or transform = (transform_xy, inv_transform_xy)
locator1, locator2 : grid locator for 1st and 2nd axis.
"""
if extreme_finder is None:
extreme_finder = ExtremeFinderSimple(20, 20)
if grid_locator1 is None:
grid_locator1 = MaxNLocator()
if grid_locator2 is None:
grid_locator2 = MaxNLocator()
if tick_formatter1 is None:
tick_formatter1 = FormatterPrettyPrint()
if tick_formatter2 is None:
tick_formatter2 = FormatterPrettyPrint()
super(GridFinder, self).__init__( \
extreme_finder,
grid_locator1,
grid_locator2,
tick_formatter1,
tick_formatter2)
self.update_transform(transform)
示例12: __call__
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def __call__(self, v1, v2):
if self._factor is not None:
self.set_bounds(v1*self._factor, v2*self._factor)
locs = mticker.MaxNLocator.__call__(self)
return np.array(locs), len(locs), self._factor
else:
self.set_bounds(v1, v2)
locs = mticker.MaxNLocator.__call__(self)
return np.array(locs), len(locs), None
示例13: colorbar
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def colorbar(self, mappable, **kwargs):
locator=kwargs.pop("locator", None)
if locator is None:
if "ticks" not in kwargs:
kwargs["ticks"] = ticker.MaxNLocator(5)
if locator is not None:
if "ticks" in kwargs:
raise ValueError("Either *locator* or *ticks* need to be given, not both")
else:
kwargs["ticks"] = locator
self.hold(True)
if self.orientation in ["top", "bottom"]:
orientation="horizontal"
else:
orientation="vertical"
cb = Colorbar(self, mappable, orientation=orientation, **kwargs)
self._config_axes()
def on_changed(m):
#print 'calling on changed', m.get_cmap().name
cb.set_cmap(m.get_cmap())
cb.set_clim(m.get_clim())
cb.update_bruteforce(m)
self.cbid = mappable.callbacksSM.connect('changed', on_changed)
mappable.colorbar = cb
self.locator = cb.cbar_axis.get_major_locator()
return cb
示例14: test_MaxNLocator
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def test_MaxNLocator():
loc = mticker.MaxNLocator(nbins=5)
test_value = np.array([20., 40., 60., 80., 100.])
assert_almost_equal(loc.tick_values(20, 100), test_value)
test_value = np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])
assert_almost_equal(loc.tick_values(0.001, 0.0001), test_value)
test_value = np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])
assert_almost_equal(loc.tick_values(-1e15, 1e15), test_value)
示例15: __init__
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MaxNLocator [as 别名]
def __init__(self, max_n_ticks, calendar, date_unit, min_n_ticks=3):
# The date unit must be in the form of days since ...
self.max_n_ticks = max_n_ticks
self.min_n_ticks = min_n_ticks
self._max_n_locator = mticker.MaxNLocator(max_n_ticks, integer=True)
self._max_n_locator_days = mticker.MaxNLocator(
max_n_ticks, integer=True, steps=[1, 2, 4, 7, 10])
self.calendar = calendar
self.date_unit = date_unit
if not self.date_unit.lower().startswith('days since'):
msg = 'The date unit must be days since for a NetCDF time locator.'
raise ValueError(msg)
self._cached_resolution = {}