Пример #1
0
 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())
Пример #2
0
 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}'),
Пример #3
0
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)
Пример #4
0
    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
Пример #5
0
 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]
Пример #6
0
 def __call__(self, x, pos=None):
     if x not in [1, 10]:
         return LogFormatterSciNotation.__call__(self, x, pos=None)
     else:
         return "{x:g}".format(x=x)
Пример #7
0
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"]
Пример #8
0
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,
Пример #9
0
 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)
Пример #10
0
    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))
Пример #11
0
    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()