本文整理匯總了Python中matplotlib.ticker方法的典型用法代碼示例。如果您正苦於以下問題:Python matplotlib.ticker方法的具體用法?Python matplotlib.ticker怎麽用?Python matplotlib.ticker使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib
的用法示例。
在下文中一共展示了matplotlib.ticker方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def __init__(self, base=1, month=1, day=1, tz=None):
"""
Mark years that are multiple of base on a given month and day
(default jan 1).
"""
DateLocator.__init__(self, tz)
self.base = ticker._Edge_integer(base, 0)
self.replaced = {'month': month,
'day': day,
'hour': 0,
'minute': 0,
'second': 0,
}
if not hasattr(tz, 'localize'):
# if tz is pytz, we need to do this w/ the localize fcn,
# otherwise datetime.replace works fine...
self.replaced['tzinfo'] = tz
示例2: mask_ques
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def mask_ques(sen, attn, idx2word):
"""
Put attention weights to each word in sentence.
--------------------
Arguments:
sen (LongTensor): encoded sentence.
attn (FloatTensor): attention weights of each word.
idx2word (dict): vocabulary.
"""
fig, ax = plt.subplots(figsize=(15,15))
ax.matshow(attn, cmap='bone')
y = [1]
x = [1] + [idx2word[i] for i in sen]
ax.set_yticklabels(y)
ax.set_xticklabels(x)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
示例3: addField1d
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def addField1d(ax, field, log10plot=True,
xlim=None, ylim=None, scaletight=None):
field = field.squeeze()
assert field.dimensions == 1, 'Field needs to be 1 dimensional'
ax.plot(field.grid, field.matrix, label=field.label)
ax.xaxis.set_major_formatter(MatplotlibPlotter.axesformatterx)
ax.yaxis.set_major_formatter(MatplotlibPlotter.axesformattery)
if log10plot and ((field.matrix < 0).sum() == 0) \
and any(field.matrix > 0):
ax.set_yscale('log') # sets the axis to log scale AND overrides
# our previously set axesformatter to the default
# matplotlib.ticker.LogFormatterMathtext.
MatplotlibPlotter.addaxislabels(ax, field)
ax.autoscale(tight=scaletight)
if xlim is not None:
ax.set_xlim(xlim)
if ylim is not None:
ax.set_ylim(ylim)
return ax
示例4: set_plot
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def set_plot(amp, function):
global figure_w, figure_h, fig
fig=plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(-np.pi*2, np.pi*2, 100)
if function == 'sine':
y= amp*np.sin(x)
ax.set_title('sin(x)')
else:
y=amp*np.cos(x)
ax.set_title('cos(x)')
plt.plot(x/np.pi,y)
#centre bottom and left axes to zero
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
#Format axes - nicer eh!
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
示例5: util_plot2d
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def util_plot2d(metric, title='', subtitle = '', line_size=2, title_size=17,date_formatter='%b-%d-%y %H-%M',plot_size=(6,6)):
if not isinstance(metric, list):
sys.exit("metric should have class 'list'")
if not isinstance(title, str):
sys.exit("title should have class 'str'")
if not isinstance(subtitle, str):
sys.exit("subtitle should have class 'str'")
times=util_timezone(metric[0])
def format_date(x, pos=None):
thisind = np.clip(int(x+0.5), 0, N-1)
return times[thisind].strftime(date_formatter)
N = len(metric[1])
ind = np.arange(N) # the evenly spaced plot indices
fig, ax = plt.subplots()
ax.plot(ind, metric[1], lw=line_size)
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()
plt.suptitle(title, y=0.99, fontsize=title_size)
plt.title(subtitle, fontsize=title_size-5)
plt.rcParams['figure.figsize'] = plot_size
plt.grid(True)
plt.show()
示例6: __init__
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def __init__(self, base=1, month=1, day=1, tz=None):
"""
Mark years that are multiple of base on a given month and day
(default jan 1).
"""
DateLocator.__init__(self, tz)
self.base = ticker.Base(base)
self.replaced = {'month': month,
'day': day,
'hour': 0,
'minute': 0,
'second': 0,
'tzinfo': tz
}
示例7: locator_params
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def locator_params(self, axis='both', tight=None, **kwargs):
"""
Control behavior of tick locators.
Parameters
----------
axis : {'both', 'x', 'y'}, optional
The axis on which to operate.
tight : bool or None, optional
Parameter passed to :meth:`autoscale_view`.
Default is None, for no change.
Other Parameters
----------------
**kw :
Remaining keyword arguments are passed to directly to the
:meth:`~matplotlib.ticker.MaxNLocator.set_params` method.
Typically one might want to reduce the maximum number
of ticks and use tight bounds when plotting small
subplots, for example::
ax.locator_params(tight=True, nbins=4)
Because the locator is involved in autoscaling,
:meth:`autoscale_view` is called automatically after
the parameters are changed.
This presently works only for the
:class:`~matplotlib.ticker.MaxNLocator` used
by default on linear axes, but it may be generalized.
"""
_x = axis in ['x', 'both']
_y = axis in ['y', 'both']
if _x:
self.xaxis.get_major_locator().set_params(**kwargs)
if _y:
self.yaxis.get_major_locator().set_params(**kwargs)
self.autoscale_view(tight=tight, scalex=_x, scaley=_y)
示例8: twinx
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def twinx(self):
"""
Create a twin Axes sharing the xaxis
Create a new Axes instance with an invisible x-axis and an independent
y-axis positioned opposite to the original one (i.e. at right). The
x-axis autoscale setting will be inherited from the original Axes.
To ensure that the tick marks of both y-axes align, see
`~matplotlib.ticker.LinearLocator`
Returns
-------
ax_twin : Axes
The newly created Axes instance
Notes
-----
For those who are 'picking' artists while using twinx, pick
events are only called for the artists in the top-most axes.
"""
ax2 = self._make_twin_axes(sharex=self)
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.yaxis.set_offset_position('right')
ax2.set_autoscalex_on(self.get_autoscalex_on())
self.yaxis.tick_left()
ax2.xaxis.set_visible(False)
ax2.patch.set_visible(False)
return ax2
示例9: twiny
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def twiny(self):
"""
Create a twin Axes sharing the yaxis
Create a new Axes instance with an invisible y-axis and an independent
x-axis positioned opposite to the original one (i.e. at top). The
y-axis autoscale setting will be inherited from the original Axes.
To ensure that the tick marks of both x-axes align, see
`~matplotlib.ticker.LinearLocator`
Returns
-------
ax_twin : Axes
The newly created Axes instance
Notes
-----
For those who are 'picking' artists while using twiny, pick
events are only called for the artists in the top-most axes.
"""
ax2 = self._make_twin_axes(sharey=self)
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top')
ax2.set_autoscaley_on(self.get_autoscaley_on())
self.xaxis.tick_bottom()
ax2.yaxis.set_visible(False)
ax2.patch.set_visible(False)
return ax2
示例10: __init__
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def __init__(self, base=1, month=1, day=1, tz=None):
"""
Mark years that are multiple of base on a given month and day
(default jan 1).
"""
DateLocator.__init__(self, tz)
self.base = ticker._Edge_integer(base, 0)
self.replaced = {'month': month,
'day': day,
'hour': 0,
'minute': 0,
'second': 0,
'tzinfo': tz
}
示例11: test_majformatter_type
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def test_majformatter_type():
fig, ax = plt.subplots()
with pytest.raises(TypeError):
ax.xaxis.set_major_formatter(matplotlib.ticker.LogLocator())
示例12: plot_scores_histogram_log
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def plot_scores_histogram_log(thresholds, all_counts, xlabel, true_counts=None, ax=None):
plt.figure()
# First graph
if ax is None:
_, ax = plt.subplots()
width = (thresholds[1] - thresholds[0]) / 2
offset = [i + width for i in thresholds]
if true_counts is not None:
falses = [i - j for i, j in zip(all_counts, true_counts)]
plt.bar(offset, falses, width=width,
log=True, label="False items")
plt.bar(thresholds, true_counts, width=width,
log=True, color="purple", label="True items")
else:
plt.bar(thresholds, all_counts, width=width,
log=True, color="purple", label="All items")
plt.grid(False)
ax.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.yaxis.get_major_formatter().set_scientific(False)
# Write to image
image_data = StringIO()
plt.xlim((0.0, 1.0))
plt.xlabel(xlabel)
plt.legend(loc='best')
plt.savefig(image_data, format='svg')
image_data.seek(0)
return image_data
示例13: locator_params
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def locator_params(self, axis='both', tight=None, **kwargs):
"""
Control behavior of tick locators.
Keyword arguments:
*axis*
['x' | 'y' | 'both'] Axis on which to operate;
default is 'both'.
*tight*
[True | False | None] Parameter passed to :meth:`autoscale_view`.
Default is None, for no change.
Remaining keyword arguments are passed to directly to the
:meth:`~matplotlib.ticker.MaxNLocator.set_params` method.
Typically one might want to reduce the maximum number
of ticks and use tight bounds when plotting small
subplots, for example::
ax.locator_params(tight=True, nbins=4)
Because the locator is involved in autoscaling,
:meth:`autoscale_view` is called automatically after
the parameters are changed.
This presently works only for the
:class:`~matplotlib.ticker.MaxNLocator` used
by default on linear axes, but it may be generalized.
"""
_x = axis in ['x', 'both']
_y = axis in ['y', 'both']
if _x:
self.xaxis.get_major_locator().set_params(**kwargs)
if _y:
self.yaxis.get_major_locator().set_params(**kwargs)
self.autoscale_view(tight=tight, scalex=_x, scaley=_y)
示例14: test_minformatter_type
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def test_minformatter_type():
fig, ax = plt.subplots()
with pytest.raises(TypeError):
ax.xaxis.set_minor_formatter(matplotlib.ticker.LogLocator())
示例15: test_minlocator_type
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import ticker [as 別名]
def test_minlocator_type():
fig, ax = plt.subplots()
with pytest.raises(TypeError):
ax.xaxis.set_minor_locator(matplotlib.ticker.LogFormatter())