Пример #1
0
def taylor(scores):
    fig = plt.figure(1)
    tr = PolarAxes.PolarTransform()
    
    CCgrid= np.concatenate((np.arange(0,10,2)/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, np.pi/2
    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["left"].set_axis_direction("bottom") 
    ax1.axis["left"].label.set_text("Normalized Standard deviation")

    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)
    
    rs,ts = np.meshgrid(np.linspace(0,2),np.linspace(0,np.pi/2))
    rms = np.sqrt(1 + rs**2 - 2*rs*np.cos(ts))
        
    contours = ax1.contour(ts, rs, rms, 3,colors='0.5')   
    plt.clabel(contours, inline=1, fontsize=10)
    plt.grid(linestyle=':',alpha=0.5) 
        
    
    for r in scores.iterrows():
        th=np.arccos(r[1].CORRELATION)
        rr=r[1].MSTD/r[1].OSTD
        
        ax1.plot(th,rr,'o',label=r[0])
        
    plt.legend(loc='upper right',bbox_to_anchor=[1.2,1.15])    
    plt.show()
Пример #2
0
def taylor_template(angle_lim, std_lim, rect, xaxislab, fig=None):
    # written by Maria Aristizabal: https://github.com/MariaAristizabal/Evaluation_surf_metrics_Dorian_figures
    import mpl_toolkits.axisartist.floating_axes as floating_axes
    from matplotlib.projections import PolarAxes
    from mpl_toolkits.axisartist.grid_finder import (FixedLocator,
                                                     DictFormatter)

    if fig is None:
        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, std_lim, .5)
    gfs = FixedLocator(STDgrid)
    tfs = DictFormatter(dict(zip(STDgrid, map(str, STDgrid))))

    ra0, ra1 = 0, angle_lim
    cz0, cz1 = 0, std_lim
    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, rect, 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")
    if xaxislab == 'yes':
        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)

    return fig, ax1
Пример #3
0
def test_curvelinear3():
    fig = plt.figure(figsize=(5, 5))

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

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

    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)
    fig.add_subplot(ax1)

    r_scale = 10
    tr2 = mtransforms.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)

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

    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)
Пример #4
0
def taylor_template(angle_lim, std_lim):

    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, std_lim, .5)
    gfs = FixedLocator(STDgrid)
    tfs = DictFormatter(dict(zip(STDgrid, map(str, STDgrid))))

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

    return fig, ax1
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
Пример #6
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
Пример #7
0
    def setup_axes2(self, fig, rect, n_markers, lat_min, lat_max, angle_ticks):
        """
        for thin shells, lat subset 
        """

        tr = PolarAxes.PolarTransform()

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

        if not angle_ticks:
            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=(lat_max / 180 * np.pi, lat_min / 180 * np.pi,
                      self.r_outer, self.r_inner),  # 70/180
            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)

        # format tick labels (see: https://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html)
        ax1.axis["bottom"].major_ticklabels.set_rotation(-90)
        ax1.axis["bottom"].major_ticklabels.set_va("center")
        ax1.axis["bottom"].major_ticklabels.set_pad(12)

        # 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
Пример #8
0
    def setup_axes1(self, fig, T_ticks, subplotshape=None):
        """
        A simple one.
        """
        deg = -45.
        self.tr = Affine2D().rotate_deg(deg)

        theta_ticks = []  #np.arange(theta_min, theta_max, d_T)

        grid_helper = GridHelperCurveLinear(
            self.tr,
            grid_locator1=FixedLocator(T_ticks),
            grid_locator2=FixedLocator(theta_ticks))

        if subplotshape is None:
            subplotshape = (1, 1, 1)

        ax1 = Subplot(fig, *subplotshape, 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)

        # SW, SE, NE, NW
        corners = np.array([[-25., -20.], [30., 40.], [-40., 120.],
                            [-105., 60.]])
        corners_t = self._tf(corners[:, 0], corners[:, 1])

        # ax1.set_aspect(1.)
        x_min, x_max = self.x_range
        ax1.set_xlim(x_min, x_max)
        ax1.set_ylim(*self.y_range)
        ax1.set_xlabel('Temperature [C]')

        ax1.set_aspect(1)

        #ax1.axis["t"]=ax1.new_floating_axis(0, 0.)
        #T_axis = ax1.axis['t']
        #theta_axis = ax1.axis["t2"]=ax1.new_floating_axis(1, 0.)

        # plot.draw()
        # plot.show()
        self.ax1 = ax1
Пример #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
Пример #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
Пример #11
0
def test_curvelinear4():
    # Remove this line when this test image is regenerated.
    plt.rcParams['text.kerning_factor'] = 6

    fig = plt.figure(figsize=(5, 5))

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

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

    grid_locator2 = FixedLocator([2, 4, 6, 8, 10])

    grid_helper = GridHelperCurveLinear(tr,
                                        extremes=(120, 30, 10, 0),
                                        grid_locator1=grid_locator1,
                                        grid_locator2=grid_locator2,
                                        tick_formatter1=tick_formatter1,
                                        tick_formatter2=None)

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

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

    for an in ["top"]:
        ax1.axis[an].set_visible(False)

    axis = grid_helper.new_floating_axis(1,
                                         70,
                                         axes=ax1,
                                         axis_direction="bottom")
    ax1.axis["z"] = axis
    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")

    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)
Пример #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
Пример #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
Пример #14
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
Пример #15
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
Пример #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
Пример #17
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()
def taylor(scores, colors, units, angle_lim):

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

    CCgrid = np.concatenate((np.arange(0, 10, 2) / 10., [0.9, 0.95, 0.99]))
    CCpolar = np.arccos(CCgrid)
    gf = FixedLocator(CCpolar)
    tf = DictFormatter(dict(zip(CCpolar, map(str, CCgrid))))

    max_std = np.nanmax([scores.OSTD, scores.MSTD])

    if np.round(scores.OSTD[0], 2) <= 0.2:
        #STDgrid=np.linspace(0,np.round(scores.OSTD[0]+0.01,2),3)
        STDgrid = np.linspace(0, np.round(scores.OSTD[0] + max_std + 0.02, 2),
                              3)
    if np.logical_and(
            np.round(scores.OSTD[0], 2) > 0.2,
            np.round(scores.OSTD[0], 2) <= 1):
        STDgrid = np.linspace(0, np.round(scores.OSTD[0] + 0.1, 2), 3)
    if np.logical_and(
            np.round(scores.OSTD[0], 2) > 1,
            np.round(scores.OSTD[0], 2) <= 5):
        STDgrid = np.arange(0, np.round(scores.OSTD[0] + 2, 2), 1)
    if np.round(scores.OSTD[0], 2) > 5:
        STDgrid = np.arange(0, np.round(scores.OSTD[0] + 5, 1), 2)

    gfs = FixedLocator(STDgrid)
    tfs = DictFormatter(dict(zip(STDgrid, map(str, STDgrid))))

    ra0, ra1 = 0, angle_lim
    if np.round(scores.OSTD[0], 2) <= 0.2:
        cz0, cz1 = 0, np.round(max_std + 0.1, 2)
    else:
        #cz0, cz1 = 0, np.round(scores.OSTD[0]+0.1,2)
        cz0, cz1 = 0, np.round(max_std + 0.1, 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("Standard Deviation " + '(' + units + ')')
    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

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

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

    rs, ts = np.meshgrid(np.linspace(0, np.round(max_std + 0.1, 2)),
                         np.linspace(0, angle_lim))

    rms = np.sqrt(scores.OSTD[0]**2 + rs**2 -
                  2 * rs * scores.OSTD[0] * np.cos(ts))

    ax1.contour(ts, rs, rms, 5, colors='0.5')
    #contours = ax1.contour(ts, rs, rms,5,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(r[1].OSTD**2 + r[1].MSTD**2 \
        #           - 2*r[1].OSTD*r[1].MSTD*r[1].CORRELATION)
        crmse = np.sqrt(scores.OSTD[0]**2 + r[1].MSTD**2 \
                   - 2*scores.OSTD[0]*r[1].MSTD*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')

    return fig, ax1
Пример #19
0
cgax.axis["bottom"].get_helper().nth_coord_ticks = 0
# and also set tickmarklength to zero for better presentation
cgax.axis["right"].major_ticks.set_ticksize(0)
cgax.axis["top"].major_ticks.set_ticksize(0)
# make ticklabels of left and bottom axis unvisible,
# because we are drawing them
cgax.axis["right"].major_ticklabels.set_visible(False)
cgax.axis["top"].major_ticklabels.set_visible(False)
# and also set tickmarklength to zero for better presentation
cgax.axis["right"].major_ticks.set_ticksize(0)
cgax.axis["top"].major_ticks.set_ticksize(0)
plt.text(0.025,
         -0.065,
         'azimuth',
         transform=caax.transAxes,
         va='bottom',
         ha='left')
cbar.set_label('reflectivity [dBZ]')
gh = cgax.get_grid_helper()
# set azimuth resolution to 15deg
gh.grid_finder.grid_locator1 = FixedLocator([i for i in np.arange(0, 359, 5)])
gh.grid_finder.grid_locator2._nbins = 30
gh.grid_finder.grid_locator2._steps = [1, 1.5, 2, 2.5, 5, 10]
cgax.axis["lat"] = cgax.new_floating_axis(0, 240)
cgax.axis["lat"].set_ticklabel_direction('-')
cgax.axis["lat"].label.set_text("range [km]")
cgax.axis["lat"].label.set_rotation(180)
cgax.axis["lat"].label.set_pad(10)
plt.tight_layout()
plt.draw()
plt.show()
Пример #20
0
def plot_shape(topological, max_level=10):
    '''
    Shows the average tree shape as a bullseye plot.

    Parameters
    ----------
    topological : TopologicalAnalysisResult
        Topological stats of the model to be visualized.
    max_level : int
        Maximul tree-depth of the visualization. Maximum allowed value is 16.

    Returns
    -------
    : matplotlib.figure.Figure
        The matpotlib Figure
    '''

    ts = topological.avg_tree_shape()
    max_levels, _ = ts.shape
    max_levels = min(max_levels, max_level + 1)
    # precision of the plot (should be at least 2**max_levels)
    max_nodes = max(128, 2**max_levels)

    # custom color map
    cm = LinearSegmentedColormap.from_list(
        'w2r', [(1, 1, 1), (23. / 255., 118. / 255., 182. / 255.)], N=256)

    # figure
    fig = plt.figure(1, figsize=(12, 6))

    tr = Affine2D().translate(np.pi, 0) + PolarAxes.PolarTransform()
    x_ticks = [x + 2. for x in range(max_levels - 1)]
    grid_locator2 = FixedLocator(x_ticks)
    tick_formatter2 = DictFormatter(
        {k: " " + str(int(k) - 1)
         for k in x_ticks})
    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(0, np.pi, 0, max_levels),
        grid_locator2=grid_locator2,
        tick_formatter2=tick_formatter2)

    ax3 = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper)
    fig.add_axes(ax3)

    # fix axes
    ax3.axis["bottom"].set_visible(False)
    ax3.axis["top"].set_visible(False)
    ax3.axis["right"].set_axis_direction("top")

    ax3.axis["left"].set_axis_direction("bottom")
    ax3.axis["left"].major_ticklabels.set_pad(-5)
    ax3.axis["left"].major_ticklabels.set_rotation(180)
    #    ax3.axis["left"].label.set_text("tree level")
    #    ax3.axis["left"].label.set_ha("right")
    ax3.axis["left"].label.set_rotation(180)
    ax3.axis["left"].label.set_pad(20)
    ax3.axis["left"].major_ticklabels.set_ha("left")

    ax = ax3.get_aux_axes(tr)
    ax.patch = ax3.patch  # for aux_ax to have a clip path as in ax
    ax3.patch.zorder = .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.
    # data to be plotted
    theta, r = np.mgrid[0:np.pi:(max_nodes + 1) * 1j, 0:max_levels + 1]
    z = np.zeros(theta.size).reshape(theta.shape)

    for level in xrange(max_levels):
        num_nodes = 2**level
        num_same_color = max_nodes / num_nodes
        for node in xrange(num_nodes):
            if node < ts.shape[1]:
                z[num_same_color * node:num_same_color * (node + 1),
                  level] = ts[level, node]

    # draw the tree nodes frequencies
    h = ax.pcolormesh(theta, r, z, cmap=cm, vmin=0., vmax=1.)

    # color bar
    cax = fig.add_axes([.95, 0.15, 0.025, 0.8])  # axes for the colot bar
    cbar = fig.colorbar(h, cax=cax, ticks=np.linspace(0, 1, 11))
    cbar.ax.tick_params(labelsize=8)
    cax.set_title('Frequency', verticalalignment="bottom", fontsize=10)

    # separate depths
    for level in xrange(1, max_levels + 1):
        ax.plot(np.linspace(0, np.pi, num=128), [1 * level] * 128,
                'k:',
                lw=0.3)

    # separate left sub-tree from right sub-tree
    ax.plot([np.pi, np.pi], [0, 1], 'k-')
    ax.plot([0, 0], [0, 1], 'k-')

    # label tree depths
    ax.text(np.pi / 2 * 3,
            .2,
            "ROOT",
            horizontalalignment='center',
            verticalalignment='center')
    ax.text(-.08,
            max_levels,
            "Tree level",
            verticalalignment='bottom',
            fontsize=14)

    # left/right subtree
    #    ax.text(np.pi/4.,max_levels*1.15, "Left subtree", fontsize=12,
    #            horizontalalignment="center", verticalalignment="center")
    #    ax.text(np.pi/4.*3,max_levels*1.15, "Right subtree", fontsize=12,
    #            horizontalalignment="center", verticalalignment="center")

    ax3.set_title("Average Tree Shape: " + str(topological.model),
                  fontsize=16,
                  y=1.2)

    return fig
def erpa_axes(fig, rect, PA_bin_edges, epq_edges, log_epq_offset):
    import mpl_toolkits.axisartist.floating_axes as floating_axes
    from matplotlib.projections import PolarAxes
    from mpl_toolkits.axisartist.grid_finder import (FixedLocator,
                                                     DictFormatter)
    '''
    Function that creates the axes for the energy resolved pitch angle plots.
    Arguments:
        fig: the figure the axes will be plotted on
        rect: the subplot of the figure the axis belongs on
    
    Note that the extreme/boundary values are swapped.
    
    If this function is used within the function erpa_plotter, the arguments are defined within erpa_plotter
    '''

    tr = PolarAxes.PolarTransform()

    #pi = np.pi
    #setting tick marks and tick labels for the pitch angle/circumference axis
    angle_ticks = [(x * np.pi / 180.0, str(x) + '$^\circ$')
                   for x in PA_bin_edges]

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

    #Make our log scale r axis start closer to r=0

    #setting tick marks and tick labels of the energy per charge/radial axis
    radius_ticks = [
        (np.log10(x) - log_epq_offset, "{:.1f}".format(x)) for x in epq_edges
    ]  #may cause issue if log(epq) < 0 (negative radius on polar plot...)

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

    #Arika's version with the extremes flipped
    grid_helper = floating_axes.GridHelperCurveLinear(
        tr,
        extremes=(np.max(PA_bin_edges) * np.pi / 180.0, np.min(PA_bin_edges),
                  np.max(np.log10(epq_edges)) - log_epq_offset,
                  np.min(np.log10(epq_edges)) - log_epq_offset),
        grid_locator1=grid_locator1,
        grid_locator2=grid_locator2,
        tick_formatter1=tick_formatter1,
        tick_formatter2=tick_formatter2)

    #version w/o extremes flipped -> doesn't appear to work!
    #grid_helper = floating_axes.GridHelperCurveLinear(
    #    tr, extremes=(np.min(PA_bin_edges),np.max(PA_bin_edges)*np.pi/180.0,  np.min(np.log10(epq_edges),np.max(np.log10(epq_edges)))),
    #    grid_locator1=grid_locator1,
    #    grid_locator2=grid_locator2,
    #    tick_formatter1=tick_formatter1,
    #    tick_formatter2=tick_formatter2)

    #grid_helper = floating_axes.GridHelperCurveLinear(
    #    tr, extremes=(np.pi,0,1,0.5),
    #    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)

    #Old way of doing plotting label and ticks
    ax1.axis["bottom"].major_ticklabels.set_rotation(180)

    ax1.axis["top"].major_ticklabels.set_axis_direction("top")
    ax1.axis["top"].label.set_axis_direction("top")
    ax1.axis['bottom'].major_ticklabels.set_fontsize(
        15)  #pitch angle tick label
    #after some experimenting, this works!
    #bad documentation for this

    #new experiemnt with radial text on right hand side
    ax1.axis['left'].toggle(
        ticklabels=False)  #turn off left side radial labels
    ax1.axis['right'].label.set_text('E/q (keV/e)')
    ax1.axis['right'].label.set_fontsize(15)
    ax1.axis['right'].label.set_visible(
        True)  #turn on right side radial labels
    ax1.axis['right'].toggle(ticklabels=True, label='E/q (keV/e)')
    ax1.axis['right'].major_ticklabels.set_fontsize(
        15)  #E/q tick label size, after some guesswork, this works!

    #Alternate plotting label and ticks section --> doesn't appear to work!
    #adjust x axis (theta):
    #    ticklabels=True
    #    thlabel='Pitch Angle'
    #    rlabel='E/q (keV/e)'
    #    ax1.axis["bottom"].set_visible(False)
    #    ax1.axis["top"].set_axis_direction("bottom") # tick direction
    #    ax1.axis["top"].toggle(ticklabels=ticklabels, label=bool(thlabel))
    #    ax1.axis["top"].major_ticklabels.set_axis_direction("top")
    #    ax1.axis["top"].label.set_axis_direction("top")
    #
    #    # adjust y axis (r):
    #    ax1.axis["left"].set_axis_direction("bottom") # tick direction
    #    ax1.axis["right"].set_axis_direction("top") # tick direction
    #    ax1.axis["left"].toggle(ticklabels=ticklabels, label=bool(rlabel))
    #
    #    # add labels:
    #    ax1.axis["top"].label.set_text(thlabel)
    #    ax1.axis["left"].label.set_text(rlabel)

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

    ###Note from Arika Egan: Not sure why this part is necessary, but it accompanied the example this function was created from, and it doesn't do any harm.
    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
Пример #22
0
def create_cg(st, fig=None, subplot=111):
    """ 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
    ----------
    st : string
        scan type, 'PPI' or 'RHI'
    fig : matplotlib Figure object
        If given, the PPI 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

    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
    """

    if st == 'RHI':
        # create transformation
        tr = Affine2D().scale(np.pi / 180, 1) + PolarAxes.PolarTransform()

        # build up curvelinear grid
        extreme_finder = ah.ExtremeFinderCycle(20, 20,
                                               lon_cycle=100,
                                               lat_cycle=None,
                                               lon_minmax=(0, np.inf),
                                               lat_minmax=(0, np.inf),
                                               )

        # locator and formatter for angular annotation
        grid_locator1 = ah.LocatorDMS(10.)
        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 range gridlines
        grid_helper.grid_finder.grid_locator2._nbins = 30.0
        grid_helper.grid_finder.grid_locator2._steps = [0, 1, 1.5,
                                                        2, 2.5, 5, 10]

    if st == 'PPI':
        # Set theta start to north
        tr_rotate = Affine2D().translate(-90, 0)
        # set theta running clockwise
        tr_scale = Affine2D().scale(-np.pi / 180, 1)
        # create transformation
        tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()

        # build up curvelinear grid
        extreme_finder = ah.ExtremeFinderCycle(20, 20,
                                               lon_cycle=360,
                                               lat_cycle=None,
                                               lon_minmax=(360, 0),
                                               lat_minmax=(0, np.inf),
                                               )

        # locator and formatter for angle annotation
        locs = [i for i in np.arange(0., 359., 10.)]
        grid_locator1 = FixedLocator(locs)
        tick_formatter1 = DictFormatter(dict([(i, r"${0:.0f}^\circ$".format(i))
                                              for i in locs]))

        # 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 range gridlines
        grid_helper.grid_finder.grid_locator2._nbins = 15.0
        grid_helper.grid_finder.grid_locator2._steps = [0, 1, 1.5, 2,
                                                        2.5,
                                                        5,
                                                        10]

    # if there is no figure object given
    if fig is None:
        # create new figure if there is only one subplot
        if subplot is 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)

    # PPIs always plottetd with equal aspect
    if st == 'PPI':
        cgax.set_aspect('equal', adjustable='box')

    # 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
Пример #23
0
def curved_earth_axes(rect=111,
                      fig=None,
                      minground=0.,
                      maxground=2000,
                      minalt=0,
                      maxalt=500,
                      Re=6371.,
                      nyticks=5,
                      nxticks=4):
    """
    Create curved axes in ground-range and altitude
    Copied from DaViTPy: https://github.com/vtsuperdarn/davitpy/blob/1b578ea2491888e3d97d6e0a8bc6d8cc7c9211fb/davitpy/utils/plotUtils.py#L559
    """
    from matplotlib.transforms import Affine2D, Transform
    import mpl_toolkits.axisartist.floating_axes as floating_axes
    from matplotlib.projections import polar
    from mpl_toolkits.axisartist.grid_finder import FixedLocator, DictFormatter
    import numpy as np
    from pylab import gcf

    ang = maxground / Re
    minang = minground / Re
    angran = ang - minang
    angle_ticks = [(0, "{:.0f}".format(minground))]
    while angle_ticks[-1][0] < angran:
        tang = angle_ticks[-1][0] + 1. / nxticks * angran
        angle_ticks.append((tang, "{:.0f}".format((tang - minang) * Re)))
    grid_locator1 = FixedLocator([v for v, s in angle_ticks])
    tick_formatter1 = DictFormatter(dict(angle_ticks))

    altran = float(maxalt - minalt)
    alt_ticks = [(minalt + Re, "{:.0f}".format(minalt))]

    while alt_ticks[-1][0] < Re + maxalt:
        alt_ticks.append(
            (altran / float(nyticks) + alt_ticks[-1][0],
             "{:.0f}".format(altran / float(nyticks) + alt_ticks[-1][0] - Re)))
    _ = alt_ticks.pop()
    grid_locator2 = FixedLocator([v for v, s in alt_ticks])
    tick_formatter2 = DictFormatter(dict(alt_ticks))

    tr_rotate = Affine2D().rotate(np.pi / 2 - ang / 2)
    tr_shift = Affine2D().translate(0, Re)
    tr = polar.PolarTransform() + tr_rotate

    grid_helper = \
        floating_axes.GridHelperCurveLinear(tr, extremes=(0, angran, Re+minalt,
                                                          Re+maxalt),
                                            grid_locator1=grid_locator1,
                                            grid_locator2=grid_locator2,
                                            tick_formatter1=tick_formatter1,
                                            tick_formatter2=tick_formatter2,)

    if not fig:
        fig = gcf()
    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)

    # adjust axis
    #     ax1.axis["left"].label.set_text(r"Alt. [km]")
    #     ax1.axis["bottom"].label.set_text(r"Ground range [km]")
    ax1.invert_xaxis()

    ax1.minground = minground
    ax1.maxground = maxground
    ax1.minalt = minalt
    ax1.maxalt = maxalt
    ax1.Re = Re

    fig.add_subplot(ax1, transform=tr)

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

    # for aux_ax to have a clip path as in ax
    aux_ax.patch = ax1.patch

    # 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.
    ax1.patch.zorder = 0.9

    return ax1, aux_ax
Пример #24
0
gh.grid_finder.grid_locator1 = FixedLocator([
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12,
    13,
    14,
    15,
    16,
    17,
    18,
    20,
    22,
    25,
    30,
    35,
    40,
    50,
    60,
    70,
    80,
    90,
])
Пример #25
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
Пример #26
0
cgax.set_ylim(0, 7)
cbar = plt.gcf().colorbar(pm, shrink=0.8, extend='both')  #, pad=0.05)
plt.gca().invert_xaxis()
cbar.set_label('Z (dBZ)', fontsize=fft)
caax.set_xlabel('x (km)', fontsize=fft)
caax.set_ylabel('z (km)', fontsize=fft)

cbar.ax.tick_params(labelsize=fft)

caax.tick_params(labelsize=fft)

plt.figtext(xl, yu, 'c) BoXPol RHI \n 2014-10-07, 02:37 UTC', fontsize=fft)

gh = cgax.get_grid_helper()
locs = [0.]
gh.grid_finder.grid_locator1 = FixedLocator(locs)
gh.grid_finder.tick_formatter1 = DictFormatter(
    dict([(i, r"${0:.0f}^\circ$".format(i)) for i in locs]))
plt.yticks(fontsize=fft)
plt.xticks(fontsize=fft)

plt.tight_layout()
plt.show()
'''
grid_gpm_xy2 = np.vstack((gpm_x[:,cut].ravel(), gpm_y.ravel())).transpose() # GPM Grid erschaffen

xxxyyy = np.vstack((xxx[0:-1,0:-1].ravel(), yyy[0:-1,0:-1].ravel())).transpose()

mask1 = ~np.isnan(ma)

result2 = wrl.ipol.interpolate(xxxyyy, grid_gpm_xy2, ma[mask1].reshape(ma.shape[0]*ma.shape[1],1), wrl.ipol.Idw, nnearest=4)  #Idw
Пример #27
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')
Пример #28
0
def curvedEarthAxes(rect=111,
                    fig=None,
                    minground=0.,
                    maxground=2000,
                    minalt=0,
                    maxalt=500,
                    Re=6371.,
                    nyticks=5,
                    nxticks=4):
    """Create curved axes in ground-range and altitude

    Parameters
    ----------
    rect : Optional[int]
        subplot spcification
    fig : Optional[pylab.figure object]
        (default to gcf)
    minground : Optional[float]

    maxground : Optional[int]
        maximum ground range [km]
    minalt : Optional[int]
        lowest altitude limit [km]
    maxalt : Optional[int]
        highest altitude limit [km]
    Re : Optional[float] 
        Earth radius in kilometers
    nyticks : Optional[int]
        Number of y axis tick marks; default is 5
    nxticks : Optional[int]
        Number of x axis tick marks; deafult is 4

    Returns
    -------
    ax : matplotlib.axes object
        containing formatting
    aax : matplotlib.axes object
        containing data

    Example
    -------
        import numpy as np
        from utils import plotUtils
        ax, aax = plotUtils.curvedEarthAxes()
        th = np.linspace(0, ax.maxground/ax.Re, 50)
        r = np.linspace(ax.Re+ax.minalt, ax.Re+ax.maxalt, 20)
        Z = exp( -(r - 300 - ax.Re)**2 / 100**2 ) * np.cos(th[:, np.newaxis]/th.max()*4*np.pi)
        x, y = np.meshgrid(th, r)
        im = aax.pcolormesh(x, y, Z.T)
        ax.grid()

    written by Sebastien, 2013-04

    """
    from matplotlib.transforms import Affine2D, Transform
    import mpl_toolkits.axisartist.floating_axes as floating_axes
    from matplotlib.projections import polar
    from mpl_toolkits.axisartist.grid_finder import FixedLocator, DictFormatter
    import numpy as np
    from pylab import gcf

    ang = maxground / Re
    minang = minground / Re
    angran = ang - minang
    angle_ticks = [(0, "{:.0f}".format(minground))]
    while angle_ticks[-1][0] < angran:
        tang = angle_ticks[-1][0] + 1. / nxticks * angran
        angle_ticks.append((tang, "{:.0f}".format((tang - minang) * Re)))
    grid_locator1 = FixedLocator([v for v, s in angle_ticks])
    tick_formatter1 = DictFormatter(dict(angle_ticks))

    altran = float(maxalt - minalt)
    alt_ticks = [(minalt + Re, "{:.0f}".format(minalt))]
    while alt_ticks[-1][0] < Re + maxalt:
        alt_ticks.append(
            (altran / float(nyticks) + alt_ticks[-1][0],
             "{:.0f}".format(altran / float(nyticks) + alt_ticks[-1][0] - Re)))
    _ = alt_ticks.pop()
    grid_locator2 = FixedLocator([v for v, s in alt_ticks])
    tick_formatter2 = DictFormatter(dict(alt_ticks))

    tr_rotate = Affine2D().rotate(np.pi / 2 - ang / 2)
    tr_shift = Affine2D().translate(0, Re)
    tr = polar.PolarTransform() + tr_rotate

    grid_helper = \
        floating_axes.GridHelperCurveLinear(tr, extremes=(0, angran, Re+minalt,
                                                          Re+maxalt),
                                            grid_locator1=grid_locator1,
                                            grid_locator2=grid_locator2,
                                            tick_formatter1=tick_formatter1,
                                            tick_formatter2=tick_formatter2,)

    if not fig: fig = gcf()
    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)

    # adjust axis
    ax1.axis["left"].label.set_text(r"Alt. [km]")
    ax1.axis["bottom"].label.set_text(r"Ground range [km]")
    ax1.invert_xaxis()

    ax1.minground = minground
    ax1.maxground = maxground
    ax1.minalt = minalt
    ax1.maxalt = maxalt
    ax1.Re = Re

    fig.add_subplot(ax1, transform=tr)

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

    # for aux_ax to have a clip path as in ax
    aux_ax.patch = ax1.patch

    # 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.
    ax1.patch.zorder = 0.9

    return ax1, aux_ax
Пример #29
0
import numpy as np
# well, it's a wradlib example
import wradlib
from mpl_toolkits.axisartist.grid_finder import FixedLocator
# reading in data, range and theta arrays from special rhi hdf5 file
file = '../../examples/data/polar_rhi_dBZ_bonn.h5'
data, meta = wradlib.io.from_hdf5(file, dataset='data')
r, meta = wradlib.io.from_hdf5(file, dataset='range')
th, meta = wradlib.io.from_hdf5(file, dataset='theta')
# mask data array for better presentation
mask_ind = np.where(data <= np.nanmin(data))
data[mask_ind] = np.nan
ma = np.ma.array(data, mask=np.isnan(data))
subplots = [221, 222, 223, 224]
for sp in subplots:
    cgax, caax, paax, pm = wradlib.vis.plot_cg_rhi(ma,
                                                   r, th, rf=1e3, autoext=True,
                                                   refrac=False, subplot=sp)
    t = plt.title('CG RHI #%(sp)d' %locals())
    t.set_y(1.1)
    cgax.set_ylim(0, 15)
    cbar = plt.gcf().colorbar(pm, pad=0.125)
    caax.set_xlabel('range [km]')
    caax.set_ylabel('height [km]')
    gh = cgax.get_grid_helper()
    # set theta to some nice values
    gh.grid_finder.grid_locator1 = FixedLocator([0, 5, 10, 15, 20, 30, 40, 60, 90,])
    cbar.set_label('reflectivity [dBZ]')
plt.tight_layout()
plt.draw()
plt.show()
Пример #30
0
    rmesh = np.loadtxt(response.readlines())[::4]
    response.close()
    np.save('data/hmi_rmesh.npy', rmesh)

# rot2d has 49 columns, latitudes are 90-i*15/8; i starts at 0
lat = np.array([15./8.*i for i in np.arange(49)])/180.*np.pi
r, th = np.meshgrid(rmesh, lat)

# adapted from
# http://matplotlib.org/examples/axes_grid/demo_floating_axes.html
fig = pl.gcf()
tr = PolarAxes.PolarTransform()
angle_ticks = [(0.0, r"$0^\circ$"),
               (0.25*np.pi, r"$45^\circ$"),
               (0.5*np.pi, r"$90^\circ$")]
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=(0, 0.5*np.pi, 0, 1),
    grid_locator1=grid_locator1,
    grid_locator2=grid_locator2,
    tick_formatter1=tick_formatter1,
    tick_formatter2=None)

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

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