Esempio n. 1
0
def curvelinear_test1(fig):
    """Grid for custom transform."""

    def tr(x, y):
        sgn = np.sign(x)
        x, y = np.abs(np.asarray(x)), np.asarray(y)
        return sgn*x**.5, y

    def inv_tr(x, y):
        sgn = np.sign(x)
        x, y = np.asarray(x), np.asarray(y)
        return sgn*x**2, y

    grid_helper = GridHelperCurveLinear(
        (tr, inv_tr),
        extreme_finder=ExtremeFinderSimple(20, 20),
        # better tick density
        grid_locator1=MaxNLocator(nbins=6), grid_locator2=MaxNLocator(nbins=6))

    ax1 = fig.add_subplot(axes_class=Axes, grid_helper=grid_helper)
    # ax1 will have a ticks and gridlines defined by the given
    # transform (+ transData of the Axes). Note that the transform of the Axes
    # itself (i.e., transData) is not affected by the given transform.

    ax1.imshow(np.arange(25).reshape(5, 5),
               vmax=50, cmap=plt.cm.gray_r, origin="lower")
Esempio n. 2
0
def setup_earth_axes(fig, rect, theta_lim, h_lim, a_e, theta_scale):
    """
    From https://matplotlib.org/examples/axes_grid/demo_floating_axes.html
    """

    # rotate a bit for better orientation
    tr_rotate = Affine2D().translate(
        np.pi / 2 - np.mean(theta_lim) * theta_scale, 0)

    # scale degree to radians
    tr_scale = Affine2D().scale(theta_scale, 1)

    # treat heights
    tr_htrans = Affine2D().translate(0, +a_e)

    tr = tr_htrans + tr_scale + tr_rotate + PolarAxes.PolarTransform()

    grid_locator1 = MaxNLocator(5)
    grid_locator2 = MaxNLocator(5)

    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(*theta_lim, *h_lim),
        grid_locator1=grid_locator1,
        grid_locator2=grid_locator2,
        tick_formatter1=None,
        tick_formatter2=None,
    )

    ax = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)

    fig.add_subplot(ax)

    # adjust axis
    ax.axis["left"].set_axis_direction("top")
    ax.axis["left"].label.set_text("Height [m]")
    ax.axis["left"].toggle(ticklabels=True, label=True)
    ax.axis["right"].toggle(ticklabels=False, label=False)
    ax.axis["right"].set_axis_direction("right")
    ax.axis["bottom"].toggle(ticklabels=True, label=True)
    ax.axis["bottom"].set_axis_direction("bottom")
    ax.axis["bottom"].major_ticklabels.set_axis_direction("bottom")
    ax.axis["bottom"].label.set_axis_direction("bottom")
    ax.axis["bottom"].label.set_text("Distance [km]")

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

    aux_ax.patch = ax.patch  # for aux_ax to have a clip path as in ax
    ax.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 ax, aux_ax
Esempio n. 3
0
def setup_axes1(fig, rect):
    tr = Affine2D().scale(2, 1).rotate_deg(30)

    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(-0.5, 3.5, 0, 4),
        grid_locator1=MaxNLocator(nbins=4),
        grid_locator2=MaxNLocator(nbins=4))

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

    aux_ax = ax1.get_aux_axes(tr)

    return ax1, aux_ax
Esempio n. 4
0
def setup_axes2(fig, rect):
    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)

    # 创建一个ParasiteAxes
    aux_ax = ax1.get_aux_axes(tr)

    # 让aux_ax具有一个ax中的剪切路径
    aux_ax.patch = ax1.patch
    # 但这样做会有一个副作用,这个patch会被绘制两次,并且可能会被绘制于其它
    # Artist的上面,因此用降低其zorder值的方法来阻止该情况
    ax1.patch.zorder = 0.9

    return ax1, aux_ax
def setup_axes2(fig, rect):
    #mengatur locator dan formatter
    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)

    aux_ax = ax1.get_aux_axes(tr)

    aux_ax.patch = ax1.patch
    ax1.patch.zorder = 0.9
    return ax1, aux_ax
Esempio n. 6
0
    def setup_axes(fig, rect, extremes):
        """Axes for a GAMA region"""

        # rotate a bit for better orientation
        tr_rotate = Affine2D().translate(-0.5 * (extremes[0] + extremes[1]), 0)

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

        tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()

        grid_locator1 = MaxNLocator(3)

        grid_locator2 = MaxNLocator(5)

        grid_helper = floating_axes.GridHelperCurveLinear(
            tr,
            extremes=extremes,
            grid_locator1=grid_locator1,
            grid_locator2=grid_locator2)

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

        # adjust axis
        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'z')
        ax1.axis["top"].label.set_text('RA [deg]')

        # create a parasite axes whose transData in RA, z
        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 test_pretty_print_format():
    locator = MaxNLocator()
    locs, nloc, factor = locator(0, 100)

    fmt = FormatterPrettyPrint()

    assert fmt("left", None, locs) == \
        [r'$\mathdefault{%d}$' % (l, ) for l in locs]
def setup_axes3(fig, rect):
    """
    Sometimes, things like axis_direction need to be adjusted.
    """

    # rotate a bit for better orientation
    tr_rotate = Affine2D().translate(-95, 0)

    # scale degree to radians
    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)

    # Specify theta limits in degrees
    ra0, ra1 = 8. * 15, 14. * 15
    # Specify radial limits
    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 = fig.add_subplot(rect,
                          axes_class=floating_axes.FloatingAxes,
                          grid_helper=grid_helper)

    # adjust axis
    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}$")

    # 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 curvelinear_test1(fig):
    """Grid for custom transform."""
    def tr(x, y):
        sgn = np.sign(x)
        x, y = np.abs(np.asarray(x)), np.asarray(y)
        return sgn * x**.5, y

    def inv_tr(x, y):
        sgn = np.sign(x)
        x, y = np.asarray(x), np.asarray(y)
        return sgn * x**2, y

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

    grid_helper = GridHelperCurveLinear(
        (tr, inv_tr),
        extreme_finder=extreme_finder,
        # better tick density
        grid_locator1=MaxNLocator(nbins=6),
        grid_locator2=MaxNLocator(nbins=6))

    ax1 = Subplot(fig, 111, grid_helper=grid_helper)
    # ax1 will have a ticks and gridlines defined by the given
    # transform (+ transData of the Axes). Note that the transform of
    # the Axes itself (i.e., transData) is not affected by the given
    # transform.

    fig.add_subplot(ax1)

    ax1.imshow(np.arange(25).reshape(5, 5),
               vmax=50,
               cmap=plt.cm.gray_r,
               origin="lower")
Esempio n. 10
0
def setup_axes3(fig, rect):
    """
    Sometimes, things like axis_direction need to be adjusted.
    """

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

    tr = tr_scale + PolarAxes.PolarTransform()

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

    grid_locator2 = MaxNLocator(3)

    ra0, ra1 = 0, 180
    cz0, cz1 = 0, 10
    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)

    # adjust axis
    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"$P(\alpha)$")
    ax1.axis["top"].label.set_text(r"$\alpha$")

    # 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
Esempio n. 11
0
def setup_axes3(fig, rect):
    # 将坐标轴稍微旋转一下
    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)

    # 设置theta的数值范围,以度为单位
    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)

    # 调整axis
    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}$")

    # 创建ParasiteAxes,其transData在(RA, cz)空间
    aux_ax = ax1.get_aux_axes(tr)

    # 让aux_ax具有一个ax中的剪切路径,并降低其zorder值
    aux_ax.patch = ax1.patch
    ax1.patch.zorder = 0.9

    return ax1, aux_ax
Esempio n. 12
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
Esempio n. 13
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
Esempio n. 15
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
Esempio n. 16
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
Esempio n. 17
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
Esempio n. 18
0
def fractional_polar_axes(f, thlim=(0, 180), rlim=(0, 1), step=(30, 0.01),
                          thlabel=r'$\alpha$', rlabel='z', ticklabels=True):
    import matplotlib.pyplot as plt

    from matplotlib.transforms import Affine2D
    from matplotlib.projections import PolarAxes
    from mpl_toolkits.axisartist import angle_helper
    from mpl_toolkits.axisartist.grid_finder import MaxNLocator
    from mpl_toolkits.axisartist.floating_axes import GridHelperCurveLinear, FloatingSubplot
    from mpl_toolkits.axisartist.grid_finder import (FixedLocator, MaxNLocator,
                                                 DictFormatter)

    """Return polar axes that adhere to desired theta (in deg) and r limits. steps for theta
    and r are really just hints for the locators. Using negative values for rlim causes
    problems for GridHelperCurveLinear for some reason"""
    th0, th1 = thlim # deg
    r0, r1 = rlim
    thstep, rstep = step

    # scale degrees to radians:
    tr_scale = Affine2D().scale(np.pi/180., 1.)
    tr = tr_scale + PolarAxes.PolarTransform()
    theta_grid_locator = angle_helper.LocatorDMS((th1-th0) // thstep)
    r_grid_locator = MaxNLocator((r1-r0) // rstep)
    theta_tick_formatter = angle_helper.FormatterDMS()
    theta_tick_formatter = None
    theta_ticks = [(0, r"$90^{\circ}$"),
                   (30, r"$120^{\circ}$"),
                   (60, r"$150^{\circ}$"),
                   (90, r"$180^{\circ}$"),
                   (120, r"$210^{\circ}$"),
                   (150, r"$270^{\circ}$"),
                   (180, r"$0^{\circ}$")]
    theta_tick_formatter = DictFormatter(dict(theta_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=None)

    a = FloatingSubplot(f, 111, grid_helper=grid_helper)
    f.add_subplot(a)

    # adjust x axis (theta):
    a.axis["bottom"].set_visible(False)
    a.axis["top"].set_axis_direction("bottom") # tick direction
    a.axis["top"].toggle(ticklabels=ticklabels, label=bool(thlabel))
    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
    a.axis["left"].toggle(ticklabels=ticklabels, label=bool(rlabel))

    # add labels:
    a.axis["top"].label.set_text(thlabel)
    a.axis["left"].label.set_text(rlabel)

    # create a parasite axes whose transData is theta, r:
    auxa = a.get_aux_axes(tr)
    # make aux_ax to have a clip path as in a?:
    auxa.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

    # add sector lines for both dimensions:
    thticks = grid_helper.grid_info['lon_info'][0]
    rticks = grid_helper.grid_info['lat_info'][0]
    for th in thticks[1:-1]: # all but the first and last
        auxa.plot([th, th], [r0, r1], '--', c='grey', zorder=-1)
    for ri, r in enumerate(rticks):
        # plot first r line as axes border in solid black only if it isn't at r=0
        if ri == 0 and r != 0:
            ls, lw, color = 'solid', 2, 'black'
        else:
            ls, lw, color = 'dashed', 1, 'grey'
        # From http://stackoverflow.com/a/19828753/2020363
        auxa.add_artist(plt.Circle([0, 0], radius=r, ls=ls, lw=lw, color=color, fill=False,
                        transform=auxa.transData._b, zorder=-1))

    return auxa
Esempio n. 19
0
    def plot_crosssection_any(self,
                              lon1,
                              lon2,
                              lat1,
                              lat2,
                              numpoints=400,
                              whattoplot='clust',
                              title='',
                              stretch=1,
                              greatcirclepath=True,
                              lon0=180,
                              spherical=False):
        """ plot horizontal slices through an ses3d model

    plot_slice(self,depth,colormap='tomo',res='i',verbose=False)

    depth=depth in km of the slice
    colormap='tomo','mono'
    res=resolution of the map, admissible values are: c, l, i, h f

    """
        model = getattr(self, whattoplot)
        #lon=(lon1+lon2)/2.
        #- set up a map and colourmap -----------------------------------------
        fig = plt.figure()
        plt.subplot(2, 1, 1)
        m = Basemap(projection='hammer', lon_0=lon0)
        #m.drawparallels(np.arange(self.lat_min,self.lat_max,45.),labels=[0,0,0,0])#[1,0,0,1])
        #m.drawmeridians(np.arange(self.lon_min,self.lon_max,60.),labels=[0,0,0,0])#[1,0,0,1])

        coasts = m.drawcoastlines(zorder=1, color='white', linewidth=0)
        coasts_paths = coasts.get_paths()
        ipolygons = range(40)  # want Baikal, but not Tanganyika
        # 80 = Superior+Michigan+Huron, 81 = Victoria, 82 = Aral, 83 = Tanganyika,
        # 84 = Baikal, 85 = Great Bear, 86 = Great Slave, 87 = Nyasa, 88 = Erie
        # 89 = Winnipeg, 90 = Ontario
        for ipoly in ipolygons:
            r = coasts_paths[ipoly]
            # Convert into lon/lat vertices
            polygon_vertices = [(vertex[0], vertex[1])
                                for (vertex,
                                     code) in r.iter_segments(simplify=False)]
            px = [polygon_vertices[i][0] for i in range(len(polygon_vertices))]
            py = [polygon_vertices[i][1] for i in range(len(polygon_vertices))]
            m.plot(px, py, linewidth=1., zorder=3, color=[0.2, 0.2, 0.2])
        #m.drawmapboundary(fill_color=[1.0,1.0,1.0])
        #m.drawmapboundary(fill_color=[1.0,1.0,1.0])
        if lon0 == 180:
            z = (model[:, :, 0])
            #z=z.transpose([1,0,2])
            #zt,lonstmp=shiftgrid(0,z.T,self.lon)
            #lonst,lonstmp=shiftgrid(0,lons.T,lons[:,0])
            x1, y1 = np.meshgrid(self.lon, self.lat)
            x, y = m(x1.T, y1.T)
        else:
            z = (model[:, :, 0])
            zt, lonstmp = shiftgrid(0, z.T, self.lon, start=False)
            x1, y1 = np.meshgrid(self.lon, self.lat)
            print(np.shape(x1), np.shape(y1))
            x, y = m(x1.T, y1.T)
        #x=m.shiftdata(x,lon_0=lon0)    rgb =np.array(np.transpose(clustmap,(1,2,0)),dtype='float32')
        #rgb =zt.transpose([1,2,0])
        #color_tuple=rgb.reshape((rgb.shape[1]*rgb.shape[0],rgb.shape[2]),order='C')
        #mapper=np.linspace(0.,1.,rgb.shape[1]*rgb.shape[0]).reshape(rgb.shape[0],rgb.shape[1])

        #rgb_map=LinearSegmentedColormap.from_list('rgbmap',color_tuple,N=rgb.shape[1]*rgb.shape[0])

        cs = m.pcolor(x, y, z, cmap=self.rgb_map, linewidth=0, rasterized=True)
        #plt.colorbar()

        inv = geo.WGS84.Inverse(lat1, lon1, lat2, lon2)
        points = np.linspace(0, inv['s12'], numpoints)
        line = geo.WGS84.Line(lat1, lon1, inv['azi1'])
        if greatcirclepath:
            [x1, y1] = m.gcpoints(lon1, lat1, lon2, lat2, numpoints)
            m.plot(x1, y1, 'k', linewidth=3)
            m.plot(x1[0], y1[0], '.c', markersize=15, markeredgecolor='k')
            m.plot(x1[-1], y1[-1], '.m', markersize=15, markeredgecolor='k')

            dist = []
            lonsline = []
            latsline = []
            for i in range(len(points)):
                loc = line.Position(points[i])
                # dist.append(haversine((loc['lat2'],loc['lon2']),([lat1],[lon1]))/111194.)
                dist.append(loc['s12'] / 111194.)
                lonsline.append(loc['lon2'])
                latsline.append(loc['lat2'])

            lonsline = np.array(lonsline)
            latsline = np.array(latsline)

        else:
            lonsline = np.linspace(lon1, lon2, numpoints)
            latsline = np.linspace(lat1, lat2, numpoints)
            dist = haversine((lat1, lon1), (latsline, lonsline)) / 111194.

            [x1, y1] = m(lonsline, latsline)
            m.plot(x1, y1, 'k', linewidth=3)
            m.plot(x1[0], y1[0], '.c', markersize=15, markeredgecolor='k')
            m.plot(x1[-1], y1[-1], '.m', markersize=15, markeredgecolor='k')

        modeltoplot = getattr(self, 'indg6')
        idxs = []
        for i in range(len(lonsline)):
            idxs.append(
                np.argmin(
                    haversine((latsline[i], lonsline[i]),
                              (self.latg6, self.long6))))
        idxs = np.array(idxs)

        toplot = np.empty((len(lonsline), len(self.depth)))

        for d in range(len(self.depth)):
            el = np.where(self.deps == self.depth[d])
            clusttmp = np.squeeze(modeltoplot[el])
            for i in range(len(lonsline)):
                toplot[i, d] = clusttmp[idxs[i]]

            #toplot.append(np.round(scipy.ndimage.map_coordinates(model[:,:,d], np.vstack((row,col)),order=0,mode='constant')))

        toplot = np.array(toplot).T

        xx, yy = np.meshgrid(dist, self.depth)

        if spherical == False:
            ax = plt.subplot(2, 1, 2)
            minval = np.min(np.min(toplot))
            maxval = np.max(np.max(toplot))

            contours = np.round(np.linspace(-1.1, 1.1, 12), 2)
            plt.title(title)

            cs = plt.pcolor(xx,
                            yy,
                            toplot,
                            cmap=self.rgb_map,
                            vmin=0.5,
                            vmax=21.5)
            plt.plot([dist[0], dist[-1]],
                     [min(self.depth), min(self.depth)],
                     'k',
                     linewidth=8)
            plt.plot(dist[0],
                     min(self.depth),
                     '.c',
                     markersize=40,
                     markeredgecolor='k')
            plt.plot(dist[-1],
                     min(self.depth),
                     '.m',
                     markersize=40,
                     markeredgecolor='k')

            #plt.pcolor(x,y,self.dvs[:,:,layer],vmin=-0.04, vmax=0.04,cmap=plt.cm.get_cmap('jet_r'))

            plt.ylim([min(self.depth), 2890])
            plt.gca().invert_yaxis()
            plt.xlim([min(dist), max(dist)])
            ax.set_aspect(.015 / stretch)
            #plt.xlabel(xlabel)
            plt.ylabel('depth (km)')
        if spherical == True:

            thetamin = 0
            thetamax = inv['a12'] * np.pi / 180.

            tr = PolarAxes.PolarTransform()

            pi = np.pi
            shift = pi / 2 - (thetamax + thetamin) / 2
            xx = xx + shift * 180. / pi
            angle_ticks = [(thetamin + shift, r""),
                           ((thetamax + thetamin) / 2 + shift, r""),
                           (thetamax + shift, r"")]
            grid_locator1 = FixedLocator([v for v, s in angle_ticks])
            tick_formatter1 = DictFormatter(dict(angle_ticks))

            grid_locator2 = MaxNLocator(6)

            grid_helper = floating_axes.GridHelperCurveLinear(
                tr,
                extremes=(thetamin + shift, thetamax + shift, 6371, 3480),
                grid_locator1=grid_locator1,
                grid_locator2=grid_locator2,
                tick_formatter1=tick_formatter1,
                tick_formatter2=None)

            ax1 = floating_axes.FloatingSubplot(fig,
                                                212,
                                                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.

            #ax=plt.subplot(212, polar = True)
            minval = np.min(np.min(toplot))
            maxval = np.max(np.max(toplot))

            contours = np.round(np.linspace(-1.1, 1.1, 12), 2)

            #plt.title(title)

            cs = aux_ax.pcolor((180. - xx) * np.pi / 180.,
                               6371. - yy,
                               toplot,
                               cmap=self.rgb_map,
                               vmin=0.5,
                               vmax=21.5)
            aux_ax.plot(np.pi - (thetamin + shift),
                        6371.,
                        '.c',
                        markersize=55,
                        markeredgecolor='k')
            aux_ax.plot(np.pi - (thetamax + shift),
                        6371.,
                        '.m',
                        markersize=55,
                        markeredgecolor='k')
            return aux_ax, shift
Esempio n. 20
0
File: wedge.py Progetto: pkaf/wedgez
def cone(
        ra,
        z,
        scale=0.5,
        orientation='horizontal',
        raaxis='min',
        ralim=None,
        zlim=None,
        hms=False,
        # cosmology=None, lookbtime=False,
        plot=None,
        fig=None,
        subnum=None,
        xlabel=r"$\alpha$",
        ylabel=r"$\mathsf{redshift}$",
        **kwargs):
    """
    Make a wedge plot of RA/Dec vs redshift z, where RA/DEC are in degrees

    Parameters
    ----------
    Input data

    angle : (n, ) array
            RA in degrees
    redshift : (n, ) array

    scale: 0.5

    orientation:
        'horizontal': increasing z along +ve xaxis
        'vertical': increasing z along +ve yaxis
        angle in degrees: increasing z along the tilted axis

    raxis: 'min' | 'mid' | float
        default is 'min'
        RA value along which the cone plot is orientated horizontal
        or vertical

    ralim, zlim: list [ramin, rmax], list [zmin, zmax]
        default is taken from the lower/upper bound of the input data

    scatter: any kwargs compatible with plt.scatter

    hms: show RA labels in units of hours (if True) or degrees (if False)

    lookbtime: True/False

    plot: None
         'scatter' | 'hexbin' etc
    fig: supply figure instance
         default None

    subnum: subplot number e.g. 111, 221 etc
            default None

    xlabel: r"$\alpha$"

    ylabel: r"$\mathsf{redshift}$"

    cosmology: dict
     Uses cosmolopy package to compute look-back time
     default cosmology is {'omega_M_0': 0.3,
                           'omega_lambda_0': 0.7,
                          'h': 0.72}

    kwargs
    ------
    scatter = {'s': 4, 'marker': ','}

    Notes
    -----
        --Decorations that can be done outside the code:
             Draw grids: ax.grid(True, alpha=0.2)
             Set title: ax.set_title('Wedge plot')

        --Look-back time as twin axis to redshift not yet implemented

        --In future plan is to able to put colorbar in the plot too.
          Using cmap option.
    """

    # ------ Extents of ra and z
    if ralim:
        ramin, ramax = ralim
    else:
        ramin, ramax = ra.min(), ra.max()

    if zlim:
        zmin, zmax = zlim
    else:
        zmin, zmax = z.min(), z.max()

    # ----- Scale and Orientation of the wedge
    if orientation == 'horizontal':
        dirn = 0.
    elif orientation == 'vertical':
        dirn = 90.
    else:
        dirn = orientation

    if raaxis == 'min':
        raaxis = ramin
    elif raaxis == 'mid':
        raaxis = 0.5 * (ramin + ramax)

    # Tilt of a cone relative to minimum RA
    tr_rotate = Affine2D().translate(dirn / scale - raaxis, 0.0)

    # Scaling the opening angle
    tr_scale = Affine2D().scale(scale * np.pi / 180., 1.0)

    tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()

    # ---- Grids
    if hms is True:
        grid_locator1 = angle_helper.LocatorHMS(4.0)
        tick_formatter1 = angle_helper.FormatterHMS()
    else:
        grid_locator1 = angle_helper.LocatorDMS(4.0)
        tick_formatter1 = angle_helper.FormatterDMS()

    grid_locator2 = MaxNLocator(10)

    grid_helper = GridHelperCurveLinear(tr,
                                        extremes=(ramin, ramax, zmin, zmax),
                                        grid_locator1=grid_locator1,
                                        grid_locator2=grid_locator2,
                                        tick_formatter1=tick_formatter1,
                                        tick_formatter2=None)

    # Figure properties
    if not fig:
        fig = plt.figure(figsize=(8, 7))
        subnum = 111
    ax = FloatingSubplot(fig, subnum, grid_helper=grid_helper)
    fig.add_subplot(ax)

    # adjust axis
    # Left, right, top represent z, lookbacktime, RA respectively.
    # right axes is for look-back time yet to be coded
    ax.axis["left"].set_axis_direction("bottom")

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

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

    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["left"].label.set_text(ylabel)
    ax.axis["top"].label.set_text(xlabel)

    # create a parasite axes that transData in RA, z
    aux = ax.get_aux_axes(tr)
    aux.patch = ax.patch  # for aux_ax to have a clip path as in ax
    ax.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.

    if plot == 'scatter':
        aux.scatter(ra, z, **kwargs)
        # plt.tight_layout()
        # plt.show()
    return ax, aux, fig
    #    while num < nstat:
    #    #  print num, nstat, mphs[num]
    #      if num == 0:
    #        dtrad[num] = math.radians( mphs[num] )
    #        strad[num] = math.radians( sphs[num] )
    #      else:
    #        dtrad.append( math.radians( mphs[num] ))
    #        strad.append( math.radians( sphs[num] ))
    #      num = num + 1

    #angle_ticks = [(0, r"$0$"),                  (.25*pi, r"$\frac{1}{4}\pi$"),                   (.5*pi, r"$\frac{1}{2}\pi$")]
    grid_locator1 = angle_helper.LocatorDMS(12)

    tick_formatter1 = angle_helper.FormatterDMS()

    grid_locator2 = MaxNLocator(2)

    dtrad = (np.array(mphs))
    strad = (np.array(sphs))

    total = np.hstack([dtrad, strad])

    checkrange_s = 0

    def mod_dist(a, b):
        return np.min([np.mod(a - b, 360), np.mod(b - a, 360)])

    for a in total:
        for b in total:
            crange = mod_dist(a, b)
            if crange > checkrange_s:
Esempio n. 22
0
def _setup_axes1(fig, angle, left, right, bottom, up, ax=None, rect=None):
    """
    Stacks a rotated axes over the main one.

    Required arguments:
    ----------
    *fig*:
        The figure that the axes are in.
        
    *angle*:
        A numeric limited in [-15, +15]. The angle of rotation of the canvas.
        
    *left*:
        A numeric. Leftmost point of the printable area.
    
    *right*:
        A numeric. Rightmost point of the printable area.
        
    *bottom*:
        A numeric. Lowest point of the printable area.
           
    *up*:
        A numeric. Highest point of the printable area.
     
    
    Return:
    -----------
    Two axes: a background one (ax1) and a rotated one (ax).
    The plot will be displayed on the rotated ax.
        
    """

    import mpl_toolkits.axisartist.floating_axes as floating_axes
    from mpl_toolkits.axisartist.grid_finder import MaxNLocator
    from matplotlib.transforms import Affine2D

    # Define height to width ratio
    vert = up - bottom
    hor = right - left
    ratio = vert / hor

    # Create rotated and scaled canvas
    tr = Affine2D().scale(4 * ratio, 4).rotate_deg(angle)

    # Rotated canvas is in the center tile of a 3x3 grid, limited by extremes
    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(left, right, bottom, up),
        grid_locator1=MaxNLocator(nbins=4),
        grid_locator2=MaxNLocator(nbins=4))

    if not rect:
        rect = 111

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

    ax = ax1.get_aux_axes(tr)

    for axisLoc in ['top', 'left', 'right', 'bottom']:
        ax1.axis[axisLoc].set_visible(False)
        ax.axis[axisLoc].set_visible(False)

    return ax, ax1
Esempio n. 23
0
def main():

    origin = [0, 0]
    xCoord = [1, -1]
    yCoord = [1, 2]
    transformation = [[1, 3], [5, 2]]
    [eigenvalue1, eigenvalue2], [eigenvector1,
                                 eigenvector2] = LA.eig(transformation)
    print eigenvalue1, eigenvalue2, (3 - sqrt(61)) / 2, (3 + sqrt(61)) / 2
    eigenvector1 = eigenvector1 / dot(eigenvector1, eigenvector1)
    eigenvector2 = eigenvector2 / dot(eigenvector2, eigenvector2)
    eigenCoord1 = zip(origin, 3 * eigenvalue1 * eigenvector1)
    print eigenvector1

    fig, ax = plt.subplots()
    x_grid_locator = MaxNLocator(3 // 0.0125)
    y_grid_locator = MaxNLocator(3 // 0.00625)
    ax = AA.Axes(
        fig, [0.1, 0.1, 0.8, 0.8],
        grid_helper=GridHelperCurveLinear(
            (tr, inv_tr),
            grid_locator1=x_grid_locator,
            grid_locator2=y_grid_locator))  # This appears to be your margins
    fig.add_axes(ax)
    ax.axis["right"].set_visible(False)
    ax.axis["top"].set_visible(False)
    ax.axis["left"].set_visible(False)
    ax.axis["bottom"].set_visible(False)
    ax.grid(True, zorder=0)
    # ax.set_xticks([0.01, 0.02, 0.03])
    ax.axis["t"] = ax.new_floating_axis(
        0, 0
    )  # first argument appears to be slope, second argument appears to be starting point on vertical
    ax.axis["t2"] = ax.new_floating_axis(1, 0)
    # ax.axis["t"].set_xticks([1, 2, 3, 4, 5, 6])
    # ax.axis["t"].label.set_pad(2)
    ax.plot([0, 1], [0, 1])
    # ax.axis["y=0"] = ax.new_floating_axis(nth_coord=0, value=0)
    # # ax.axis["x=0"] = ax.new_floating_axis(nth_coord=0, value=0)
    # ax.axis["right2"] = ax.new_fixed_axis(loc="right", offset=(-184, 0))
    # ax.axis["t"] = ax.new_floating_axis(0, 0) # first argument appears to be slope, second argument appears to be starting point on vertical
    # ax.axis["t2"] = ax.new_floating_axis(1, 0)
    scalingFactor = (24 * sqrt(29)) / 5
    otherFactor = 12 * sqrt(5)
    print scalingFactor / 3
    print otherFactor / 3
    ax.set_xlim(-scalingFactor, scalingFactor)
    ax.set_ylim(-otherFactor, otherFactor)
    ax.quiver(origin,
              origin,
              xCoord,
              yCoord,
              color=[colorDefault(0), colorDefault(3)],
              angles='xy',
              scale_units='xy',
              scale=1)
    ax.grid(True, which='both')
    ax.axhline(y=0, color='k')
    ax.axvline(x=0, color='k')
    # axis_to_data = ax.transAxes + ax.transData.inverted()
    # points_data = axis_to_data.transform((2, 3))
    # data_to_axis = axis_to_data.inverted()
    # numpy.testing.assert_allclose((2, 3), data_to_axis.transform(points_data))
    plt.xlim(-8, 8)
    plt.ylim(-8, 8)

    plt.figure()
    plt.quiver(origin,
               origin,
               xCoord,
               yCoord,
               color=[colorDefault(0), colorDefault(3)],
               angles='xy',
               scale_units='xy',
               scale=1)
    plt.grid(True, which='both')
    plt.axhline(y=0, color='k')
    plt.axvline(x=0, color='k')
    # axis_to_data = ax.transAxes + ax.transData.inverted()
    # points_data = axis_to_data.transform((2, 3))
    # data_to_axis = axis_to_data.inverted()
    # numpy.testing.assert_allclose((2, 3), data_to_axis.transform(points_data))
    plt.xlim(-8, 8)
    plt.ylim(-8, 8)

    fig = plt.figure()
    x_grid_locator = MaxNLocator(3 // 0.0125)
    y_grid_locator = MaxNLocator(3 // 0.00625)
    ax = AA.Axes(
        fig, [0.1, 0.1, 0.8, 0.8],
        grid_helper=GridHelperCurveLinear(
            (tr, inv_tr),
            grid_locator1=x_grid_locator,
            grid_locator2=y_grid_locator))  # This appears to be your margins
    fig.add_axes(ax)
    ax.axis["right"].set_visible(False)
    ax.axis["top"].set_visible(False)
    ax.axis["left"].set_visible(False)
    ax.axis["bottom"].set_visible(False)
    ax.grid(True, zorder=0)
    # ax.set_xticks([0.01, 0.02, 0.03])
    ax.axis["t"] = ax.new_floating_axis(
        0, 0
    )  # first argument appears to be slope, second argument appears to be starting point on vertical
    ax.axis["t2"] = ax.new_floating_axis(1, 0)
    # ax.axis["t"].set_xticks([1, 2, 3, 4, 5, 6])
    # ax.axis["t"].label.set_pad(2)
    ax.plot([0, 1], [0, 1])
    # ax.axis["y=0"] = ax.new_floating_axis(nth_coord=0, value=0)
    # # ax.axis["x=0"] = ax.new_floating_axis(nth_coord=0, value=0)
    # ax.axis["right2"] = ax.new_fixed_axis(loc="right", offset=(-184, 0))
    # ax.axis["t"] = ax.new_floating_axis(0, 0) # first argument appears to be slope, second argument appears to be starting point on vertical
    # ax.axis["t2"] = ax.new_floating_axis(1, 0)
    scalingFactor = (24 * sqrt(29)) / 5
    otherFactor = 12 * sqrt(5)
    print scalingFactor / 3
    print otherFactor / 3
    ax.set_xlim(-scalingFactor, scalingFactor)
    ax.set_ylim(-otherFactor, otherFactor)

    plt.show()
Esempio n. 24
0
def setup_axes(fig, rect, theta, radius, quad):

    # quad controls the quadrant of the plot and controls the orientation
    # of the plot where quad=1 is upper left, 2 is upper right, 3 is
    # lower left, 4 is lower right
    if quad == 1:
        tr_rotate = Affine2D().translate(np.pi / 2.0, 0)
    elif quad == 2:
        tr_rotate = Affine2D().translate(0, 0)
    elif quad == 3:
        tr_rotate = Affine2D().translate(np.pi, 0)
    else:
        tr_rotate = Affine2D().translate(3.0 * np.pi / 2.0, 0)

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

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = tr_scale + tr_rotate + PolarAxes.PolarTransform()

    # Find grid values appropriate for the coordinate (degree).
    # The argument is an approximate number of grids.
    grid_locator1 = angle_helper.LocatorD(2)

    # And also use an appropriate formatter:
    tick_formatter1 = angle_helper.FormatterDMS()

    # set up number of ticks for the r-axis
    grid_locator2 = MaxNLocator(5)
    grid_locator1 = MaxNLocator(6)

    # the extremes are passed to the function
    thetaMin = 0
    thetaMax = 90
    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(thetaMin, thetaMax, 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)

    print ax1.get_xlim()
    print ax1.get_ylim()
    # adjust axis
    # the axis artist lets you call axis with
    # "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")
    ax1.axis["top"].label.set_text(ur"$\Phi$")

    # Set the axis labels based on the quadrant
    if quad == 1:

        # Set visibilities
        ax1.axis["right"].set_visible(True)
        ax1.axis["left"].set_visible(True)
        ax1.axis["right"].toggle(ticklabels=True, label=True)
        ax1.axis["left"].toggle(ticklabels=False, label=False)

        # Tick Labels
        #ax1.axis["right"].major_ticks.set_axis_direction('right')
        ax1.axis["right"].major_ticklabels.set_axis_direction('bottom')
        #ax1.axis["right"].major_ticklabels.set_pad(-20)
        #ax1.axis["right"].set_axis_direction('top')
        #ax1.axis["right"].set_ticklabel_direction('+')

        # Axis labels
        ax1.axis["right"].label.set_rotation(0)
        ax1.axis["right"].label.set_text("$D$ (kpc)")
        ax1.axis["right"].label.set_pad(20)

    elif quad == 2:
        ax1.axis["left"].set_visible(True)
        ax1.axis["left"].toggle(ticklabels=True, label=True)
        ax1.axis["left"].major_ticklabels.set_axis_direction("bottom")
        ax1.axis["left"].set_axis_direction("bottom")
        ax1.axis["left"].label.set_text("$D$ (kpc)")

    elif quad == 3:
        # Set visibilities
        ax1.axis["right"].set_visible(True)
        ax1.axis["left"].set_visible(True)
        ax1.axis["right"].toggle(ticklabels=False, label=False)
        ax1.axis["left"].toggle(ticklabels=True, label=True)

        # Tick Labels
        #ax1.axis["right"].major_ticks.set_axis_direction('right')
        ax1.axis["left"].major_ticklabels.set_axis_direction('top')
        #ax1.axis["right"].major_ticklabels.set_pad(-20)
        #ax1.axis["right"].set_axis_direction('top')
        #ax1.axis["right"].set_ticklabel_direction('+')

        # Axis labels
        ax1.axis["left"].label.set_rotation(180)
        ax1.axis["left"].label.set_text("$D$ (kpc)")
        ax1.axis["left"].label.set_pad(20)

    else:
        # Set visibilities
        ax1.axis["right"].set_visible(True)
        ax1.axis["left"].set_visible(True)
        ax1.axis["right"].toggle(ticklabels=True, label=True)
        ax1.axis["left"].toggle(ticklabels=False, label=False)

        # Tick Labels
        #ax1.axis["right"].major_ticks.set_axis_direction('right')
        ax1.axis["right"].major_ticklabels.set_axis_direction('top')
        #ax1.axis["right"].major_ticklabels.set_pad(-20)
        #ax1.axis["right"].set_axis_direction('top')
        #ax1.axis["right"].set_ticklabel_direction('+')

        # Axis labels
        ax1.axis["right"].label.set_rotation(180)
        ax1.axis["right"].label.set_text("$D$ (kpc)")
        ax1.axis["right"].label.set_pad(0)

    ax1.grid(True)

    # create a parasite axes
    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
Esempio n. 25
0
def fractional_polar_axes(f, thlim=(0, 180), rlim=(0, 1), step=(30, 0.25),
						  thlabel='theta', rlabel='r', ticklabels=True, rlabels = None, subplot=111):
	'''Return polar axes that adhere to desired theta (in deg) and r limits. steps for theta
	and r are really just hints for the locators.'''
	th0, th1 = thlim # deg
	r0, r1 = rlim
	thstep, rstep = step

	# scale degrees to radians:
	tr_scale = Affine2D().scale(np.pi/180., 1.)
	pa = PolarAxes
	tr = tr_scale + pa.PolarTransform()
	theta_grid_locator = angle_helper.LocatorDMS((th1-th0)//thstep)
	r_grid_locator = MaxNLocator((r1-r0)//rstep)
	theta_tick_formatter = angle_helper.FormatterDMS()
	if rlabels:
		rlabels = DictFormatter(rlabels)

	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=rlabels)

	a = FloatingSubplot(f, subplot, grid_helper=grid_helper)
	f.add_subplot(a)
	
	# adjust x axis (theta):
	a.axis["bottom"].set_visible(False)
	a.axis["top"].set_axis_direction("bottom") # tick direction
	a.axis["top"].toggle(ticklabels=ticklabels, label=bool(thlabel))
	a.axis["top"].major_ticklabels.set_axis_direction("top")
	a.axis["top"].label.set_axis_direction("top")
	a.axis["top"].major_ticklabels.set_pad(10)

	# adjust y axis (r):
	a.axis["left"].set_axis_direction("bottom") # tick direction
	a.axis["right"].set_axis_direction("top") # tick direction
	a.axis["left"].toggle(ticklabels=True, label=bool(rlabel))
	
	# add labels:
	a.axis["top"].label.set_text(thlabel)
	a.axis["left"].label.set_text(rlabel)
	
	# create a parasite axes whose transData is theta, r:
	auxa = a.get_aux_axes(tr)
	
	# make aux_ax to have a clip path as in a?:
	auxa.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

	# add sector lines for both dimensions:
	thticks = grid_helper.grid_info['lon_info'][0]
	rticks = grid_helper.grid_info['lat_info'][0]
	for th in thticks[1:-1]: # all but the first and last
		auxa.plot([th, th], [r0, r1], ':', c='grey', zorder=-1, lw=0.5)
		for ri, r in enumerate(rticks):
			# plot first r line as axes border in solid black only if it  isn't at r=0
			if ri == 0 and r != 0:
				ls, lw, color = 'solid', 1, 'black'
			else:
				ls, lw, color = 'dashed', 0.5, 'grey'
				# From http://stackoverflow.com/a/19828753/2020363
				auxa.add_artist(plt.Circle([0, 0], radius=r, ls=ls, lw=lw, color=color, fill=False,
							   transform=auxa.transData._b, zorder=-1))

	return auxa
Esempio n. 26
0
    def __init__(self,
                 rotation,
                 ra_min,
                 ra_max,
                 z_min,
                 z_max,
                 stretch=1,
                 nrows=1,
                 ncols=1,
                 npar=1,
                 width=8.0,
                 aspect=0.8,
                 gridspec=None,
                 blank=True,
                 fontsize=16,
                 legend_fontsize=14,
                 family='serif',
                 style='Times',
                 weight='normal',
                 usetex=False):

        super(ConePlot,
              self).__init__(nrows, ncols, npar, width, aspect, gridspec,
                             blank, fontsize, legend_fontsize, family, style,
                             weight, usetex)

        # Rotate for better orientation:
        rotate = Affine2D().translate(rotation, 0)

        # Scale degree to radians:
        scale = Affine2D().scale(np.pi * stretch / 180, 1)

        transform = rotate + scale + PolarAxes.PolarTransform()

        grid_locator1 = angle_helper.LocatorHMS(4)
        grid_locator2 = MaxNLocator(5)
        tick_formatter1 = angle_helper.FormatterHMS()

        self.grid_helper = floating_axes.GridHelperCurveLinear(
            transform,
            extremes=(ra_min, ra_max, z_min, z_max),
            grid_locator1=grid_locator1,
            grid_locator2=grid_locator2,
            tick_formatter1=tick_formatter1,
            tick_formatter2=None)

        ax = floating_axes.FloatingSubplot(self,
                                           111,
                                           grid_helper=self.grid_helper)

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

        ax.axis['bottom'].set_visible(False)
        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['left'].label.set_text('Redshift')
        ax.axis['top'].label.set_text('RA (J2000)')

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

        self.add_subplot(ax)
        self.aux_ax = aux_ax