def test_generate_tick_format_commands(self): """ Check that the tick format commands are correctly generated if they are set different to the default. """ fig, axes = plt.subplots(ncols=2, nrows=2, subplot_kw={'projection': 'mantid'}) for ax in fig.get_axes(): ax.plot([-10, 10], [1, 2]) # Only change the major formatter for one of the x axes and one of the y axes. # The rest will be default, and shouldn't generate any lines in the script. axes[0][1].xaxis.set_major_formatter(LogFormatterSciNotation()) axes[1][0].yaxis.set_major_formatter(LogFormatterSciNotation()) script = generate_script(fig) # Check the import is there exactly once. self.assertEqual(script.count("from matplotlib.ticker import"), 1) # We only set the major formatter for axes[0][1].xaxis, so the command should only be present there. self.assertNotIn("axes[0][0].xaxis.set_major_formatter", script) self.assertIn("axes[0][1].xaxis.set_major_formatter", script) self.assertNotIn("axes[1][0].xaxis.set_major_formatter", script) self.assertNotIn("axes[1][1].xaxis.set_major_formatter", script) # We only set the major formatter for axes[1][0].yaxis, so the command should only be present there. self.assertNotIn("axes[0][0].yaxis.set_major_formatter", script) self.assertNotIn("axes[0][1].yaxis.set_major_formatter", script) self.assertIn("axes[1][0].yaxis.set_major_formatter", script) self.assertNotIn("axes[1][1].yaxis.set_major_formatter", script)
def set_default_locators_and_formatters(self, axis): # docstring inherited axis.set_major_locator(LogLocator(self.base)) axis.set_major_formatter(LogFormatterSciNotation(self.base)) axis.set_minor_locator(LogLocator(self.base, self.subs)) axis.set_minor_formatter( LogFormatterSciNotation(self.base, labelOnlyBase=(self.subs is not None)))
def set_default_locators_and_formatters(self, axis): """ Set the locators and formatters to specialized versions for log scaling. """ axis.set_major_locator(LogLocator(self.base)) axis.set_major_formatter(LogFormatterSciNotation(self.base)) axis.set_minor_locator(LogLocator(self.base, self.subs)) axis.set_minor_formatter(LogFormatterSciNotation(self.base))
def test_update_axis_ticks_format(self): fig, ax = plt.subplots() x_axis = ax.xaxis x_axis.set_major_formatter(LogFormatterSciNotation()) x_axis.set_minor_formatter(LogFormatterSciNotation()) PlotsLoader.update_axis_ticks( x_axis, self.dictionary['properties']['xAxisProperties']) self.assertIsInstance(x_axis.get_major_formatter(), ScalarFormatter) self.assertIsInstance(x_axis.get_minor_formatter(), NullFormatter)
def test_axis_editor_initialised_with_correct_values_3d(self): a = np.array([[1]]) fig, ax = plt.subplots(subplot_kw={'projection': 'mantid3d'}) ax.plot_surface(a, a, a) # Set properties that can be accessed via the axes menu ax.set_xlim(1, 2) ax.set_ylim(3, 4) ax.set_zlim(5, 6) ax.xaxis.set_major_formatter(ScalarFormatter(useOffset=True)) ax.yaxis.set_major_formatter(ScalarFormatter(useOffset=True)) ax.zaxis.set_major_formatter(LogFormatterSciNotation()) # Create axis editors for each axis x_editor = XAxisEditor(fig.canvas, ax) y_editor = YAxisEditor(fig.canvas, ax) z_editor = ZAxisEditor(fig.canvas, ax) # Check that the correct axis is assigned self.assertEqual(x_editor.axis, ax.xaxis) self.assertEqual(y_editor.axis, ax.yaxis) self.assertEqual(z_editor.axis, ax.zaxis) # Test tick formats self.assertEqual(x_editor._memento.formatter, DECIMAL_FORMAT) self.assertEqual(y_editor._memento.formatter, DECIMAL_FORMAT) self.assertEqual(z_editor._memento.formatter, SCIENTIFIC_FORMAT) # Test limits self.assertEqual(x_editor._memento.min, ax.get_xlim()[0]) self.assertEqual(x_editor._memento.max, ax.get_xlim()[1]) self.assertEqual(y_editor._memento.min, ax.get_ylim()[0]) self.assertEqual(y_editor._memento.max, ax.get_ylim()[1]) self.assertEqual(z_editor._memento.min, ax.get_zlim()[0]) self.assertEqual(z_editor._memento.max, ax.get_zlim()[1])
def set_default_locators_and_formatters(self, axis): # docstring inherited axis.set_major_locator(SymmetricalLogLocator(self.get_transform())) axis.set_major_formatter(LogFormatterSciNotation(self.base)) axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(), self.subs)) axis.set_minor_formatter(NullFormatter())
def _set_tick_format(self): formatter = self.ui.editor_format.currentText() if formatter == DECIMAL_FORMAT: fmt = ScalarFormatter(useOffset=True) elif formatter == SCIENTIFIC_FORMAT: fmt = LogFormatterSciNotation() getattr(self.axes, '{}axis'.format(self.axis_id)).set_major_formatter(fmt) return
def _set_tick_format(self): formatter = self.ui.editor_format.currentText() if formatter == 'Decimal Format': fmt = ScalarFormatter(useOffset=True) elif formatter == 'Scientific Format': fmt = LogFormatterSciNotation() getattr(self.axes, 'get_{}axis'.format(self.axis_id))().set_major_formatter(fmt) return
def set_default_locators_and_formatters(self, axis): """ Set the locators and formatters to specialized versions for symmetrical log scaling. """ axis.set_major_locator(SymmetricalLogLocator(self.get_transform())) axis.set_major_formatter(LogFormatterSciNotation(self.base)) axis.set_minor_locator( SymmetricalLogLocator(self.get_transform(), self.subs)) axis.set_minor_formatter(NullFormatter())
def set_default_locators_and_formatters(self, axis): axis.set(major_locator=AsinhLocator(self.linear_width, base=self._base), minor_locator=AsinhLocator(self.linear_width, base=self._base, subs=self._subs), minor_formatter=NullFormatter()) if self._base > 1: axis.set_major_formatter(LogFormatterSciNotation(self._base)) else: axis.set_major_formatter('{x:.3g}'),
def _add_colorbar(im, cticks=None, label='', fmt='%d', log=False): """Adds Colorbar Nicely to figure""" ax = im.axes fig = ax.figure divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="3.5%", pad=0.05, axes_class=mpl.pyplot.Axes) if log: formatter = LogFormatterSciNotation(10, labelOnlyBase=False) else: formatter = fmt if isinstance(cticks, np.ndarray): fig.colorbar(im, ax=ax, cax=cax, label=label, format=formatter, ticks=cticks) else: fig.colorbar(im, ax=ax, cax=cax, label=label, format=formatter)
def build(self): """ Builds the configured plotting object. Returns: fig: figure object ax: axis object with the wanted configurations. """ fig, ax = plt.subplots(1, 1, figsize=self.__figsize) ax.set_title(self.__title) ax.set_yscale(self.__yscale) if self.__yscale == 'log': formatter = LogFormatterSciNotation(labelOnlyBase=False, minor_thresholds=(3, 0.5)) ax.yaxis.set_minor_formatter(formatter) ax.yaxis.set_major_formatter(formatter) else: ax.ticklabel_format(useOffset=False, style='plain') if self.__yaxis_formatter: ax.yaxis.set_major_formatter(self.__yaxis_formatter) if self.__xaxis_formatter: ax.xaxis.set_major_formatter(self.__xaxis_formatter) ax.set(xlabel=self.__xlabel) ax.set(ylabel=self.__ylabel) return [fig, ax]
def _get_formatter(self, locator, formatter, like, base, unit): log_base, symlog_thresh = self._parse_for_log_params(self.trans) if base is None: if symlog_thresh: log_base = 10 base = log_base if formatter is not None: return formatter if like is not None: if isinstance(like, str): if "{x" in like or "{pos" in like: fmt = like else: fmt = f"{{x:{like}}}" formatter = StrMethodFormatter(fmt) else: formatter = FuncFormatter(like) elif base is not None: # We could add other log options if necessary formatter = LogFormatterSciNotation(base) elif unit is not None: if isinstance(unit, tuple): sep, unit = unit else: sep = " " formatter = EngFormatter(unit, sep=sep) else: formatter = ScalarFormatter() return formatter
def __init__(self, model, pop_x_positions, ax=None, figsize=None, linthreshy=None, minor_yticks=None, major_yticks=None, color_map="cool", pulse_color_bounds=(0, 1), draw=True): self.leafs = model.leafs self.model = model.copy() try: pop_x_positions.items() except AttributeError: pop_x_positions = {p: i for i, p in enumerate(pop_x_positions)} self.x_pos = dict(pop_x_positions) if ax: self.ax = ax else: if figsize: plt.figure(figsize=figsize) fig = plt.gcf() fig.clf() self.ax = fig.gca() if linthreshy: self.ax.set_yscale('symlog', linthreshy=linthreshy) self.ax.get_yaxis().set_major_formatter( LogFormatterSciNotation(labelOnlyBase=False, minor_thresholds=(100, 100), linthresh=5e4)) self.ax.axhline(y=linthreshy, linestyle=":", color="black", zorder=1) self.minor_yticks = minor_yticks self.major_yticks = major_yticks self.additional_times = [] if minor_yticks: self.additional_times.extend(minor_yticks) if major_yticks: self.additional_times.extend(major_yticks) self.additional_times = sorted(self.additional_times) self._init_plot(model) self.all_N = [ p.N for popline in self._plot.pop_lines.values() for p in popline.points ] self.base_N = min(self.all_N) self.pmin, self.pmax = pulse_color_bounds self.cm_scalar_mappable = plt.cm.ScalarMappable( norm=mpl.colors.Normalize(vmin=self.pmin, vmax=self.pmax), cmap=color_map) self.cbar = None if draw: self.draw()
def format_ticks(self, values): if self.unit is None or self.unit == '': fmt = LogFormatterSciNotation() return [f"${fmt.format_data(10.0**x)}$" for x in values] else: return super().format_ticks(values)
from matplotlib.ticker import NullFormatter,\ ScalarFormatter, LogFormatterSciNotation from mantid import logger from mantid.api import AnalysisDataService as ADS from mantid.plots.legend import LegendProperties from mantid.plots.plotfunctions import create_subplots # Constants set in workbench.plotting.functions but would cause backwards reliability from mantidqt.plotting.functions import pcolormesh SUBPLOT_WSPACE = 0.5 SUBPLOT_HSPACE = 0.5 TICK_FORMATTERS = {"NullFormatter": NullFormatter(), "ScalarFormatter": ScalarFormatter(useOffset=True), "LogFormatterSciNotation": LogFormatterSciNotation() } def get_tick_format(tick_formatters: dict, tick_formatter: str, tick_format): if tick_formatter == "FixedFormatter": fmt = ticker.FixedFormatter(tick_format) else: try: fmt = tick_formatters[tick_formatter] except KeyError: # If the formatter is not FixedFormatter or # does not exist in global_tick_format_dict, # default to ScalarFormatter fmt = tick_formatters["ScalarFormatter"]
b = np.array(b) '----------------------------------------------------------------' print('Plotting ' + indep_name + ' vs. ' + dep_name) ### Relative error in normal distr. approx. ### A, B = np.meshgrid(a, b) #meshgrid for contour plot #print(a,b) #exit() err_n = np.load('err_norm.npy', allow_pickle=True) err_a = np.load('err_analytic.npy', allow_pickle=True) # err_n = err_n[:-1, :-1] #levels = MaxNLocator(nbins=5).tick_values(err.min(), 1) #setting contour levels levels = [1e0, 1e1, 1e2, 1e3] fmt = LogFormatterSciNotation() fmt.create_dummy_axis() #levelsf = MaxNLocator(nbins=60).tick_values(err.min(), err.max()) #setting contourf levels levelscheck = [2.0] #contours for regimes #mesh of regimes if indep_name == x1 and dep_name == y1: R1_plot = R1(A, B, z) elif indep_name == x1 and dep_name == z1: R1_plot = R1(A, y, B) elif indep_name == y1 and dep_name == z1: R1_plot = R1(x, A, B) CS1 = plt.contour(A, B, R1_plot,
def __init__(self, params_dict, default_N, event_list, additional_times, x_pos_dict, legend_kwargs, xlab_rotation=-30, exclude_xlabs=[], pop_marker_kwargs=None, adjust_pulse_labels={}, rename_pops={}, min_N=None, ax=None, cm_scalar_mappable=None, colornorm=None, alpha=1.0, pop_line_color="C0", pulse_line_color="gray", plot_pulse_nums=None, plot_leafs=True, linthreshy=None): self.plot_leafs = plot_leafs self.pop_marker_kwargs = pop_marker_kwargs self.exclude_xlabs = list(exclude_xlabs) self.adjust_pulse_labels = dict(adjust_pulse_labels) self.xlab_rotation = xlab_rotation self.legend_kwargs = legend_kwargs self.additional_times = list(additional_times) self.default_N = default_N self.pop_lines = { p: PopulationLine(p, x, self.additional_times, self.default_N) for p, x in x_pos_dict.items() } self.pop_arrows = [] self.rename_pops = rename_pops self.x_pos = x_pos_dict self.pop_line_color = pop_line_color self.pulse_line_color = pulse_line_color if plot_pulse_nums is None: plot_pulse_nums = not cm_scalar_mappable self.plot_pulse_nums = plot_pulse_nums for e in event_list: e.add_to_plot(params_dict, self) for pop in self.pop_lines.values(): pop.goto_time(float('inf')) if ax is None: self.fig = plt.gcf() self.fig.clf() self.ax = self.fig.gca() else: self.ax = ax self.fig = ax.get_figure() self.all_N = [ p.N for popline in self.pop_lines.values() for p in popline.points ] if min_N is None: self.min_N = min(self.all_N) else: self.min_N = min_N self.cm_scalar_mappable = cm_scalar_mappable self.alpha = alpha if linthreshy: self.ax.set_yscale('symlog', linthreshy=linthreshy) self.ax.get_yaxis().set_major_formatter( LogFormatterSciNotation(labelOnlyBase=False, minor_thresholds=(100, 100), linthresh=5e4))