def curvelinear_test2(fig):
    """
    polar projection, but in a rectangular box.
    """
    global ax1
    # see demo_curvelinear_grid.py for details
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )

    grid_locator1 = angle_helper.LocatorDMS(12)

    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    fig.add_subplot(ax1)

    # Now creates floating axis

    # floating axis whose first coordinate (theta) is fixed at 60
    ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60)
    axis.label.set_text(r"$\theta = 60^{\circ}$")
    axis.label.set_visible(True)

    # floating axis whose second coordinate (r) is fixed at 6
    ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6)
    axis.label.set_text(r"$r = 6$")

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True)
Ejemplo n.º 2
0
def setup_axes(fig, rect, theta, radius):
    """ Sets up the axes in such a way we can plot the polarplot. """

    tr = PolarAxes.PolarTransform()

    pi = np.pi
    angle_ticks = [(-4. / 8. * pi, r"$-\frac{1}{2}\pi$"), (-3. / 8. * pi, r""),
                   (-2. / 8. * pi, r"$-\frac{1}{4}\pi$"), (-1. / 8. * pi, r""),
                   (0. / 8. * pi, r"$0$"), (1. / 8. * pi, r""),
                   (2. / 8. * pi, r"$\frac{1}{4}\pi$"), (3. / 8. * pi, r""),
                   (4. / 8. * pi, r"$\frac{1}{2}\pi$"),
                   (6. / 8. * pi, r"$\frac{3}{4}\pi$"),
                   (8. / 8. * pi, r"$\pi$")]

    grid_locator1 = FixedLocator([v for v, s in angle_ticks])
    tick_formatter1 = DictFormatter(dict(angle_ticks))
    grid_locator2 = MaxNLocator(3)

    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(theta[0], theta[1], radius[0], radius[1]),
        grid_locator1=grid_locator1,
        grid_locator2=grid_locator2,
        tick_formatter1=tick_formatter1,
        tick_formatter2=None)

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
    fig.add_subplot(ax1)

    # adjust axis
    # "bottom", "top", "left", "right"
    ax1.axis["left"].set_axis_direction("bottom")
    ax1.axis["right"].set_axis_direction("top")

    ax1.axis["bottom"].set_visible(False)
    ax1.axis["top"].set_axis_direction("bottom")
    ax1.axis["top"].toggle(ticklabels=True, label=True)
    ax1.axis["top"].major_ticklabels.set_axis_direction("top")
    ax1.axis["top"].label.set_axis_direction("top")

    # create a parasite axes
    aux_ax = ax1.get_aux_axes(tr)

    return ax1, aux_ax
Ejemplo n.º 3
0
def plot_taylor_diag(std, corr, ref_std, normalized=True):

    import mpl_toolkits.axisartist.grid_finder as gf
    import mpl_toolkits.axisartist.floating_axes as fa

    # define polar axes transform
    tr = PolarAxes.PolarTransform()

    # define correlation labels
    rlocs = np.concatenate((np.arange(10) / 10., [0.95, 0.99]))
    tlocs = np.arccos(rlocs)
    gl1 = gf.FixedLocator(tlocs)
    tf1 = gf.DictFormatter(dict(zip(tlocs, map(str, rlocs))))

    smin = 0
    smax = max(2.0, 1.1 * std.max())

    # add the curvilinear grid
    fig = plt.figure()

    ghelper = fa.GridHelperCurveLinear(tr,
                                       extremes=(0, np.pi / 2, smin, smax),
                                       grid_locator1=gl1,
                                       tick_formatter1=tf1)
    ax = fa.FloatingSubplot(fig, 111, grid_helper=ghelper)
    fig.add_subplot(ax)

    # adjust axes
    ax.axis["top"].set_axis_direction("bottom")
    ax.axis["top"].toggle(ticklabels=True, label=True)
    ax.axis["top"].major_ticklabels.set_axis_direction("top")
    ax.axis["top"].label.set_axis_direction("top")
    ax.axis["top"].label.set_text("Correlation")
    ax.axis["left"].set_axis_direction("bottom")
    if normalize:
        ax.axis["left"].label.set_text("Normalized standard deviation")
    else:
        ax.axis["left"].label.set_text("Standard deviation")
    ax.axis["right"].set_axis_direction("top")
    ax.axis["right"].toggle(ticklabels=True)
    ax.axis["right"].major_ticklabels.set_axis_direction("left")
    ax.axis["bottom"].set_visible(False)
    ax.grid(True)
Ejemplo n.º 4
0
    def __init__(self, figure):
        self.figure = figure

        self.the_min = 0
        self.the_max = 360

        self.r_min = 0
        self.r_max = 20

        self.the_label = 'The'
        self.r_label = 'R'

        # ---

        tr_scale = Affine2D().scale(np.pi / 180., 1.)
        tr = tr_scale + PolarAxes.PolarTransform()
        grid_helper = GridHelperCurveLinear(tr)

        a = FloatingSubplot(self.figure, 111, grid_helper=grid_helper)
        self.figure.add_subplot(a)

        # ---

        # adjust x axis (theta):
        a["bottom"].set_visible(False)
        a.axis["top"].set_axis_direction("bottom")  # tick direction
        a.axis["top"].major_ticklabels.set_axis_direction("top")
        a.axis["top"].label.set_axis_direction("top")

        # adjust y axis (r):
        a.axis["left"].set_axis_direction("bottom")  # tick direction
        a.axis["right"].set_axis_direction("top")  # tick direction

        # ---
        # create a parasite axes whose transData is theta, r:
        self.plt = a.get_aux_axes(tr)
        # make aux_ax to have a clip path as in a?:
        self.patch = a.patch
        # this has a side effect that the patch is drawn twice, and possibly over some other
        # artists. So, we decrease the zorder a bit to prevent this:
        a.patch.zorder = -2

        self.plt.add_artist(plt.Circle([0, 0]))
Ejemplo n.º 5
0
def setup_axes2(fig, rect):
    """
    With custom locator and formatter.
    Note that the extreme values are swapped.
    """
    tr = PolarAxes.PolarTransform()

    pi = np.pi
    angle_ticks = [(.5 * pi, r"90$\degree$"), (.625 * pi, r"112.5$\degree$"),
                   (.75 * pi, r"135$\degree$"),
                   (.81111111 * pi, r"146$\degree$"),
                   (.84444444 * pi, r"152$\degree$"), (pi, r"180$\degree$")]
    grid_locator1 = FixedLocator([v for v, s in angle_ticks])
    tick_formatter1 = DictFormatter(dict(angle_ticks))

    grid_locator2 = MaxNLocator(2)

    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(pi, 0.5 * pi, 6371, 0),
        grid_locator1=grid_locator1,
        grid_locator2=grid_locator2,
        tick_formatter1=tick_formatter1,
        tick_formatter2=None)

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
    ax1.axis["bottom"].major_ticklabels.set_axis_direction("top")
    ax1.axis["left"].toggle(ticklabels=False)
    ax1.axis["left"].toggle(ticks=False)
    ax1.axis["top"].toggle(ticks=False)
    fig.add_subplot(ax1)

    # create a parasite axes whose transData in RA, cz
    aux_ax = ax1.get_aux_axes(tr)

    aux_ax.patch = ax1.patch  # for aux_ax to have a clip path as in ax
    ax1.patch.zorder = 0.9  # but this has a side effect that the patch is
    # drawn twice, and possibly over some other
    # artists. So, we decrease the zorder a bit to
    # prevent this.

    return ax1, aux_ax
def setup_axes3(fig, rect):
    #menentukan axis_direction
    tr_rotate = Affine2D().translate(-95, 0)
    tr_scale = Affine2D().scale(np.pi / 180., 1.)
    tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()

    grid_locator1 = angle_helper.LocatorHMS(4)
    tick_formatter1 = angle_helper.FormatterHMS()

    grid_locator2 = MaxNLocator(3)
    ra0, ra1 = 8. * 15, 14. * 15
    cz0, cz1 = 0, 14000
    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(ra0, ra1, cz0, cz1),
        grid_locator1=grid_locator1,
        grid_locator2=grid_locator2,
        tick_formatter1=tick_formatter1,
        tick_formatter2=None,
    )

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
    fig.add_subplot(ax1)

    ax1.axis["left"].set_axis_direction("bottom")
    ax1.axis["right"].set_axis_direction("top")

    ax1.axis["bottom"].set_visible("False")
    ax1.axis["top"].set_axis_direction("bottom")
    ax1.axis["top"].toggle(ticklabels=True, label=True)
    ax1.axis["top"].major_ticklabels.set_axis_direction("top")
    ax1.axis["top"].label.set_axis_direction("top")

    ax1.axis["left"].label.set_text(r"cz [km$^{-1}$]")
    ax1.axis["top"].label.set_text(r"$\alpha_{1950}$]")

    aux_ax = ax1.get_aux_axes(tr)
    aux_ax.patch = ax1.patch
    #efek dari patch adalah lebih sederhana dan lebih pada tampilan lainnya
    ax1.patch.zorder = 0.9
    return ax1, aux_ax
Ejemplo n.º 7
0
def setup_axes(fig, rect):
    """
    polar projection, but in a rectangular box.
    """

    # see demo_curvelinear_grid.py for details
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )

    grid_locator1 = angle_helper.LocatorDMS(12)
    grid_locator2 = grid_finder.MaxNLocator(5)

    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        grid_locator2=grid_locator2,
                                        tick_formatter1=tick_formatter1)

    ax1 = axisartist.Subplot(fig, rect, grid_helper=grid_helper)
    #ax1.axis[:].toggle(all=False)
    ax1.axis[:].set_visible(False)

    fig.add_subplot(ax1)

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    #ax1.grid(True)

    return ax1
Ejemplo n.º 8
0
def setup_axes2(fig, rect):
    """
    With custom locator and formatter.
    Note that the extreme values are swapped.
    """

    #tr_scale = Affine2D().scale(np.pi/180., 1.)

    tr = PolarAxes.PolarTransform()

    pi = np.pi
    angle_ticks = [(0, r"$0$"), (.25 * pi, r"$\frac{1}{4}\pi$"),
                   (.5 * pi, r"$\frac{1}{2}\pi$")]
    grid_locator1 = FixedLocator([v for v, s in angle_ticks])
    tick_formatter1 = DictFormatter(dict(angle_ticks))

    grid_locator2 = MaxNLocator(2)

    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(.5 * pi, 0, 2, 1),
        grid_locator1=grid_locator1,
        grid_locator2=grid_locator2,
        tick_formatter1=tick_formatter1,
        tick_formatter2=None,
    )

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
    fig.add_subplot(ax1)

    # create a parasite axes whose transData in RA, cz
    aux_ax = ax1.get_aux_axes(tr)

    aux_ax.patch = ax1.patch  # for aux_ax to have a clip path as in ax
    ax1.patch.zorder = 0.9  # but this has a side effect that the patch is
    # drawn twice, and possibly over some other
    # artists. So, we decrease the zorder a bit to
    # prevent this.

    return ax1, aux_ax
Ejemplo n.º 9
0
    def setup_axes(self, fig, rect, n_markers):
        """
        With custom locator and formatter.
        Note that the extreme values are swapped.
        """

        tr = PolarAxes.PolarTransform()

        rs = np.linspace(self.r_inner, self.r_outer, n_markers)

        angle_ticks = []

        grid_locator1 = FixedLocator([v for v, s in angle_ticks])
        tick_formatter1 = DictFormatter(dict(angle_ticks))

        # set the number of r points you want on plot
        grid_locator2 = FixedLocator(rs)
        tick_formatter2 = None

        grid_helper = floating_axes.GridHelperCurveLinear(
            tr,
            extremes=(0.5 * np.pi, -0.5 * np.pi, self.r_outer, self.r_inner),
            grid_locator1=grid_locator1,
            grid_locator2=grid_locator2,
            tick_formatter1=tick_formatter1,
            tick_formatter2=tick_formatter2)

        ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
        fig.add_subplot(ax1)

        # create a parasite axes whose transData in RA, cz
        aux_ax = ax1.get_aux_axes(tr)

        aux_ax.patch = ax1.patch  # for aux_ax to have a clip path as in ax
        ax1.patch.zorder = 0.9  # but this has a side effect that the patch is
        # drawn twice, and possibly over some other
        # artists. So, we decrease the zorder a bit to
        # prevent this.

        return ax1, aux_ax
Ejemplo n.º 10
0
    def polarplot(self):

        tr = PolarAxes.PolarTransform()

        grid_locator1 = FixedLocator([v for v, s in self.angle_ticks])
        tick_formatter1 = DictFormatter(dict(self.angle_ticks))

        grid_locator2 = FixedLocator([a for a, b in self.radius_ticks])
        tick_formatter2 = DictFormatter(dict(self.radius_ticks))

        grid_helper = floating_axes.GridHelperCurveLinear(
            tr,
            extremes=(self.max_angle, self.min_angle, self.max_rad,
                      self.min_rad),
            grid_locator1=grid_locator1,
            grid_locator2=grid_locator2,
            tick_formatter1=tick_formatter1,
            tick_formatter2=tick_formatter2)

        ax = floating_axes.FloatingSubplot(self.fig,
                                           self.rect,
                                           grid_helper=grid_helper)
        self.fig.add_subplot(ax)
        ax.grid(True, color='b', linewidth=0.2, linestyle='-')

        aux_ax = ax.get_aux_axes(tr)
        aux_ax.patch = ax.patch
        ax.patch.zorder = 0.9

        ax.axis['bottom'].set_label(r'Angle ($^{\circ}$)')
        ax.axis['bottom'].major_ticklabels.set_rotation(180)
        ax.axis['bottom'].label.set_rotation(180)
        ax.axis['bottom'].LABELPAD += 30
        ax.axis['left'].set_label('Range (m)')
        ax.axis['left'].label.set_rotation(0)
        ax.axis['left'].LABELPAD += 15
        ax.axis['left'].set_visible(True)

        return ax, aux_ax
Ejemplo n.º 11
0
def setup_axes2(fig, rect, tmin, tmax, zmin, zmax):
    """
  With custom locator and formatter.
  Note that the extreme values are swapped.
  """

    tr = PolarAxes.PolarTransform()
    pi = np.pi

    angle_ticks = [(tmin, '%.2f' % tmin), (0, r'$0$'), (tmax, '%.2f' % tmax)]

    grid_locator1 = FixedLocator([v for v, s in angle_ticks])
    tick_formatter1 = DictFormatter(dict(angle_ticks))

    grid_locator2 = MaxNLocator(4)

    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(tmax, tmin, zmax, zmin),
        grid_locator1=grid_locator1,
        grid_locator2=grid_locator2,
        tick_formatter1=tick_formatter1,
        tick_formatter2=None)

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
    fig.add_subplot(ax1)

    # create a parasite axes whose transData in RA, cz
    aux_ax = ax1.get_aux_axes(tr)

    aux_ax.patch = ax1.patch  # for aux_ax to have a clip path as in ax
    ax1.patch.zorder = 0.95  # but this has a side effect that the patch is
    # drawn twice, and possibly over some other
    # artists. So, we decrease the zorder a bit to
    # prevent this.

    return ax1, aux_ax
Ejemplo n.º 12
0
    def setup_axes2(fig, rect):
        """
        With custom locator and formatter.
        Note that the extreme values are swapped.
        """
        tr = PolarAxes.PolarTransform()

        pi = np.pi
        angle_ticks = [(0,'180' ),
                   (.25*pi,'135' ),
                   (.5*pi, '90'),
                   (.75*pi,'45' ),
                   (pi,'0')]
        grid_locator1 = FixedLocator([v for v, s in angle_ticks])
        tick_formatter1 = DictFormatter(dict(angle_ticks))

        grid_locator2 = MaxNLocator(nbins=6)

        grid_helper = floating_axes.GridHelperCurveLinear(
            tr, extremes=(pi,0, 6371,3481),
            grid_locator1=grid_locator1,
            grid_locator2=grid_locator2,
            tick_formatter1=tick_formatter1,
            tick_formatter2=None)

        ax1 = floating_axes.FloatingSubplot(fig, rect,
                          grid_helper=grid_helper)
        fig.add_subplot(ax1)
        aux_ax = ax1.get_aux_axes(tr)

        aux_ax.patch = ax1.patch  # for aux_ax to have a clip path as in ax
        ax1.patch.zorder = 0.9  # but this has a side effect that the patch is
        # drawn twice, and possibly over some other
        # artists. So, we decrease the zorder a bit to
        # prevent this.

        return ax1, aux_ax
Ejemplo n.º 13
0
def get_slice_axes(fig, num, lat1=-90., lat2=90., shrink=1.0):

    tr_rotate = Affine2D().translate(0, 90)
    # set up polar axis
    tr = PolarAxes.PolarTransform() + tr_rotate

    angle_ticks = [(np.radians(i), str(i)) for i in np.arange(80, -81, -10)]
    # angle_ticks = [(np.radians(80), r"$80$"),
    #                (np.radians(40), r"$\frac{3}{4}\pi$"),
    #                (1.*np.pi, r"$\pi$"),
    #                (1.25*np.pi, r"$\frac{5}{4}\pi$"),
    #                (1.5*np.pi, r"$\frac{3}{2}\pi$"),
    #                (1.75*np.pi, r"$\frac{7}{4}\pi$")]

    # set up ticks and spacing around the circle
    grid_locator1 = FixedLocator([v for v, s in angle_ticks])
    tick_formatter1 = DictFormatter(dict(angle_ticks))

    # set up grid spacing along the 'radius'
    radius_ticks = [
        (1., ''),
        # (1.5, '%i' % (MAX_R/2.)),
        (R / Rb, '')
    ]

    grid_locator2 = FixedLocator([v for v, s in radius_ticks])
    tick_formatter2 = DictFormatter(dict(radius_ticks))

    # define angle ticks around the circumference:
    # set up axis:
    # tr: the polar axis setup
    # extremes: theta max, theta min, r max, r min
    # the grid for the theta axis
    # the grid for the r axis
    # the tick formatting for the theta axis
    # the tick formatting for the r axis
    lat1 = np.radians(lat1)
    lat2 = np.radians(lat2)
    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(-lat1, lat2, R / Rb * shrink, 1 * shrink),
        grid_locator1=grid_locator1,
        grid_locator2=grid_locator2,
        tick_formatter1=tick_formatter1,
        tick_formatter2=tick_formatter2)

    ax1 = floating_axes.FloatingSubplot(fig, num, grid_helper=grid_helper)
    fig.add_subplot(ax1)

    ax1.axis["left"].set_axis_direction("bottom")
    ax1.axis["right"].set_axis_direction("bottom")
    ax1.axis["left"].major_ticklabels.set_rotation(90)
    #ax1.axis["right"].set_tick_direction('out')
    #ax1.axis
    # ax1.axis["left"].major_ticks.set_tick_out(True)
    # # ax1.axis["bottom"].set_visible(False)
    ax1.axis["bottom"].set_axis_direction("right")
    ax1.axis["bottom"].major_ticks.set_tick_out(True)
    # ax1.axis["bottom"].major_ticklabels.locs_angles_labels = [0, 0, 0, 0,0,0,0]
    # print(ax1.axis["bottom"].major_ticklabels._locs_angles_labels)
    #ax1.axis["bottom"].major_ticklabels.set_ha('right')

    majortick_iter, minortick_iter = ax1.axis[
        'bottom']._axis_artist_helper.get_tick_iterators(ax1)
    tick_loc_angle, ticklabel_loc_angle_label = ax1.axis[
        'bottom']._get_tick_info(majortick_iter)
    #ax1.axis["bottom"].major_ticklabels.set_pad(1.0)
    aux_ax = ax1.get_aux_axes(tr)

    aux_ax.patch = ax1.patch  # for aux_ax to have a clip path as in ax
    ax1.patch.zorder = 0.9  # but this has a side effect that the patch is
    #  drawn twice, and possibly over some other
    #  artists. So, we decrease the zorder a bit to
    #  prevent this.

    return ax1, aux_ax
    def setup_axes(self, fig, rect=111):
        """Set up Taylor diagram axes, i.e. single quadrant polar
        plot, using mpl_toolkits.axisartist.floating_axes.

        Wouldn't the ideal be to define its own non-linear
        transformation, so that coordinates are directly r=stddev and
        theta=correlation? I guess it would allow 
        """

        from matplotlib.projections import PolarAxes
        import mpl_toolkits.axisartist.floating_axes as FA
        import mpl_toolkits.axisartist.grid_finder as GF

        tr = PolarAxes.PolarTransform()

        # Correlation labels
        rlocs = NP.concatenate((NP.arange(10)/10.,[0.95,0.99]))
        tlocs = NP.arccos(rlocs)        # Conversion to polar angles
        gl1 = GF.FixedLocator(tlocs)    # Positions
        tf1 = GF.DictFormatter(dict(zip(tlocs, map(str,rlocs))))

        ghelper = FA.GridHelperCurveLinear(tr,
                                           extremes=(0,NP.pi/2, # 1st quadrant
                                                     0,1.5*self.ref.std()),
                                           grid_locator1=gl1,
                                           tick_formatter1=tf1,
                                           )

        ax = FA.FloatingSubplot(fig, rect, grid_helper=ghelper)
        fig.add_subplot(ax)

        # Adjust axes
        ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
        ax.axis["top"].toggle(ticklabels=True, label=True)
        ax.axis["top"].major_ticklabels.set_axis_direction("top")
        ax.axis["top"].label.set_axis_direction("top")
        ax.axis["top"].label.set_text("Correlation")

        ax.axis["left"].set_axis_direction("bottom") # "X axis"
        ax.axis["left"].label.set_text("Standard deviation")

        ax.axis["right"].set_axis_direction("top")   # "Y axis"
        ax.axis["right"].toggle(ticklabels=True)
        ax.axis["right"].major_ticklabels.set_axis_direction("left")

        ax.axis["bottom"].set_visible(False)         # Useless
        
        # Grid
        ax.grid()

        self._ax = ax                   # Graphical axes
        self.ax = ax.get_aux_axes(tr)   # Polar coordinates

        # Add reference point and stddev contour
        print("Reference std:", self.ref.std())
        self.ax.plot([0],self.ref.std(),'ko', label='_')
        t = NP.linspace(0,NP.pi/2)
        r = NP.zeros_like(t) + self.ref.std()
        self.ax.plot(t,r,'k--', label='_')

        return self.ax
Ejemplo n.º 15
0
    def __init__(
        self,
        ref_point: float,
        fig: Optional[plt.figure] = None,
        subplot: Optional[int] = 111,
        extend_angle: bool = False,
        corr_labels: Optional[np.ndarray] = None,
        ref_range: Tuple[float, float] = (0, 10),
        ref_label: str = "Reference Point",
        angle_label: str = "Correlation",
        var_label: str = "Standard Deviation",
    ) -> None:

        self.angle_label = angle_label
        self.ref_label = ref_label
        self.var_label = var_label
        self.extend_angle = extend_angle

        # correlation labels
        if corr_labels is None:
            corr_labels = np.array(
                [0, 0.2, 0.4, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1.0])

        # extend
        if extend_angle:
            # Extend to negative correlations
            self.tmax = np.pi
            corr_labels = np.concatenate((-corr_labels[:0:-1], corr_labels))
        else:
            # limit to only positive correlations
            self.tmax = np.pi / 2.0

        # init figure
        if fig is None:
            fig = plt.figure(figsize=(8, 8))

        # extend or not
        self.smin = ref_range[0] * ref_point
        self.smax = (ref_range[1] / 100) * ref_point + ref_point

        corr_ticks = np.arccos(corr_labels)
        gl1 = grid_finder.FixedLocator(corr_ticks)
        tf1 = grid_finder.DictFormatter(
            dict(zip(corr_ticks, map(str, corr_labels))))

        # Grid Helper
        ghelper = floating_axes.GridHelperCurveLinear(
            aux_trans=PolarAxes.PolarTransform(),
            extremes=(0, self.tmax, self.smin, self.smax),
            grid_locator1=gl1,
            tick_formatter1=tf1,
        )

        # create graphical axes

        ax = floating_axes.FloatingSubplot(fig, subplot, grid_helper=ghelper)
        fig.add_subplot(ax)
        self.graph_axes = ax
        self.polar_axes = ax.get_aux_axes(PolarAxes.PolarTransform())

        self.sample_points = []
        # Setup Axes
        self.reset_axes()
Ejemplo n.º 16
0
def curvelinear_test3(fig):
    """
    polar projection, but in a rectangular box.
    """
    global ax1, axis
    import numpy as np
    from . import angle_helper
    from matplotlib.projections import PolarAxes
    from matplotlib.transforms import Affine2D

    from mpl_toolkits.axes_grid.parasite_axes import SubplotHost

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )

    grid_locator1 = angle_helper.LocatorDMS(12)
    # Find a grid values appropriate for the coordinate (degree,
    # minute, second).

    tick_formatter1 = angle_helper.FormatterDMS()
    # And also uses an appropriate formatter.  Note that,the
    # acceptable Locator and Formatter class is a bit different than
    # that of mpl's, and you cannot directly use mpl's Locator and
    # Formatter here (but may be possible in the future).

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    for axis in list(six.itervalues(ax1.axis)):
        axis.set_visible(False)

    fig.add_subplot(ax1)

    grid_helper = ax1.get_grid_helper()
    ax1.axis["lat1"] = axis = grid_helper.new_floating_axis(
        0, 130, axes=ax1, axis_direction="left")
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper()._extremes = 0.001, 10

    grid_helper = ax1.get_grid_helper()
    ax1.axis["lat2"] = axis = grid_helper.new_floating_axis(
        0, 50, axes=ax1, axis_direction="right")
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper()._extremes = 0.001, 10

    ax1.axis["lon"] = axis = grid_helper.new_floating_axis(
        1, 10, axes=ax1, axis_direction="bottom")
    axis.label.set_text("Test 2")
    axis.get_helper()._extremes = 50, 130
    axis.major_ticklabels.set_axis_direction("top")
    axis.label.set_axis_direction("top")

    grid_helper.grid_finder.grid_locator1.den = 5
    grid_helper.grid_finder.grid_locator2._nbins = 5

    #     # A parasite axes with given transform
    #     ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    #     # note that ax2.transData == tr + ax1.transData
    #     # Anthing you draw in ax2 will match the ticks and grids of ax1.
    #     ax1.parasites.append(ax2)
    #     intp = cbook.simple_linear_interpolation
    #     ax2.plot(intp(np.array([0, 30]), 50),
    #              intp(np.array([10., 10.]), 50))

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True)
Ejemplo n.º 17
0
    def __init__(self,
                 refstd,
                 refcorrcoef=1.0,
                 fig=None,
                 rect=111,
                 label='_',
                 srange=(0, 1.5)):
        """Set up Taylor diagram axes, i.e. single quadrant polar
        plot, using `mpl_toolkits.axisartist.floating_axes`. 

        Parameters:
        
        * refstd: reference standard deviation to be compared to
        * fig: input Figure or None
        * rect: subplot definition
        * label: reference label
        * srange: stddev axis extension, in units of *refstd*
        """

        from matplotlib.projections import PolarAxes
        import mpl_toolkits.axisartist.floating_axes as FA
        import mpl_toolkits.axisartist.grid_finder as GF

        self.refstd = refstd  # Reference standard deviation

        tr = PolarAxes.PolarTransform()

        # Correlation labels
        rlocs = NP.concatenate((NP.arange(10) / 10., [0.95, 0.99]))
        tlocs = NP.arccos(rlocs)  # Conversion to polar angles
        gl1 = GF.FixedLocator(tlocs)  # Positions
        tf1 = GF.DictFormatter(dict(zip(tlocs, map(str, rlocs))))

        # Standard deviation axis extent (in units of reference stddev)
        self.smin = srange[0] * self.refstd
        self.smax = srange[1] * self.refstd

        ghelper = FA.GridHelperCurveLinear(
            tr,
            extremes=(
                0,
                NP.pi / 2,  # 1st quadrant
                self.smin,
                self.smax),
            grid_locator1=gl1,
            tick_formatter1=tf1)

        if fig is None:
            fig = PLT.figure()

        ax = FA.FloatingSubplot(fig, rect, grid_helper=ghelper)
        fig.add_subplot(ax)

        # Adjust axes
        ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
        ax.axis["top"].toggle(ticklabels=True, label=True)
        ax.axis["top"].major_ticklabels.set_axis_direction("top")
        ax.axis["top"].label.set_axis_direction("top")
        ax.axis["top"].label.set_text("Correlation")

        ax.axis["left"].set_axis_direction("bottom")  # "X axis"
        ax.axis["left"].label.set_text("Standard deviation")

        ax.axis["right"].set_axis_direction("top")  # "Y axis"
        ax.axis["right"].toggle(ticklabels=True)
        ax.axis["right"].major_ticklabels.set_axis_direction("left")

        ax.axis["bottom"].set_visible(False)  # Useless

        self._ax = ax  # Graphical axes
        self.ax = ax.get_aux_axes(tr)  # Polar coordinates

        # Add reference point and stddev contour
        l, = self.ax.plot(NP.arccos(refcorrcoef),
                          self.refstd,
                          'k*',
                          ls='',
                          ms=10,
                          label=label)
        t = NP.linspace(0, NP.pi / 2)
        r = NP.zeros_like(t) + self.refstd
        self.ax.plot(t, r, 'k--', label='_')

        # Collect sample points for latter use (e.g. legend)
        self.samplePoints = [l]
Ejemplo n.º 18
0
def create_cg(fig=None,
              subplot=111,
              rot=-450,
              scale=-1,
              angular_spacing=10,
              radial_spacing=10,
              latmin=0,
              lon_cycle=360):
    """ Helper function to create curvelinear grid

    The function makes use of the Matplotlib AXISARTIST namespace
    `mpl_toolkits.axisartist \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html>`_.

    Here are some limitations to normal Matplotlib Axes. While using the
    Matplotlib `AxesGrid Toolkit \
    <https://matplotlib.org/mpl_toolkits/axes_grid/index.html>`_
    most of the limitations can be overcome.
    See `Matplotlib AxesGrid Toolkit User’s Guide \
    <https://matplotlib.org/mpl_toolkits/axes_grid/users/index.html>`_.

    Parameters
    ----------
    fig : matplotlib Figure object
        If given, the PPI/RHI will be plotted into this figure object.
        Axes are created as needed. If None a new figure object will
        be created or current figure will be used, depending on "subplot".
    subplot : :class:`matplotlib:matplotlib.gridspec.GridSpec`, \
        matplotlib grid definition
        nrows/ncols/plotnumber, see examples section
        defaults to '111', only one subplot
    rot : float
        Rotation of the source data in degrees, defaults to -450 for PPI,
        use 0 for RHI
    scale : float
        Scale of source data, defaults to -1. for PPI, use 1 for RHI
    angular_spacing : float
        Spacing of the angular grid, defaults to 10.
    radial_spacing : float
        Spacing of the radial grid, defaults to 10.
    latmin : float
        Startvalue for radial grid, defaults to 0.
    lon_cycle : float
        Angular cycle, defaults to 360.

    Returns
    -------
    cgax : matplotlib toolkit axisartist Axes object
        curvelinear Axes (r-theta-grid)
    caax : matplotlib Axes object (twin to cgax)
        Cartesian Axes (x-y-grid) for plotting cartesian data
    paax : matplotlib Axes object (parasite to cgax)
        The parasite axes object for plotting polar data
    """
    # create transformation
    # rotate
    tr_rotate = Affine2D().translate(rot, 0)
    # scale
    tr_scale = Affine2D().scale(scale * np.pi / 180, 1)
    # polar
    tr_polar = PolarAxes.PolarTransform()

    tr = tr_rotate + tr_scale + tr_polar

    # build up curvelinear grid
    extreme_finder = ah.ExtremeFinderCycle(
        360,
        360,
        lon_cycle=lon_cycle,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(latmin, np.inf),
    )
    # locator and formatter for angular annotation
    grid_locator1 = ah.LocatorDMS(lon_cycle // angular_spacing)
    tick_formatter1 = ah.FormatterDMS()

    # grid_helper for curvelinear grid
    grid_helper = GridHelperCurveLinear(
        tr,
        extreme_finder=extreme_finder,
        grid_locator1=grid_locator1,
        grid_locator2=None,
        tick_formatter1=tick_formatter1,
        tick_formatter2=None,
    )

    # try to set nice locations for radial gridlines
    grid_locator2 = grid_helper.grid_finder.grid_locator2
    grid_locator2._nbins = (radial_spacing * 2 + 1) // np.sqrt(2)

    # if there is no figure object given
    if fig is None:
        # create new figure if there is only one subplot
        if subplot == 111:
            fig = pl.figure()
        # otherwise get current figure or create new figure
        else:
            fig = pl.gcf()

    # generate Axis
    cgax = SubplotHost(fig, subplot, grid_helper=grid_helper)
    fig.add_axes(cgax)

    # get twin axis for cartesian grid
    caax = cgax.twin()
    # move axis annotation from right to left and top to bottom for
    # cartesian axis
    caax.toggle_axisline()

    # make right and top axis visible and show ticklabels (curvelinear axis)
    cgax.axis["top", "right"].set_visible(True)
    cgax.axis["top", "right"].major_ticklabels.set_visible(True)

    # make ticklabels of left and bottom axis invisible (curvelinear axis)
    cgax.axis["left", "bottom"].major_ticklabels.set_visible(False)

    # and also set tickmarklength to zero for better presentation
    # (curvelinear axis)
    cgax.axis["top", "right", "left", "bottom"].major_ticks.set_ticksize(0)

    # show theta (angles) on top and right axis
    cgax.axis["top"].get_helper().nth_coord_ticks = 0
    cgax.axis["right"].get_helper().nth_coord_ticks = 0

    # generate and add parasite axes with given transform
    paax = ParasiteAxesAuxTrans(cgax, tr, "equal")
    # note that paax.transData == tr + cgax.transData
    # Anything you draw in paax will match the ticks and grids of cgax.
    cgax.parasites.append(paax)

    return cgax, caax, paax
Ejemplo n.º 19
0
    def __init__(self, refstd, fig=None, rect=111, label='_'):
        """Set up Taylor diagram axes, i.e. single quadrant polar
        plot, using mpl_toolkits.axisartist.floating_axes. refstd is
        the reference standard deviation to be compared to.
        """

        from matplotlib.projections import PolarAxes
        import mpl_toolkits.axisartist.floating_axes as FA
        import mpl_toolkits.axisartist.grid_finder as GF

        self.refstd = refstd  # Reference standard deviation

        tr = PolarAxes.PolarTransform()

        # Correlation labels
        rlocs = NP.concatenate((NP.arange(10) / 10., [0.95, 0.99]))
        tlocs = NP.arccos(rlocs)  # Conversion to polar angles
        gl1 = GF.FixedLocator(tlocs)  # Positions
        tf1 = GF.DictFormatter(dict(zip(tlocs, map(str, rlocs))))

        # Standard deviation axis extent
        self.smin = 0
        self.smax = 1.4 * self.refstd

        ghelper = FA.GridHelperCurveLinear(
            tr,
            extremes=(
                0,
                NP.pi / 2,  # 1st quadrant
                self.smin,
                self.smax),
            grid_locator1=gl1,
            tick_formatter1=tf1,
        )

        if fig is None:
            fig = PLT.figure()

        #ax = FA.FloatingSubplot(fig, rect, grid_helper=ghelper)
        # for plot number > 9
        ax = FA.FloatingSubplot(fig, rect[0], rect[1], rect[2], \
                grid_helper=ghelper)
        fig.add_subplot(ax)

        # Adjust axes
        ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
        ax.axis["top"].toggle(ticklabels=True, label=True)
        ax.axis["top"].major_ticklabels.set_axis_direction("top")
        ax.axis["top"].label.set_axis_direction("top")
        ax.axis["top"].label.set_text("Correlation")

        ax.axis["left"].set_axis_direction("bottom")  # "X axis"
        ax.axis["left"].label.set_text("Standard deviation")

        ax.axis["right"].set_axis_direction("top")  # "Y axis"
        ax.axis["right"].toggle(ticklabels=True)
        ax.axis["right"].major_ticklabels.set_axis_direction("left")

        ax.axis["bottom"].set_visible(False)  # Useless

        # Contours along standard deviations
        ax.grid(False)

        self._ax = ax  # Graphical axes
        self.ax = ax.get_aux_axes(tr)  # Polar coordinates

        # Add reference point and stddev contour
        print "Reference std:", self.refstd
        l, = self.ax.plot([0], self.refstd, 'k*', ls='', ms=10, label=label)
        # ms is the marker size
        t = NP.linspace(0, NP.pi / 2)
        r = NP.zeros_like(t) + self.refstd
        self.ax.plot(t, r, 'k--', label='_')

        # Collect sample points for latter use (e.g. legend)
        self.samplePoints = [l]
Ejemplo n.º 20
0
def curvelinear_plot(rayon_max=1000):
    """Fonction pour créer un repère cartésien avec en décoration les coordonnées polaire pour mieux repérer les angles
    Cette fonction est basée sur un exemple matplotlib : see demo_curvelinear_grid.py for details

    Args:
        rayon_max (float, optional): Rayon amximal du plot dans lequel afficher le robot. Defaults to 1000.

    Returns:
        matplotlib.fig, matplotlib.ax : figure et axe matplotlib dans lequel on fait l'affichage
    """
    tr_rotate = Affine2D().translate(90, 0)
    tr_scale = Affine2D().scale(np.pi / 180., 1.)
    tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()

    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(-np.inf, np.inf),
    )

    grid_locator1 = angle_helper.LocatorDMS(8)
    # tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(
        tr,
        extreme_finder=extreme_finder,
        grid_locator1=grid_locator1,
        # tick_formatter1=tick_formatter1
    )

    fig = plt.figure()
    ax1 = fig.add_subplot(axes_class=HostAxes, grid_helper=grid_helper)

    # Now creates floating axis
    # ax1.scatter(5, 5)

    # floating axis whose first coordinate (theta) is fixed at 60
    ax1.axis["ax"] = axis = ax1.new_floating_axis(0, 0)
    axis.set_axis_direction("top")
    axis.major_ticklabels.set_axis_direction("left")
    ax1.axis["ax1"] = axis = ax1.new_floating_axis(0, -90)
    axis.set_axis_direction("left")
    axis.major_ticklabels.set_axis_direction("top")
    # axis.label.set_text(r"$\theta = 60^{\circ}$")
    # axis.label.set_visible(True)

    # floating axis whose second coordinate (r) is fixed at 6
    ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 150)
    axis.label.set_pad(10)

    # axis.label.set_text(r"$r = 1$")

    ax1.set_aspect(1.)
    ax1.set_xlim(-rayon_max, rayon_max)
    ax1.set_ylim(-rayon_max, rayon_max)

    ax1.grid(True)
    return fig, ax1
Ejemplo n.º 21
0
def taylor_normalized(scores, colors, angle_lim):

    import mpl_toolkits.axisartist.floating_axes as floating_axes
    from matplotlib.projections import PolarAxes
    from mpl_toolkits.axisartist.grid_finder import (FixedLocator,
                                                     DictFormatter)

    fig = plt.figure()
    tr = PolarAxes.PolarTransform()

    min_corr = np.round(np.cos(angle_lim), 1)
    CCgrid = np.concatenate(
        (np.arange(min_corr * 10, 10, 2.0) / 10., [0.9, 0.95, 0.99]))
    CCpolar = np.arccos(CCgrid)
    gf = FixedLocator(CCpolar)
    tf = DictFormatter(dict(zip(CCpolar, map(str, CCgrid))))

    STDgrid = np.arange(0, 2.0, .5)
    gfs = FixedLocator(STDgrid)
    tfs = DictFormatter(dict(zip(STDgrid, map(str, STDgrid))))

    ra0, ra1 = 0, angle_lim
    cz0, cz1 = 0, 2
    grid_helper = floating_axes.GridHelperCurveLinear(tr,
                                                      extremes=(ra0, ra1, cz0,
                                                                cz1),
                                                      grid_locator1=gf,
                                                      tick_formatter1=tf,
                                                      grid_locator2=gfs,
                                                      tick_formatter2=tfs)

    ax1 = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper)
    fig.add_subplot(ax1)

    ax1.axis["top"].set_axis_direction("bottom")
    ax1.axis["top"].toggle(ticklabels=True, label=True)
    ax1.axis["top"].major_ticklabels.set_axis_direction("top")
    ax1.axis["top"].label.set_axis_direction("top")
    ax1.axis["top"].label.set_text("Correlation")
    ax1.axis['top'].label.set_size(14)

    ax1.axis["left"].set_axis_direction("bottom")
    ax1.axis["left"].label.set_text("Normalized Standard Deviation")
    ax1.axis['left'].label.set_size(14)

    ax1.axis["right"].set_axis_direction("top")
    ax1.axis["right"].toggle(ticklabels=True)
    ax1.axis["right"].major_ticklabels.set_axis_direction("left")

    ax1.axis["bottom"].set_visible(False)
    ax1 = ax1.get_aux_axes(tr)

    plt.grid(linestyle=':', alpha=0.5)

    for i, r in enumerate(scores.iterrows()):
        theta = np.arccos(r[1].CORRELATION)
        rr = r[1].MSTD / r[1].OSTD
        print(rr)
        print(theta)

        ax1.plot(theta, rr, 'o', label=r[0], color=colors[i])

    ax1.plot(0, 1, 'o', label='Obs')
    plt.legend(loc='upper right', bbox_to_anchor=[1.3, 1.15])
    plt.show()

    rs, ts = np.meshgrid(np.linspace(0, 2), np.linspace(0, angle_lim))
    rms = np.sqrt(1 + rs**2 - 2 * rs * np.cos(ts))

    ax1.contour(ts, rs, rms, 3, colors='0.5')
    #contours = ax1.contour(ts, rs, rms,3,colors='0.5')
    #plt.clabel(contours, inline=1, fontsize=10)
    plt.grid(linestyle=':', alpha=0.5)

    for i, r in enumerate(scores.iterrows()):
        crmse = np.sqrt(1 + (r[1].MSTD/scores.OSTD[i])**2 \
                   - 2*(r[1].MSTD/scores.OSTD[i])*r[1].CORRELATION)
        print(crmse)
        c1 = ax1.contour(ts, rs, rms, [crmse], colors=colors[i])
        plt.clabel(c1, inline=1, fontsize=10, fmt='%1.2f')
Ejemplo n.º 22
0
def plot_polar_heatmap(data,
                       name,
                       interp_factor=5.,
                       color_limits=False,
                       hide_colorbar=False,
                       vmin=None,
                       vmax=None,
                       log_scale=True,
                       dpi=200,
                       output_dir=None):
    """Plots the polar heatmap describing azimuth and latitude / elevation components.

    Plots the polar heatmap where each cell of the heatmap corresponds to
    the specific element of the array provided by `gather_polar_errors`
    function.

    Parameters
    ----------
    data : 2D array
        Indicates the array containing the sum of angular errors within the
        specified angular ranges. It is usually provided by `gather_polar_errors`
        function.

    name : str
        Indicates the name of the output png file.

    interp_factor : float
        Indicates the interpolation factor of the heatmap.

    color_limits : boolean
        Specifies if the determined intensity limits should be returned.

    hide_colorbar : boolean
        Specifies if the colorbar should be hidden.

    vmin : float
        Indicates the minimum value of the colorbar.

    vmax : float
        Indicates the maximum value of the colorbar.

    log_scale : float
        Specifies if the heatmap sould be in the logarithmic scale.

    dpi : integer
        Indicates the DPI of the output image.

    output_dir : str
        Indicates the path to the output folder where the image will be stored.
    """
    th0, th1 = 0., 180.
    r0, r1 = 0, 90
    thlabel, rlabel = 'Azimuth', 'Elevation'

    tr_scale = Affine2D().scale(np.pi / 180., 1.)
    tr = tr_scale + PolarAxes.PolarTransform()

    lat_ticks = [(.0 * 90., '0$^{\circ}$'), (.33 * 90., '30$^{\circ}$'),
                 (.66 * 90., '60$^{\circ}$'), (1. * 90., '90$^{\circ}$')]
    r_grid_locator = FixedLocator([v for v, s in lat_ticks])
    r_grid_formatter = DictFormatter(dict(lat_ticks))

    angle_ticks = [(0 * 180., '90$^{\circ}$'), (.25 * 180., '45$^{\circ}$'),
                   (.5 * 180., '0$^{\circ}$'), (.75 * 180., '-45$^{\circ}$'),
                   (1. * 180., '-90$^{\circ}$')]
    theta_grid_locator = FixedLocator([v for v, s in angle_ticks])
    theta_tick_formatter = DictFormatter(dict(angle_ticks))

    grid_helper = GridHelperCurveLinear(tr,
                                        extremes=(th0, th1, r0, r1),
                                        grid_locator1=theta_grid_locator,
                                        grid_locator2=r_grid_locator,
                                        tick_formatter1=theta_tick_formatter,
                                        tick_formatter2=r_grid_formatter)

    fig = plt.figure()
    ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper)
    fig.add_subplot(ax)
    ax.set_facecolor('white')

    ax.axis["bottom"].set_visible(False)
    ax.axis["top"].toggle(ticklabels=True, label=True)
    ax.axis["top"].set_axis_direction("bottom")
    ax.axis["top"].major_ticklabels.set_axis_direction("top")
    ax.axis["top"].label.set_axis_direction("top")

    ax.axis["left"].set_axis_direction("bottom")
    ax.axis["right"].set_axis_direction("top")

    ax.axis["top"].label.set_text(thlabel)
    ax.axis["left"].label.set_text(rlabel)

    aux_ax = ax.get_aux_axes(tr)
    aux_ax.patch = ax.patch
    ax.patch.zorder = 0.9

    rad = np.linspace(0, 90, data.shape[1])
    azm = np.linspace(0, 180, data.shape[0])

    f = interpolate.interp2d(rad,
                             azm,
                             data,
                             kind='linear',
                             bounds_error=True,
                             fill_value=0)

    new_rad = np.linspace(0, 90, 180 * interp_factor)
    new_azm = np.linspace(0, 180, 360 * interp_factor)
    new_data_angle_dist = f(new_rad, new_azm)
    new_r, new_th = np.meshgrid(new_rad, new_azm)
    new_data_angle_dist += 1.

    if log_scale:
        data_mesh = aux_ax.pcolormesh(
            new_th,
            new_r,
            new_data_angle_dist,
            cmap='jet',
            norm=colors.LogNorm(
                vmin=1. if vmin is None else vmin,
                vmax=new_data_angle_dist.max() if vmax is None else vmax))
    else:
        data_mesh = aux_ax.pcolormesh(new_th,
                                      new_r,
                                      new_data_angle_dist,
                                      cmap='jet',
                                      vmin=vmin,
                                      vmax=vmax)

    cbar = plt.colorbar(data_mesh,
                        orientation='vertical',
                        shrink=.88,
                        pad=.1,
                        aspect=15)
    cbar.ax.set_ylabel('Absolute error, [deg.]')

    if hide_colorbar:
        cbar.remove()

    ax.grid(False)

    plt.show()

    if output_dir is not None:
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        fig.savefig(os.path.join(output_dir, f'{name}_chart.png'),
                    transparent=False,
                    bbox_inches='tight',
                    pad_inches=0.1,
                    dpi=dpi)

    if color_limits:
        return 1., new_data_angle_dist.max()
Ejemplo n.º 23
0
Archivo: Post.py Proyecto: Espipi/ILAMB
def TaylorDiagram(stddev,corrcoef,refstd,fig,colors,normalize=True):
    """Plot a Taylor diagram.

    This is adapted from the code by Yannick Copin found here:

    https://gist.github.com/ycopin/3342888

    Parameters
    ----------
    stddev : numpy.ndarray
        an array of standard deviations
    corrcoeff : numpy.ndarray
        an array of correlation coefficients
    refstd : float
        the reference standard deviation
    fig : matplotlib figure
        the matplotlib figure
    colors : array
        an array of colors for each element of the input arrays
    normalize : bool, optional
        disable to skip normalization of the standard deviation

    """
    from matplotlib.projections import PolarAxes
    import mpl_toolkits.axisartist.floating_axes as FA
    import mpl_toolkits.axisartist.grid_finder as GF

    # define transform
    tr = PolarAxes.PolarTransform()

    # correlation labels
    rlocs = np.concatenate((np.arange(10)/10.,[0.95,0.99]))
    tlocs = np.arccos(rlocs)
    gl1   = GF.FixedLocator(tlocs)
    tf1   = GF.DictFormatter(dict(zip(tlocs,map(str,rlocs))))

    # standard deviation axis extent
    if normalize:
        stddev = stddev/refstd
        refstd = 1.
    smin = 0
    smax = max(2.0,1.1*stddev.max())

    # add the curvilinear grid
    ghelper = FA.GridHelperCurveLinear(tr,
                                       extremes=(0,np.pi/2,smin,smax),
                                       grid_locator1=gl1,
                                       tick_formatter1=tf1)
    ax = FA.FloatingSubplot(fig, 111, grid_helper=ghelper)
    fig.add_subplot(ax)

    # adjust axes
    ax.axis["top"].set_axis_direction("bottom")
    ax.axis["top"].toggle(ticklabels=True,label=True)
    ax.axis["top"].major_ticklabels.set_axis_direction("top")
    ax.axis["top"].label.set_axis_direction("top")
    ax.axis["top"].label.set_text("Correlation")
    ax.axis["left"].set_axis_direction("bottom")
    if normalize:
        ax.axis["left"].label.set_text("Normalized standard deviation")
    else:
        ax.axis["left"].label.set_text("Standard deviation")
    ax.axis["right"].set_axis_direction("top")
    ax.axis["right"].toggle(ticklabels=True)
    ax.axis["right"].major_ticklabels.set_axis_direction("left")
    ax.axis["bottom"].set_visible(False)
    ax.grid(True)

    ax = ax.get_aux_axes(tr)
    # Plot data
    corrcoef = corrcoef.clip(-1,1)
    for i in range(len(corrcoef)):
        ax.plot(np.arccos(corrcoef[i]),stddev[i],'o',color=colors[i],mew=0,ms=8)

    # Add reference point and stddev contour
    l, = ax.plot([0],refstd,'k*',ms=12,mew=0)
    t = np.linspace(0, np.pi/2)
    r = np.zeros_like(t) + refstd
    ax.plot(t,r, 'k--')

    # centralized rms contours
    rs,ts = np.meshgrid(np.linspace(smin,smax),
                        np.linspace(0,np.pi/2))
    rms = np.sqrt(refstd**2 + rs**2 - 2*refstd*rs*np.cos(ts))
    contours = ax.contour(ts,rs,rms,5,colors='k',alpha=0.4)
    ax.clabel(contours,fmt='%1.1f')


    return ax
Ejemplo n.º 24
0
def plotGsrResidue(theta,
                   phi,
                   residue,
                   optTheta,
                   optPhi,
                   mvabTheta=None,
                   mvabPhi=None,
                   mvubTheta=None,
                   mvubPhi=None):
    fig = figure()
    fig.clf()

    # some matplotlib setup stuff which I don't fully understand but it works
    tr = Affine2D().scale(pi / 180., 1.) + PolarAxes.PolarTransform()
    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, inf),
    )
    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()
    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)
    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
    fig.add_subplot(ax1)
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    # draw the filled contoured map in polar coordinates
    ax1.contour(transpose(mat(theta)) * mat(cos(phi * pi / 180)),
                transpose(mat(theta)) * mat(sin(phi * pi / 180)),
                1 / transpose(reshape(residue, (phi.size, -1))),
                100,
                lw=0.1)
    cc = ax1.contourf(
        transpose(mat(theta)) * mat(cos(phi * pi / 180)),
        transpose(mat(theta)) * mat(sin(phi * pi / 180)),
        1 / transpose(reshape(residue, (phi.size, -1))), 100)
    # remove gaps between the contour lines
    for c in cc.collections:
        c.set_antialiased(False)

    # show the MVAB direction
    if mvabTheta is not None and mvabPhi is not None:
        ax1.plot(mvabTheta * cos(mvabPhi * pi / 180),
                 mvabTheta * sin(mvabPhi * pi / 180),
                 'sk',
                 markersize=8)

    # show the MVUB direction
    if mvubTheta is not None and mvubPhi is not None:
        ax1.plot(mvubTheta * cos(mvubPhi * pi / 180),
                 mvubTheta * sin(mvubPhi * pi / 180),
                 'dk',
                 markersize=8)

    # show the optimal direction
    ax1.plot(optTheta * cos(optPhi * pi / 180),
             optTheta * sin(optPhi * pi / 180),
             '.k',
             markersize=15)

    # aspect and initial axes limits
    ax1.set_aspect(1.)
    ax1.set_xlim(-90, 90)
    ax1.set_ylim(-90, 90)

    # add grid
    ax1.grid(True)

    # add colobar
    cb = colorbar(cc, pad=0.07)
    cb.locator = MaxNLocator(14)
    cb.update_ticks()
    cb.set_label(r"$1/\tilde{\mathcal{R}}$")

    # save
    if toSave:
        savefig(resultsDir + '/eps/gsr_ResidualMap.eps', format='eps')
        savefig(resultsDir + '/png/gsr_ResidualMap.png', format='png')
Ejemplo n.º 25
0
    def curvelinear_test2(fig, gs=None, xcenter=0.0, ycenter=17.3, xwidth=1.5, ywidth=1.5,
            rot_angle=0.0, xlabel=xlabel, ylabel=ylabel, xgrid_density=8, ygrid_density=5):
        """
        polar projection, but in a rectangular box.
        """

        tr = Affine2D().translate(0,90)
        tr += Affine2D().scale(np.pi/180., 1.)
        tr += PolarAxes.PolarTransform()

        tr += Affine2D().rotate(rot_angle)  # This rotates the grid

        extreme_finder = angle_helper.ExtremeFinderCycle(10, 60,
                                                        lon_cycle = 360,
                                                        lat_cycle = None,
                                                        lon_minmax = None,
                                                        lat_minmax = (-90, np.inf),
                                                        )

        grid_locator1 = angle_helper.LocatorHMS(xgrid_density) #changes theta gridline count
        tick_formatter1 = angle_helper.FormatterHMS()
        grid_locator2 = angle_helper.LocatorDMS(ygrid_density) #changes theta gridline count
        tick_formatter2 = angle_helper.FormatterDMS()


        grid_helper = GridHelperCurveLinear(tr,
                                            extreme_finder=extreme_finder,
                                            grid_locator1=grid_locator1,
                                            grid_locator2=grid_locator2,
                                            tick_formatter1=tick_formatter1,
                                            tick_formatter2=tick_formatter2
                                            )

        # ax1 = SubplotHost(fig, rect, grid_helper=grid_helper)
        if gs is None:
            ax1 = SubplotHost(fig, 111, grid_helper=grid_helper)
        else:
            ax1 = SubplotHost(fig, gs, grid_helper=grid_helper)



        # make ticklabels of right and top axis visible.
        ax1.axis["right"].major_ticklabels.set_visible(False)
        ax1.axis["top"].major_ticklabels.set_visible(False)
        ax1.axis["bottom"].major_ticklabels.set_visible(True) #Turn off?

        # let right and bottom axis show ticklabels for 1st coordinate (angle)
        ax1.axis["right"].get_helper().nth_coord_ticks=0
        ax1.axis["bottom"].get_helper().nth_coord_ticks=0


        fig.add_subplot(ax1)

        grid_helper = ax1.get_grid_helper()

        # These move the grid
        ax1.set_xlim(xcenter-xwidth, xcenter+xwidth) # moves the origin left-right in ax1
        ax1.set_ylim(ycenter-ywidth, ycenter+ywidth) # moves the origin up-down


        if xlabel is not None: ax1.set_xlabel(xlabel)
        if ylabel is not None: ax1.set_ylabel(ylabel)
        ax1.grid(True, linestyle='-')


        return ax1,tr
Ejemplo n.º 26
0
    def __init__(self,
                 refstd=1,
                 fig=None,
                 rect=111,
                 label='REF',
                 std_range=(0, 1.65),
                 std_level=np.arange(0, 1.51, 0.25)):
        """Create base Taylor Diagram.

        Parameters
        ----------
        refstd : float, optional
            reference standard deviation

        fig : matplotlib.figure.Figure, optional
            Optional input figure. Default is None

        rect : int, optional
            Optional subplot definition

        label : string, optional
            Optional reference label string indentifier

        std_range : Tuple, optional
            Optional stddev axis extent

        std_level : list, optional
            Optional list of tick locations for stddev axis
        """

        from matplotlib.projections import PolarAxes
        import mpl_toolkits.axisartist.floating_axes as fa
        import mpl_toolkits.axisartist.grid_finder as gf

        # Pull and set optional constructor variables
        # Set figure
        self.fig = fig
        if fig is None:
            self.fig = plt.figure(figsize=(8, 8))

        # Reference standard deviation
        self.refstd = refstd

        # Standard deviation axis extent (in units of reference stddev)
        self.smin = std_range[0]
        self.smax = std_range[1]

        # Set polar transform
        tr = PolarAxes.PolarTransform()

        # Set correlation labels
        rlocs = np.concatenate((np.arange(10) / 10., [0.95, 0.99, 1]))
        tlocs = np.arccos(rlocs)  # Conversion to polar angles
        gl1 = gf.FixedLocator(tlocs)  # Positions
        tf1 = gf.DictFormatter(dict(list(zip(tlocs, list(map(str, rlocs))))))

        # Set standard deviation labels
        gl2 = gf.FixedLocator(std_level)

        # format each label with 2 decimal places
        format_string = list(map(lambda x: "{0:0.2f}".format(x), std_level))
        index = np.where(std_level == self.refstd)[0][0]
        format_string[index] = label
        tf2 = gf.DictFormatter(dict(list(zip(std_level, format_string))))

        # Use customized GridHelperCurveLinear to define curved axis
        ghelper = fa.GridHelperCurveLinear(
            tr,
            extremes=(
                0,
                np.pi / 2,  # 1st quadrant only
                self.smin,
                self.smax),
            grid_locator1=gl1,
            tick_formatter1=tf1,
            grid_locator2=gl2,
            tick_formatter2=tf2)

        # Create graphical axes
        ax = fa.FloatingSubplot(self.fig, rect, grid_helper=ghelper)
        self.fig.add_subplot(ax)

        # Adjust axes for Correlation
        ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
        ax.axis["top"].toggle(ticklabels=True, label=True)
        ax.axis["top"].major_ticklabels.set_axis_direction("right")
        ax.axis["top"].label.set_axis_direction("top")
        ax.axis["top"].label.set_text("Correlation")

        # Standard deviation ("X axis")
        ax.axis["left"].set_axis_direction("bottom")

        # Standard deviation ("Y axis")
        ax.axis["right"].set_axis_direction("top")
        ax.axis["right"].toggle(ticklabels=True, label=True)
        ax.axis["right"].major_ticklabels.set_axis_direction("left")
        ax.axis["right"].label.set_text("Standard deviation (Normalized)")

        # Set font sizes, tick sizes, and padding
        ax.axis['top', 'right'].label.set_fontsize(18)
        ax.axis['top', 'right', 'left'].major_ticklabels.set_fontsize(16)
        ax.axis['top', 'right', 'left'].major_ticks.set_ticksize(10)
        ax.axis['top', 'right', 'left'].major_ticklabels.set_pad(8)
        ax.axis['top', 'right'].label.set_pad(6)

        # Bottom axis is not needed
        ax.axis["bottom"].set_visible(False)

        self._ax = ax  # Graphical axes
        self.ax = ax.get_aux_axes(tr)  # Polar coordinates

        # Add reference point stddev contour
        t = np.linspace(0, np.pi / 2)
        r = np.zeros_like(t) + self.refstd
        h, = self.ax.plot(t,
                          r,
                          linewidth=1,
                          linestyle=(0, (9, 5)),
                          color='black',
                          zorder=1)

        # Set aspect ratio
        self.ax.set_aspect('equal')

        # Store the reference line
        self.referenceLine = h

        # Collect sample points for latter use (e.g. legend)
        self.modelMarkerSet = []

        # Set number for models outside axes
        self.modelOutside = -1
Ejemplo n.º 27
0
def curvelinear_test2(fig):
    """
    polar projection, but in a rectangular box.
    """

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )

    grid_locator1 = angle_helper.LocatorDMS(12)
    # Find a grid values appropriate for the coordinate (degree,
    # minute, second).

    tick_formatter1 = angle_helper.FormatterDMS()
    # And also uses an appropriate formatter.  Note that,the
    # acceptable Locator and Formatter class is a bit different than
    # that of mpl's, and you cannot directly use mpl's Locator and
    # Formatter here (but may be possible in the future).

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper)

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    fig.add_subplot(ax1)

    # A parasite axes with given transform
    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    # note that ax2.transData == tr + ax1.transData
    # Anthing you draw in ax2 will match the ticks and grids of ax1.
    ax1.parasites.append(ax2)
    intp = cbook.simple_linear_interpolation
    ax2.plot(intp(np.array([0, 30]), 50),
             intp(np.array([10., 10.]), 50),
             linewidth=2.0)

    ax1.set_aspect(1.)
    ax1.set_xlim(-5, 12)
    ax1.set_ylim(-5, 10)

    ax1.grid(True, zorder=0)
Ejemplo n.º 28
0
    def __init__(self,
                 refstd,
                 fig=None,
                 rect=111,
                 label='_',
                 srange=(0, 1.5),
                 extend=False):
        """
        Set up Taylor diagram axes, i.e. single quadrant polar
        plot, using `mpl_toolkits.axisartist.floating_axes`.
        Parameters:
        * refstd: reference standard deviation to be compared to
        * fig: input Figure or None
        * rect: subplot definition
        * label: reference label
        * srange: stddev axis extension, in units of *refstd*
        * extend: extend diagram to negative correlations
        """

        from matplotlib.projections import PolarAxes
        import mpl_toolkits.axisartist.floating_axes as FA
        import mpl_toolkits.axisartist.grid_finder as GF

        self.refstd = refstd  # Reference standard deviation

        tr = PolarAxes.PolarTransform()

        # Correlation labels
        rlocs = NP.array([0, 0.2, 0.4, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1])
        if extend:
            # Diagram extended to negative correlations
            self.tmax = NP.pi
            rlocs = NP.concatenate((-rlocs[:0:-1], rlocs))
        else:
            # Diagram limited to positive correlations
            self.tmax = NP.pi / 2
        tlocs = NP.arccos(rlocs)  # Conversion to polar angles
        gl1 = GF.FixedLocator(tlocs)  # Positions
        tf1 = GF.DictFormatter(dict(zip(tlocs, map(str, rlocs))))

        # Standard deviation axis extent (in units of reference stddev)
        self.smin = srange[0] * self.refstd
        self.smax = srange[1] * self.refstd

        ghelper = FA.GridHelperCurveLinear(tr,
                                           extremes=(0, self.tmax, self.smin,
                                                     self.smax),
                                           grid_locator1=gl1,
                                           tick_formatter1=tf1)

        if fig is None:
            fig = PLT.figure()

        ax = FA.FloatingSubplot(fig, rect, grid_helper=ghelper)
        fig.add_subplot(ax)

        # Adjust axes
        ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
        ax.axis["top"].toggle(ticklabels=True, label=True)
        ax.axis["top"].major_ticklabels.set_axis_direction("top")
        ax.axis["top"].major_ticklabels.set_fontsize(15)
        ax.axis["top"].label.set_axis_direction("top")
        ax.axis["top"].label.set_text("Standardized gauge density")
        ax.axis["top"].label.set_fontsize(15)

        ax.axis["left"].set_axis_direction("bottom")  # "X axis"
        ax.axis["left"].label.set_text("RMSD (mm/h)")
        ax.axis["left"].label.set_fontsize(15)
        ax.axis["left"].major_ticklabels.set_fontsize(15)

        ax.axis["right"].set_axis_direction("top")  # "Y-axis"
        ax.axis["right"].toggle(ticklabels=True)
        ax.axis["right"].major_ticklabels.set_axis_direction(
            "bottom" if extend else "left")

        ax.axis["right"].major_ticklabels.set_fontsize(15)
        ax.axis["right"].label.set_text("RMSD (mm/h)")
        ax.axis["right"].label.set_fontsize(15)

        if self.smin:
            ax.axis["bottom"].toggle(ticklabels=False, label=False)
        else:
            ax.axis["bottom"].set_visible(False)  # Unused

        self._ax = ax  # Graphical axes
        self.ax = ax.get_aux_axes(tr)  # Polar coordinates

        # Add reference point and stddev contour
        l, = self.ax.plot([0], self.refstd, '.', ls='', ms=10, label=label)
        t = NP.linspace(0, self.tmax)
        r = NP.zeros_like(t) + self.refstd
        self.ax.plot(t, r, 'k--', label='_')

        # Collect sample points for latter use (e.g. legend)
        self.samplePoints = [l]
def curvelinear_test3(fig):
    """
    polar projection, but in a rectangular box.
    """
    global ax1, axis
    import numpy as np
    from . import angle_helper
    from matplotlib.projections import PolarAxes

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    grid_locator1 = angle_helper.LocatorDMS(15)
    # Find a grid values appropriate for the coordinate (degree,
    # minute, second).

    tick_formatter1 = angle_helper.FormatterDMS()
    # And also uses an appropriate formatter.  Note that,the
    # acceptable Locator and Formatter class is a bit different than
    # that of mpl's, and you cannot directly use mpl's Locator and
    # Formatter here (but may be possible in the future).

    from .grid_finder import FixedLocator
    grid_locator2 = FixedLocator([2, 4, 6, 8, 10])

    grid_helper = GridHelperCurveLinear(
        tr,
        extremes=(0, 360, 10, 3),
        grid_locator1=grid_locator1,
        grid_locator2=grid_locator2,
        tick_formatter1=tick_formatter1,
        tick_formatter2=None,
    )

    ax1 = FloatingSubplot(fig, 111, grid_helper=grid_helper)

    #ax1.axis["top"].set_visible(False)
    #ax1.axis["bottom"].major_ticklabels.set_axis_direction("top")

    fig.add_subplot(ax1)

    #ax1.grid(True)

    r_scale = 10.
    tr2 = Affine2D().scale(1., 1. / r_scale) + tr
    grid_locator2 = FixedLocator([30, 60, 90])
    grid_helper2 = GridHelperCurveLinear(
        tr2,
        extremes=(0, 360, 10. * r_scale, 3. * r_scale),
        grid_locator2=grid_locator2,
    )

    ax1.axis["right"] = axis = grid_helper2.new_fixed_axis("right", axes=ax1)

    ax1.axis["left"].label.set_text("Test 1")
    ax1.axis["right"].label.set_text("Test 2")

    for an in ["left", "right"]:
        ax1.axis[an].set_visible(False)

    #grid_helper2 = ax1.get_grid_helper()
    ax1.axis["z"] = axis = grid_helper.new_floating_axis(
        1, 7, axes=ax1, axis_direction="bottom")
    axis.toggle(all=True, label=True)
    #axis.label.set_axis_direction("top")
    axis.label.set_text("z = ?")
    axis.label.set_visible(True)
    axis.line.set_color("0.5")
    #axis.label.set_visible(True)

    ax2 = ax1.get_aux_axes(tr)

    xx, yy = [67, 90, 75, 30], [2, 5, 8, 4]
    ax2.scatter(xx, yy)
    l, = ax2.plot(xx, yy, "k-")
    l.set_clip_path(ax1.patch)
def test_axis_direction():
    fig = plt.figure(figsize=(5, 5))

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).

    # 20, 20 : number of sampling points along x, y direction
    extreme_finder = angle_helper.ExtremeFinderCycle(
        20,
        20,
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )

    grid_locator1 = angle_helper.LocatorDMS(12)
    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    for axis in ax1.axis.values():
        axis.set_visible(False)

    fig.add_subplot(ax1)

    ax1.axis["lat1"] = axis = grid_helper.new_floating_axis(
        0, 130, axes=ax1, axis_direction="left")
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper()._extremes = 0.001, 10

    ax1.axis["lat2"] = axis = grid_helper.new_floating_axis(
        0, 50, axes=ax1, axis_direction="right")
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper()._extremes = 0.001, 10

    ax1.axis["lon"] = axis = grid_helper.new_floating_axis(
        1, 10, axes=ax1, axis_direction="bottom")
    axis.label.set_text("Test 2")
    axis.get_helper()._extremes = 50, 130
    axis.major_ticklabels.set_axis_direction("top")
    axis.label.set_axis_direction("top")

    grid_helper.grid_finder.grid_locator1.den = 5
    grid_helper.grid_finder.grid_locator2._nbins = 5

    ax1.set_aspect(1.)
    ax1.set_xlim(-8, 8)
    ax1.set_ylim(-4, 12)

    ax1.grid(True)