{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Custom scale\n\nCustom scales can be created in two ways\n\n#. For simple cases, use `~.scale.FuncScale` and the ``'function'`` option of\n   `~.Axes.set_xscale` and `~.Axes.set_yscale`.  See the last example in\n   :doc:`/gallery/scales/scales`.\n\n#. Create a custom scale class such as the one in this example, which implements\n   the scaling use for latitude data in a Mercator Projection.  This more complicated\n   approach is useful when\n\n   * You are making special use of the `.Transform` class, such as the special\n     handling of values beyond the threshold in ``MercatorLatitudeTransform``\n     below.\n\n   * You want to override the default locators and formatters for the axis\n     (``set_default_locators_and_formatters`` below).\n\n   * You want to limit the range of the axis (``limit_range_for_scale`` below).\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nfrom numpy import ma\n\nfrom matplotlib import scale as mscale\nfrom matplotlib import transforms as mtransforms\nfrom matplotlib.ticker import FixedLocator, FuncFormatter\n\n\nclass MercatorLatitudeScale(mscale.ScaleBase):\n    \"\"\"\n    Scales data in range -pi/2 to pi/2 (-90 to 90 degrees) using\n    the system used to scale latitudes in a Mercator__ projection.\n\n    The scale function:\n      ln(tan(y) + sec(y))\n\n    The inverse scale function:\n      atan(sinh(y))\n\n    Since the Mercator scale tends to infinity at +/- 90 degrees,\n    there is user-defined threshold, above and below which nothing\n    will be plotted.  This defaults to +/- 85 degrees.\n\n    __ https://en.wikipedia.org/wiki/Mercator_projection\n    \"\"\"\n\n    # The scale class must have a member ``name`` that defines the string used\n    # to select the scale.  For example, ``ax.set_yscale(\"mercator\")`` would be\n    # used to select this scale.\n    name = 'mercator'\n\n    def __init__(self, axis, *, thresh=np.deg2rad(85), **kwargs):\n        \"\"\"\n        Any keyword arguments passed to ``set_xscale`` and ``set_yscale`` will\n        be passed along to the scale's constructor.\n\n        thresh: The degree above which to crop the data.\n        \"\"\"\n        super().__init__(axis)\n        if thresh >= np.pi / 2:\n            raise ValueError(\"thresh must be less than pi/2\")\n        self.thresh = thresh\n\n    def get_transform(self):\n        \"\"\"\n        Override this method to return a new instance that does the\n        actual transformation of the data.\n\n        The MercatorLatitudeTransform class is defined below as a\n        nested class of this one.\n        \"\"\"\n        return self.MercatorLatitudeTransform(self.thresh)\n\n    def set_default_locators_and_formatters(self, axis):\n        \"\"\"\n        Override to set up the locators and formatters to use with the\n        scale.  This is only required if the scale requires custom\n        locators and formatters.  Writing custom locators and\n        formatters is rather outside the scope of this example, but\n        there are many helpful examples in :mod:`.ticker`.\n\n        In our case, the Mercator example uses a fixed locator from -90 to 90\n        degrees and a custom formatter to convert the radians to degrees and\n        put a degree symbol after the value.\n        \"\"\"\n        fmt = FuncFormatter(\n            lambda x, pos=None: f\"{np.degrees(x):.0f}\\N{DEGREE SIGN}\")\n        axis.set(major_locator=FixedLocator(np.radians(range(-90, 90, 10))),\n                 major_formatter=fmt, minor_formatter=fmt)\n\n    def limit_range_for_scale(self, vmin, vmax, minpos):\n        \"\"\"\n        Override to limit the bounds of the axis to the domain of the\n        transform.  In the case of Mercator, the bounds should be\n        limited to the threshold that was passed in.  Unlike the\n        autoscaling provided by the tick locators, this range limiting\n        will always be adhered to, whether the axis range is set\n        manually, determined automatically or changed through panning\n        and zooming.\n        \"\"\"\n        return max(vmin, -self.thresh), min(vmax, self.thresh)\n\n    class MercatorLatitudeTransform(mtransforms.Transform):\n        # There are two value members that must be defined.\n        # ``input_dims`` and ``output_dims`` specify number of input\n        # dimensions and output dimensions to the transformation.\n        # These are used by the transformation framework to do some\n        # error checking and prevent incompatible transformations from\n        # being connected together.  When defining transforms for a\n        # scale, which are, by definition, separable and have only one\n        # dimension, these members should always be set to 1.\n        input_dims = output_dims = 1\n\n        def __init__(self, thresh):\n            mtransforms.Transform.__init__(self)\n            self.thresh = thresh\n\n        def transform_non_affine(self, a):\n            \"\"\"\n            This transform takes a numpy array and returns a transformed copy.\n            Since the range of the Mercator scale is limited by the\n            user-specified threshold, the input array must be masked to\n            contain only valid values.  Matplotlib will handle masked arrays\n            and remove the out-of-range data from the plot.  However, the\n            returned array *must* have the same shape as the input array, since\n            these values need to remain synchronized with values in the other\n            dimension.\n            \"\"\"\n            masked = ma.masked_where((a < -self.thresh) | (a > self.thresh), a)\n            if masked.mask.any():\n                return ma.log(np.abs(ma.tan(masked) + 1 / ma.cos(masked)))\n            else:\n                return np.log(np.abs(np.tan(a) + 1 / np.cos(a)))\n\n        def inverted(self):\n            \"\"\"\n            Override this method so Matplotlib knows how to get the\n            inverse transform for this transform.\n            \"\"\"\n            return MercatorLatitudeScale.InvertedMercatorLatitudeTransform(\n                self.thresh)\n\n    class InvertedMercatorLatitudeTransform(mtransforms.Transform):\n        input_dims = output_dims = 1\n\n        def __init__(self, thresh):\n            mtransforms.Transform.__init__(self)\n            self.thresh = thresh\n\n        def transform_non_affine(self, a):\n            return np.arctan(np.sinh(a))\n\n        def inverted(self):\n            return MercatorLatitudeScale.MercatorLatitudeTransform(self.thresh)\n\n\n# Now that the Scale class has been defined, it must be registered so\n# that Matplotlib can find it.\nmscale.register_scale(MercatorLatitudeScale)\n\n\nif __name__ == '__main__':\n    import matplotlib.pyplot as plt\n\n    t = np.arange(-180.0, 180.0, 0.1)\n    s = np.radians(t)/2.\n\n    plt.plot(t, s, '-', lw=2)\n    plt.yscale('mercator')\n\n    plt.xlabel('Longitude')\n    plt.ylabel('Latitude')\n    plt.title('Mercator projection')\n    plt.grid(True)\n\n    plt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}