Python matplotlib.ticker() Examples
The following are 30
code examples of matplotlib.ticker().
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: dates.py From CogAlg with MIT License | 6 votes |
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
Example #2
Source File: dates.py From coffeegrindsize with MIT License | 6 votes |
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
Example #3
Source File: plotter_matplotlib.py From postpic with GNU General Public License v3.0 | 6 votes |
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
Example #4
Source File: dates.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #5
Source File: 10e PSG (Same Window).py From PySimpleGUI with GNU Lesser General Public License v3.0 | 6 votes |
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
Example #6
Source File: 10d PSG (Plots Tabs and sin cos options).py From PySimpleGUI with GNU Lesser General Public License v3.0 | 6 votes |
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
Example #7
Source File: utils.py From Dense-CoAttention-Network with MIT License | 6 votes |
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))
Example #8
Source File: _base.py From coffeegrindsize with MIT License | 5 votes |
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
Example #9
Source File: dates.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def __init__(self, interval=1, tz=None): """ *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second microsecond. """ self._interval = interval self._wrapped_locator = ticker.MultipleLocator(interval) self.tz = tz
Example #10
Source File: dates.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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 }
Example #11
Source File: _base.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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
Example #12
Source File: plot.py From FlowCal with MIT License | 5 votes |
def view_limits(self, vmin, vmax): """ Try to choose the view limits intelligently. """ b = self._transform.base if vmax < vmin: vmin, vmax = vmax, vmin if not matplotlib.ticker.is_decade(abs(vmin), b): if vmin < 0: vmin = -_base_up(-vmin, b) else: vmin = _base_down(vmin, b) if not matplotlib.ticker.is_decade(abs(vmax), b): if vmax < 0: vmax = -_base_down(-vmax, b) else: vmax = _base_up(vmax, b) if vmin == vmax: if vmin < 0: vmin = -_base_up(-vmin, b) vmax = -_base_down(-vmax, b) else: vmin = _base_down(vmin, b) vmax = _base_up(vmax, b) result = matplotlib.transforms.nonsingular(vmin, vmax) return result
Example #13
Source File: plot.py From FlowCal with MIT License | 5 votes |
def set_default_locators_and_formatters(self, axis): """ Set up the locators and formatters for the scale. Parameters ---------- axis: matplotlib.axis Axis for which to set locators and formatters. """ axis.set_major_locator(_LogicleLocator(self._transform)) axis.set_minor_locator(_LogicleLocator(self._transform, subs=np.arange(2.0, 10.))) axis.set_major_formatter(matplotlib.ticker.LogFormatterSciNotation( labelOnlyBase=True))
Example #14
Source File: plots.py From scikit-optimize with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _cat_format(dimension, x, _): """Categorical axis tick formatter function. Returns the name of category `x` in `dimension`. Used with `matplotlib.ticker.FuncFormatter`.""" return str(dimension.categories[int(x)])
Example #15
Source File: plot.py From PE-HFT-Python with GNU General Public License v3.0 | 5 votes |
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()
Example #16
Source File: train.py From Global-Encoding with MIT License | 5 votes |
def showAttention(path, s, c, attentions, index): # Set up figure with colorbar fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(attentions.numpy(), cmap='bone') fig.colorbar(cax) # Set up axes ax.set_xticklabels([''] + s, rotation=90) ax.set_yticklabels([''] + c) # Show label at every tick ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) plt.show() plt.savefig(path + str(index) + '.jpg')
Example #17
Source File: _base.py From coffeegrindsize with MIT License | 5 votes |
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)
Example #18
Source File: _base.py From ImageFusion with MIT License | 5 votes |
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)
Example #19
Source File: _base.py From coffeegrindsize with MIT License | 5 votes |
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
Example #20
Source File: test_ticker.py From coffeegrindsize with MIT License | 5 votes |
def test_majformatter_type(): fig, ax = plt.subplots() with pytest.raises(TypeError): ax.xaxis.set_major_formatter(matplotlib.ticker.LogLocator())
Example #21
Source File: test_ticker.py From coffeegrindsize with MIT License | 5 votes |
def test_minformatter_type(): fig, ax = plt.subplots() with pytest.raises(TypeError): ax.xaxis.set_minor_formatter(matplotlib.ticker.LogLocator())
Example #22
Source File: test_ticker.py From coffeegrindsize with MIT License | 5 votes |
def test_minlocator_type(): fig, ax = plt.subplots() with pytest.raises(TypeError): ax.xaxis.set_minor_locator(matplotlib.ticker.LogFormatter())
Example #23
Source File: dates.py From coffeegrindsize with MIT License | 5 votes |
def __init__(self, interval=1, tz=None): """ *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second microsecond. """ self._interval = interval self._wrapped_locator = ticker.MultipleLocator(interval) self.tz = tz
Example #24
Source File: dates.py From CogAlg with MIT License | 5 votes |
def __init__(self, interval=1, tz=None): """ *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second microsecond. """ self._interval = interval self._wrapped_locator = ticker.MultipleLocator(interval) self.tz = tz
Example #25
Source File: visualization.py From OCDVAEContinualLearning with MIT License | 5 votes |
def visualize_confusion(writer, step, matrix, class_dict, save_path): """ Visualization of confusion matrix. Is saved to hard-drive and TensorBoard. Parameters: writer (tensorboard.SummaryWriter): TensorBoard SummaryWriter instance. step (int): Counter usually specifying steps/epochs/time. matrix (numpy.array): Square-shaped array of size class x class. Should specify cross-class accuracies/confusion in percent values (range 0-1). class_dict (dict): Dictionary specifying class names as keys and corresponding integer labels/targets as values. save_path (str): Path used for saving """ all_categories = sorted(class_dict, key=class_dict.get) fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(matrix) fig.colorbar(cax, boundaries=[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]) # Set up axes ax.set_xticklabels([''] + all_categories, rotation=90) ax.set_yticklabels([''] + all_categories) # Force label at every tick ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) # Turn off the grid for this plot ax.grid(False) plt.tight_layout() writer.add_figure("Training data", fig, global_step=str(step)) plt.savefig(os.path.join(save_path, 'confusion_epoch_' + str(step) + '.png'), bbox_inches='tight')
Example #26
Source File: _base.py From twitter-stock-recommendation with MIT License | 5 votes |
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)
Example #27
Source File: _base.py From twitter-stock-recommendation with MIT License | 5 votes |
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
Example #28
Source File: _base.py From twitter-stock-recommendation with MIT License | 5 votes |
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
Example #29
Source File: dates.py From twitter-stock-recommendation with MIT License | 5 votes |
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 }
Example #30
Source File: dates.py From twitter-stock-recommendation with MIT License | 5 votes |
def __init__(self, interval=1, tz=None): """ *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second microsecond. """ self._interval = interval self._wrapped_locator = ticker.MultipleLocator(interval) self.tz = tz