Example #1
0
 def __init__(self, base, nonpositive='clip'):
     super().__init__()
     if base <= 0 or base == 1:
         raise ValueError('The log base cannot be <= 0 or == 1')
     self.base = base
     self._clip = _api.check_getitem(
         {"clip": True, "mask": False}, nonpositive=nonpositive)
Example #2
0
 def _set_transform(self):
     self.set_transform(_api.check_getitem({
         "data": self.Q.axes.transData,
         "axes": self.Q.axes.transAxes,
         "figure": self.Q.axes.figure.transFigure,
         "inches": self.Q.axes.figure.dpi_scale_trans,
     }, coordinates=self.coord))
Example #3
0
def _mpl_to_gtk_cursor(mpl_cursor):
    return _api.check_getitem({
        Cursors.MOVE: "move",
        Cursors.HAND: "pointer",
        Cursors.POINTER: "default",
        Cursors.SELECT_REGION: "crosshair",
        Cursors.WAIT: "wait",
        Cursors.RESIZE_HORIZONTAL: "ew-resize",
        Cursors.RESIZE_VERTICAL: "ns-resize",
    }, cursor=mpl_cursor)
Example #4
0
 def _dots_per_unit(self, units):
     """Return a scale factor for converting from units to pixels."""
     bb = self.axes.bbox
     vl = self.axes.viewLim
     return _api.check_getitem({
         'x': bb.width / vl.width,
         'y': bb.height / vl.height,
         'xy': np.hypot(*bb.size) / np.hypot(*vl.size),
         'width': bb.width,
         'height': bb.height,
         'dots': 1.,
         'inches': self.axes.figure.dpi,
     }, units=units)
Example #5
0
def _mpl_to_gtk_cursor(mpl_cursor):
    name = _api.check_getitem(
        {
            Cursors.MOVE: "move",
            Cursors.HAND: "pointer",
            Cursors.POINTER: "default",
            Cursors.SELECT_REGION: "crosshair",
            Cursors.WAIT: "wait",
            Cursors.RESIZE_HORIZONTAL: "ew-resize",
            Cursors.RESIZE_VERTICAL: "ns-resize",
        },
        cursor=mpl_cursor)
    return Gdk.Cursor.new_from_name(Gdk.Display.get_default(), name)
Example #6
0
    def set_axislabel_direction(self, label_direction):
        r"""
        Adjust the direction of the axislabel.

        Note that the *label_direction*\s '+' and '-' are relative to the
        direction of the increasing coordinate.

        Parameters
        ----------
        label_direction : {"+", "-"}
        """
        self._axislabel_add_angle = _api.check_getitem(
            {"+": 0, "-": 180}, label_direction=label_direction)
 def set_cursor(self, cursor):
     # docstring inherited
     cursor = _api.check_getitem(
         {
             backend_tools.Cursors.HAND: 'pointer',
             backend_tools.Cursors.POINTER: 'default',
             backend_tools.Cursors.SELECT_REGION: 'crosshair',
             backend_tools.Cursors.MOVE: 'move',
             backend_tools.Cursors.WAIT: 'wait',
             backend_tools.Cursors.RESIZE_HORIZONTAL: 'ew-resize',
             backend_tools.Cursors.RESIZE_VERTICAL: 'ns-resize',
         },
         cursor=cursor)
     self.send_event('cursor', cursor=cursor)
Example #8
0
 def set_cursor(self, cursor):
     # docstring inherited
     cursor = wx.Cursor(
         _api.check_getitem(
             {
                 cursors.MOVE: wx.CURSOR_HAND,
                 cursors.HAND: wx.CURSOR_HAND,
                 cursors.POINTER: wx.CURSOR_ARROW,
                 cursors.SELECT_REGION: wx.CURSOR_CROSS,
                 cursors.WAIT: wx.CURSOR_WAIT,
                 cursors.RESIZE_HORIZONTAL: wx.CURSOR_SIZEWE,
                 cursors.RESIZE_VERTICAL: wx.CURSOR_SIZENS,
             },
             cursor=cursor))
     self.SetCursor(cursor)
     self.Refresh()
Example #9
0
    def _print_ps(self,
                  fmt,
                  outfile,
                  *args,
                  dpi=None,
                  metadata=None,
                  papertype=None,
                  orientation='portrait',
                  **kwargs):

        if dpi is None:  # always use this branch after deprecation elapses.
            dpi = self.figure.get_dpi()
        self.figure.set_dpi(72)  # Override the dpi kwarg

        dsc_comments = {}
        if isinstance(outfile, (str, os.PathLike)):
            filename = pathlib.Path(outfile).name
            dsc_comments["Title"] = \
                filename.encode("ascii", "replace").decode("ascii")
        dsc_comments["Creator"] = (metadata or {}).get(
            "Creator",
            f"Matplotlib v{mpl.__version__}, https://matplotlib.org/")
        # See https://reproducible-builds.org/specs/source-date-epoch/
        source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
        dsc_comments["CreationDate"] = (datetime.datetime.utcfromtimestamp(
            int(source_date_epoch)).strftime("%a %b %d %H:%M:%S %Y")
                                        if source_date_epoch else time.ctime())
        dsc_comments = "\n".join(f"%%{k}: {v}"
                                 for k, v in dsc_comments.items())

        if papertype is None:
            papertype = mpl.rcParams['ps.papersize']
        papertype = papertype.lower()
        _api.check_in_list(['auto', *papersize], papertype=papertype)

        orientation = _api.check_getitem(_Orientation,
                                         orientation=orientation.lower())

        printer = (self._print_figure_tex
                   if mpl.rcParams['text.usetex'] else self._print_figure)
        printer(fmt,
                outfile,
                dpi=dpi,
                dsc_comments=dsc_comments,
                orientation=orientation,
                papertype=papertype,
                **kwargs)
Example #10
0
def scale_factory(scale, axis, **kwargs):
    """
    Return a scale class by name.

    Parameters
    ----------
    scale : {%(names)s}
    axis : `matplotlib.axis.Axis`
    """
    if scale != scale.lower():
        _api.warn_deprecated(
            "3.5",
            message="Support for case-insensitive scales is deprecated "
            "since %(since)s and support will be removed %(removal)s.")
        scale = scale.lower()
    scale_cls = _api.check_getitem(_scale_mapping, scale=scale)
    return scale_cls(axis, **kwargs)
Example #11
0
    def _parse_cached(self, s, dpi, prop):
        if prop is None:
            prop = FontProperties()

        fontset_class = _api.check_getitem(self._font_type_mapping,
                                           fontset=prop.get_math_fontfamily())
        backend = self._backend_mapping[self._output]()
        font_output = fontset_class(prop, backend)

        fontsize = prop.get_size_in_points()

        # This is a class variable so we don't rebuild the parser
        # with each request.
        if self._parser is None:
            self.__class__._parser = _mathtext.Parser()

        box = self._parser.parse(s, font_output, fontsize, dpi)
        backend.set_canvas_size(*np.ceil([box.width, box.height, box.depth]))
        return backend.get_results(box)
Example #12
0
    def __init__(self, value, units):
        """
        Create a new UnitDbl object.

        Units are internally converted to km, rad, and sec.  The only
        valid inputs for units are [m, km, mile, rad, deg, sec, min, hour].

        The field UnitDbl.value will contain the converted value.  Use
        the convert() method to get a specific type of units back.

        = ERROR CONDITIONS
        - If the input units are not in the allowed list, an error is thrown.

        = INPUT VARIABLES
        - value     The numeric value of the UnitDbl.
        - units     The string name of the units the value is in.
        """
        data = _api.check_getitem(self.allowed, units=units)
        self._value = float(value * data[0])
        self._units = data[1]
Example #13
0
    def convert(self, units):
        """
        Convert the UnitDbl to a specific set of units.

        = ERROR CONDITIONS
        - If the input units are not in the allowed list, an error is thrown.

        = INPUT VARIABLES
        - units     The string name of the units to convert to.

        = RETURN VALUE
        - Returns the value of the UnitDbl in the requested units as a floating
          point number.
        """
        if self._units == units:
            return self._value
        data = _api.check_getitem(self.allowed, units=units)
        if self._units != data[1]:
            raise ValueError(f"Error trying to convert to different units.\n"
                             f"    Invalid conversion requested.\n"
                             f"    UnitDbl: {self}\n"
                             f"    Units:   {units}\n")
        return self._value / data[0]
Example #14
0
 def __init__(self, ax, direction):
     self._get_size = _api.check_getitem(self._get_size_map,
                                         direction=direction)
     self._ax_list = [ax] if isinstance(ax, Axes) else ax
Example #15
0
 def set_default_angle(self, d):
     self.set_rotation(_api.check_getitem(self._default_angles, d=d))
Example #16
0
 def set_default_alignment(self, d):
     va, ha = _api.check_getitem(self._default_alignments, d=d)
     self.set_va(va)
     self.set_ha(ha)
Example #17
0
    def __init__(
        self, parent, handles, labels,
        loc=None,
        numpoints=None,      # number of points in the legend line
        markerscale=None,    # relative size of legend markers vs. original
        markerfirst=True,    # left/right ordering of legend marker and label
        scatterpoints=None,  # number of scatter points
        scatteryoffsets=None,
        prop=None,           # properties for the legend texts
        fontsize=None,       # keyword to set font size directly
        labelcolor=None,     # keyword to set the text color

        # spacing & pad defined as a fraction of the font-size
        borderpad=None,      # whitespace inside the legend border
        labelspacing=None,   # vertical space between the legend entries
        handlelength=None,   # length of the legend handles
        handleheight=None,   # height of the legend handles
        handletextpad=None,  # pad between the legend handle and text
        borderaxespad=None,  # pad between the axes and legend border
        columnspacing=None,  # spacing between columns

        ncol=1,     # number of columns
        mode=None,  # horizontal distribution of columns: None or "expand"

        fancybox=None,  # True: fancy box, False: rounded box, None: rcParam
        shadow=None,
        title=None,           # legend title
        title_fontsize=None,  # legend title font size
        framealpha=None,      # set frame alpha
        edgecolor=None,       # frame patch edgecolor
        facecolor=None,       # frame patch facecolor

        bbox_to_anchor=None,  # bbox to which the legend will be anchored
        bbox_transform=None,  # transform for the bbox
        frameon=None,         # draw frame
        handler_map=None,
        title_fontproperties=None,  # properties for the legend title
    ):
        """
        Parameters
        ----------
        parent : `~matplotlib.axes.Axes` or `.Figure`
            The artist that contains the legend.

        handles : list of `.Artist`
            A list of Artists (lines, patches) to be added to the legend.

        labels : list of str
            A list of labels to show next to the artists. The length of handles
            and labels should be the same. If they are not, they are truncated
            to the smaller of both lengths.

        Other Parameters
        ----------------
        %(_legend_kw_doc)s

        Notes
        -----
        Users can specify any arbitrary location for the legend using the
        *bbox_to_anchor* keyword argument. *bbox_to_anchor* can be a
        `.BboxBase` (or derived there from) or a tuple of 2 or 4 floats.
        See `set_bbox_to_anchor` for more detail.

        The legend location can be specified by setting *loc* with a tuple of
        2 floats, which is interpreted as the lower-left corner of the legend
        in the normalized axes coordinate.
        """
        # local import only to avoid circularity
        from matplotlib.axes import Axes
        from matplotlib.figure import FigureBase

        super().__init__()

        if prop is None:
            if fontsize is not None:
                self.prop = FontProperties(size=fontsize)
            else:
                self.prop = FontProperties(
                    size=mpl.rcParams["legend.fontsize"])
        else:
            self.prop = FontProperties._from_any(prop)
            if isinstance(prop, dict) and "size" not in prop:
                self.prop.set_size(mpl.rcParams["legend.fontsize"])

        self._fontsize = self.prop.get_size_in_points()

        self.texts = []
        self.legendHandles = []
        self._legend_title_box = None

        #: A dictionary with the extra handler mappings for this Legend
        #: instance.
        self._custom_handler_map = handler_map

        def val_or_rc(val, rc_name):
            return val if val is not None else mpl.rcParams[rc_name]

        self.numpoints = val_or_rc(numpoints, 'legend.numpoints')
        self.markerscale = val_or_rc(markerscale, 'legend.markerscale')
        self.scatterpoints = val_or_rc(scatterpoints, 'legend.scatterpoints')
        self.borderpad = val_or_rc(borderpad, 'legend.borderpad')
        self.labelspacing = val_or_rc(labelspacing, 'legend.labelspacing')
        self.handlelength = val_or_rc(handlelength, 'legend.handlelength')
        self.handleheight = val_or_rc(handleheight, 'legend.handleheight')
        self.handletextpad = val_or_rc(handletextpad, 'legend.handletextpad')
        self.borderaxespad = val_or_rc(borderaxespad, 'legend.borderaxespad')
        self.columnspacing = val_or_rc(columnspacing, 'legend.columnspacing')
        self.shadow = val_or_rc(shadow, 'legend.shadow')
        # trim handles and labels if illegal label...
        _lab, _hand = [], []
        for label, handle in zip(labels, handles):
            if isinstance(label, str) and label.startswith('_'):
                _api.warn_external('The handle {!r} has a label of {!r} '
                                   'which cannot be automatically added to'
                                   ' the legend.'.format(handle, label))
            else:
                _lab.append(label)
                _hand.append(handle)
        labels, handles = _lab, _hand

        handles = list(handles)
        if len(handles) < 2:
            ncol = 1
        self._ncol = ncol

        if self.numpoints <= 0:
            raise ValueError("numpoints must be > 0; it was %d" % numpoints)

        # introduce y-offset for handles of the scatter plot
        if scatteryoffsets is None:
            self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
        else:
            self._scatteryoffsets = np.asarray(scatteryoffsets)
        reps = self.scatterpoints // len(self._scatteryoffsets) + 1
        self._scatteryoffsets = np.tile(self._scatteryoffsets,
                                        reps)[:self.scatterpoints]

        # _legend_box is a VPacker instance that contains all
        # legend items and will be initialized from _init_legend_box()
        # method.
        self._legend_box = None

        if isinstance(parent, Axes):
            self.isaxes = True
            self.axes = parent
            self.set_figure(parent.figure)
        elif isinstance(parent, FigureBase):
            self.isaxes = False
            self.set_figure(parent)
        else:
            raise TypeError(
                "Legend needs either Axes or FigureBase as parent"
            )
        self.parent = parent

        self._loc_used_default = loc is None
        if loc is None:
            loc = mpl.rcParams["legend.loc"]
            if not self.isaxes and loc in [0, 'best']:
                loc = 'upper right'
        if isinstance(loc, str):
            loc = _api.check_getitem(self.codes, loc=loc)
        if not self.isaxes and loc == 0:
            raise ValueError(
                "Automatic legend placement (loc='best') not implemented for "
                "figure legend")

        self._mode = mode
        self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)

        # We use FancyBboxPatch to draw a legend frame. The location
        # and size of the box will be updated during the drawing time.

        if facecolor is None:
            facecolor = mpl.rcParams["legend.facecolor"]
        if facecolor == 'inherit':
            facecolor = mpl.rcParams["axes.facecolor"]

        if edgecolor is None:
            edgecolor = mpl.rcParams["legend.edgecolor"]
        if edgecolor == 'inherit':
            edgecolor = mpl.rcParams["axes.edgecolor"]

        if fancybox is None:
            fancybox = mpl.rcParams["legend.fancybox"]

        self.legendPatch = FancyBboxPatch(
            xy=(0, 0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            # If shadow is used, default to alpha=1 (#8943).
            alpha=(framealpha if framealpha is not None
                   else 1 if shadow
                   else mpl.rcParams["legend.framealpha"]),
            # The width and height of the legendPatch will be set (in draw())
            # to the length that includes the padding. Thus we set pad=0 here.
            boxstyle=("round,pad=0,rounding_size=0.2" if fancybox
                      else "square,pad=0"),
            mutation_scale=self._fontsize,
            snap=True,
            visible=(frameon if frameon is not None
                     else mpl.rcParams["legend.frameon"])
        )
        self._set_artist_props(self.legendPatch)

        # init with null renderer
        self._init_legend_box(handles, labels, markerfirst)

        tmp = self._loc_used_default
        self._set_loc(loc)
        self._loc_used_default = tmp  # ignore changes done by _set_loc

        # figure out title font properties:
        if title_fontsize is not None and title_fontproperties is not None:
            raise ValueError(
                "title_fontsize and title_fontproperties can't be specified "
                "at the same time. Only use one of them. ")
        title_prop_fp = FontProperties._from_any(title_fontproperties)
        if isinstance(title_fontproperties, dict):
            if "size" not in title_fontproperties:
                title_fontsize = mpl.rcParams["legend.title_fontsize"]
                title_prop_fp.set_size(title_fontsize)
        elif title_fontsize is not None:
            title_prop_fp.set_size(title_fontsize)
        elif not isinstance(title_fontproperties, FontProperties):
            title_fontsize = mpl.rcParams["legend.title_fontsize"]
            title_prop_fp.set_size(title_fontsize)

        self.set_title(title, prop=title_prop_fp)
        self._draggable = None

        # set the text color

        color_getters = {  # getter function depends on line or patch
            'linecolor':       ['get_color',           'get_facecolor'],
            'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'],
            'mfc':             ['get_markerfacecolor', 'get_facecolor'],
            'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'],
            'mec':             ['get_markeredgecolor', 'get_edgecolor'],
        }
        if labelcolor is None:
            if mpl.rcParams['legend.labelcolor'] is not None:
                labelcolor = mpl.rcParams['legend.labelcolor']
            else:
                labelcolor = mpl.rcParams['text.color']
        if isinstance(labelcolor, str) and labelcolor in color_getters:
            getter_names = color_getters[labelcolor]
            for handle, text in zip(self.legendHandles, self.texts):
                for getter_name in getter_names:
                    try:
                        color = getattr(handle, getter_name)()
                        text.set_color(color)
                        break
                    except AttributeError:
                        pass
        elif isinstance(labelcolor, str) and labelcolor == 'none':
            for text in self.texts:
                text.set_color(labelcolor)
        elif np.iterable(labelcolor):
            for text, color in zip(self.texts,
                                   itertools.cycle(
                                       colors.to_rgba_array(labelcolor))):
                text.set_color(color)
        else:
            raise ValueError("Invalid argument for labelcolor : %s" %
                             str(labelcolor))
Example #18
0
 def set_cursor(self, cursor):
     # docstring inherited
     self.setCursor(_api.check_getitem(cursord, cursor=cursor))
Example #19
0
 def set_cursor(self, cursor):
     # docstring inherited
     cursor = wx.Cursor(_api.check_getitem(cursord, cursor=cursor))
     self.SetCursor(cursor)
     self.Update()