Exemple #1
0
    def _set_lim_and_transforms(self):
        """
        Overrides the method with the same name in the PolarAxes-class.

        This method replaces the same method in the PolarAxes-class. It ensures
        that the limits and label placement fit the north-polar projection.
        """
        PolarAxes._set_lim_and_transforms(self)
        self.transProjection = self.NorthPolarTransform()
        # pylint: attribute-defined-outside-init,invalid-name
        self.transData = (
            self.transScale + 
            self.transProjection + 
            (self.transProjectionAffine + self.transAxes))
        # pylint: attribute-defined-outside-init,invalid-name
        self._xaxis_transform = (
            self.transProjection +
            self.PolarAffine(IdentityTransform(), Bbox.unit()) +
            self.transAxes)  # pylint: attribute-defined-outside-init
        self._xaxis_text1_transform = (
            self._theta_label1_position +
            self._xaxis_transform)  # pylint: attribute-defined-outside-init
        self._yaxis_transform = (
            Affine2D().scale(np.pi * 2.0, 1.0) +
            self.transData)  # pylint: attribute-defined-outside-init
        self._yaxis_text1_transform = (
            Affine2D().scale(1.0 / 360.0, 1.0) +
            self._yaxis_transform)  # pylint: attribute-defined-outside-init
Exemple #2
0
        def _set_lim_and_transforms(self):
            PolarAxes._set_lim_and_transforms(self)
            try:
                theta_position = self._theta_label1_position
            except AttributeError:
                theta_position = self.get_theta_offset()

            self.transProjection = self.GlobeCrossSectionTransform()
            self.transData = (
                self.transScale +
                self.transProjection +
                (self.transProjectionAffine + self.transAxes))
            self._xaxis_transform = (
                self.transProjection +
                self.PolarAffine(IdentityTransform(), Bbox.unit()) +
                self.transAxes)
            self._xaxis_text1_transform = (
                theta_position +
                self._xaxis_transform)
            self._yaxis_transform = (
                Affine2D().scale(num.pi * 2.0, 1.0) +
                self.transData)

            try:
                rlp = getattr(self, '_r_label1_position')
            except AttributeError:
                rlp = getattr(self, '_r_label_position')

            self._yaxis_text1_transform = (
                rlp +
                Affine2D().scale(1.0 / 360.0, 1.0) +
                self._yaxis_transform)
	def _set_lim_and_transforms(self):
		PolarAxes._set_lim_and_transforms(self)
		self.transProjection = self.NorthPolarTransform()
		self.axisProjection = self.NorthPolarAxisTransform()
		self.transData = (
			Affine2D().scale(numpy.pi/180.0, 1.0/90.0) + 
			self.transScale + 
			self.transProjection + 
			(self.transProjectionAffine + self.transAxes))
		self._xaxis_pretransform = (
			Affine2D().scale(1.0, 1.0) )
		self._xaxis_transform = (
			self._xaxis_pretransform + 
			self.axisProjection +
			self.PolarAffine(IdentityTransform(), Bbox.unit()) +
			self.transAxes)
		self._xaxis_text1_transform = (
			self._theta_label1_position +
			self._xaxis_transform)
		self._yaxis_transform = (
			Affine2D().scale(numpy.pi*2.0, 1.0) + 
			self.transScale + 
			self.axisProjection + 
			(self.transProjectionAffine + self.transAxes))
		self._yaxis_text1_transform = (
			self._r_label1_position +
			Affine2D().translate(0.0, -0.051) +
			self._yaxis_transform)
Exemple #4
0
 def _set_lim_and_transforms(self):
     PolarAxes._set_lim_and_transforms(self)
     self.transProjection = self.GlobeCrossSectionTransform(GlobeCrossSectionAxes.RESOLUTION)
     self.transData = self.transScale + self.transProjection + (self.transProjectionAffine + self.transAxes)
     self._xaxis_transform = (
         self.transProjection + self.PolarAffine(IdentityTransform(), Bbox.unit()) + self.transAxes
     )
     self._xaxis_text1_transform = self._theta_label1_position + self._xaxis_transform
     self._yaxis_transform = Affine2D().scale(num.pi * 2.0, 1.0) + self.transData
     self._yaxis_text1_transform = (
         self._r_label1_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform
     )
 def _set_lim_and_transforms(self):
     PolarAxes._set_lim_and_transforms(self)
     self.transProjection = self.NorthPolarTransform()
     self.transData = (
         self.transScale + 
         self.transProjection + 
         (self.transProjectionAffine + self.transAxes))
     self._xaxis_transform = (
         self.transProjection +
         self.PolarAffine(IdentityTransform(), Bbox.unit()) +
         self.transAxes)
     self._xaxis_text1_transform = (
         self._theta_label1_position +
         self._xaxis_transform)
     self._yaxis_transform = (
         Affine2D().scale(np.pi * 2.0, 1.0) +
         self.transData)
Exemple #6
0
 def _set_lim_and_transforms(self):
     """
     """
     PolarAxes._set_lim_and_transforms(self)
     self.transProjection = self.DipPolarTransform()
     # pylint: attribute-defined-outside-init,invalid-name
     self.transData = (
         self.transScale +
         self.transProjection +
         (self.transProjectionAffine + self.transAxes))
     # pylint: attribute-defined-outside-init,invalid-name
     self._xaxis_transform = (
         self.transProjection +
         self.PolarAffine(IdentityTransform(), Bbox.unit()) +
         self.transAxes)  # pylint: attribute-defined-outside-init
     self._xaxis_text1_transform = (
         self._theta_label1_position +
         self._xaxis_transform)  # pylint: attribute-defined-outside-init
     self._yaxis_transform = (
         Affine2D().scale(np.pi * 2.0, 1.0) +
         self.transData)  # pylint: attribute-defined-outside-init
     self._yaxis_text1_transform = (
         Affine2D().scale(1.0 / 360.0, 1.0) +
         self._yaxis_transform)  # pylint: attribute-defined-outside-init
Exemple #7
0
def curvelinear_test2(fig):
    """
    Polar projection, but in a rectangular box.
    """

    # PolarAxes.PolarTransform takes radian. However, we want our coordinate
    # system in degree
    tr = Affine2D().scale(np.pi / 180, 1) + PolarAxes.PolarTransform()
    # Polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).
    extreme_finder = angle_helper.ExtremeFinderCycle(
        nx=20,
        ny=20,  # Number of sampling points in each direction.
        lon_cycle=360,
        lat_cycle=None,
        lon_minmax=None,
        lat_minmax=(0, np.inf),
    )
    # Find grid values appropriate for the coordinate (degree, minute, second).
    grid_locator1 = angle_helper.LocatorDMS(12)
    # Use an appropriate formatter.  Note that the acceptable Locator and
    # Formatter classes are a bit different than that of Matplotlib, which
    # cannot directly be used here (this may be possible in the future).
    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1)
    ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper)

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)
    # let right axis shows ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks = 0
    # let bottom axis shows ticklabels for 2nd coordinate (radius)
    ax1.axis["bottom"].get_helper().nth_coord_ticks = 1

    fig.add_subplot(ax1)

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

    ax1.grid(True, zorder=0)

    # A parasite axes with given transform
    ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
    # note that ax2.transData == tr + ax1.transData
    # Anything you draw in ax2 will match the ticks and grids of ax1.
    ax1.parasites.append(ax2)
    ax2.plot(np.linspace(0, 30, 51), np.linspace(10, 10, 51), linewidth=2)

    ax2.pcolor(np.linspace(0, 90, 4), np.linspace(0, 10, 4),
               np.arange(9).reshape((3, 3)))
    ax2.contour(np.linspace(0, 90, 4),
                np.linspace(0, 10, 4),
                np.arange(16).reshape((4, 4)),
                colors="k")
Exemple #8
0
def create_cg(
    fig=None,
    subplot=111,
    rot=-450,
    scale=-1,
    angular_spacing=10,
    radial_spacing=10,
    latmin=0,
    lon_cycle=360,
):
    """ Helper function to create curvelinear grid

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

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

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

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

    tr = tr_rotate + tr_scale + tr_polar

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

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

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

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

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

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

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

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

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

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

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

    return cgax, caax, paax
Exemple #9
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, '{}_chart.png'.format(name)),
                    transparent=False,
                    bbox_inches='tight',
                    pad_inches=0.1,
                    dpi=dpi)

    if color_limits:
        return 1., new_data_angle_dist.max()
Exemple #10
0
def get_smith(fig,
              rect=111,
              plot_impedance=True,
              plot_ticks=False,
              plot_admittance=False,
              plot_labels=False):
    '''Function which returns an axis with a blank smith chart, provide a figure and optional rect coords'''

    #Example use:

    # fig3 = plt.figure(3)
    # ax31 = pySmith.get_smith(fig3, 221)
    # ax31.plot(np.real(filtsmatrix[0,:,0,0]),np.imag(filtsmatrix[0,:,0,0]))
    # ax32= pySmith.get_smith(fig3, 222)
    # ax32.plot(np.real(filtsmatrix[0,:,0,1]),np.imag(filtsmatrix[0,:,0,1]))
    # ax33 = pySmith.get_smith(fig3, 223)
    # ax33.plot(np.real(filtsmatrix[0,:,1,0]),np.imag(filtsmatrix[0,:,1,0]))
    # ax34 = pySmith.get_smith(fig3, 224)
    # ax34.plot(np.real(filtsmatrix[0,:,1,1]),np.imag(filtsmatrix[0,:,1,1]))
    try:
        #font definition
        font = {
            'family': 'sans-serif',
            'color': 'black',
            'weight': 'normal',
            'size': 16,
        }

        #plot radial tick marks
        tr = PolarAxes.PolarTransform()
        num_thetas = 8  #*3 #12 gives in 30 deg intervals, 8 in 45 deg, 24 in 15deg
        thetas = np.linspace(0.0, math.pi * (1 - 2.0 / num_thetas),
                             num_thetas // 2)
        angle_ticks = []  #(0, r"$0$"),
        for theta in thetas:
            angle_info = []
            angle_info.append(theta)
            deg = int(round(180.0 * theta / math.pi))
            angle_info.append(r'%d$^{\circ}$' % deg)
            angle_ticks.append(angle_info)
        grid_locator1 = FixedLocator([v for v, s in angle_ticks])
        tick_formatter1 = DictFormatter(dict(angle_ticks))
        thetas2 = np.linspace(math.pi, 2 * math.pi * (1 - 1.0 / num_thetas),
                              num_thetas // 2)
        angle_ticks2 = []  #(0, r"$0$"),
        for theta in thetas2:
            angle_info = []
            angle_info.append(theta)
            deg = int(round(180.0 * theta / math.pi))
            angle_info.append(r'%d$^{\circ}$' % deg)
            angle_ticks2.append(angle_info)
        grid_locator2 = FixedLocator([v for v, s in angle_ticks2])
        tick_formatter2 = DictFormatter(dict(angle_ticks2))

        grid_helper1 = floating_axes.GridHelperCurveLinear(
            tr,
            extremes=(math.pi, 0, 1, 0),
            grid_locator1=grid_locator1,
            #grid_locator2=grid_locator2,
            tick_formatter1=tick_formatter1  #,
            #tick_formatter2=None,
        )

        grid_helper2 = floating_axes.GridHelperCurveLinear(
            tr,
            extremes=(2 * math.pi, math.pi, 1, 0),
            grid_locator1=grid_locator2,
            #grid_locator2=grid_locator2,
            tick_formatter1=tick_formatter2  #,
            #tick_formatter2=None,
        )

        r1 = int(math.floor(rect / 100))
        r2 = int(math.floor((rect - 100 * r1) / 10))
        r3 = int(math.floor((rect - 100 * r1 - 10 * r2)))
        ax = SubplotHost(fig, r1, r2, r3, grid_helper=grid_helper1)
        ax2 = SubplotHost(fig, r1, r2, r3, grid_helper=grid_helper2)
        #ax.set_aspect(math.pi/180.0,'datalim')
        fig.add_subplot(ax)
        fig.add_subplot(ax2)

        ax.axis["bottom"].major_ticklabels.set_axis_direction("top")
        ax.axis["bottom"].major_ticklabels.set_fontsize(13)
        ax.axis["left"].set_visible(False)
        ax.axis["left"].toggle(all=False)
        ax.axis["right"].set_visible(False)
        ax.axis["right"].toggle(all=False)
        ax.axis["top"].set_visible(False)
        ax.axis["top"].toggle(all=False)
        ax.patch.set_visible(False)

        ax2.axis["bottom"].major_ticklabels.set_fontsize(13)
        ax2.axis["left"].set_visible(False)
        ax2.axis["left"].toggle(all=False)
        ax2.axis["right"].set_visible(False)
        ax2.axis["right"].toggle(all=False)
        ax2.axis["top"].set_visible(False)
        ax2.axis["top"].toggle(all=False)

        #ax = fig.add_subplot(rect)

        #remove axis labels
        ax.axis('off')
        #set aspect ratio to 1
        ax.set_aspect(1)  #, 'datalim')
        #set limits
        ax.set_xlim([-1.02, 1.02])
        ax.set_ylim([-1.02, 1.02])
        #remove axis labels
        ax2.axis('off')
        #set aspect ratio to 1
        ax2.set_aspect(1)  #,'datalim')
        #set limits
        ax2.set_xlim([-1.02, 1.02])
        ax2.set_ylim([-1.02, 1.02])
        ax2.patch.set_visible(False)
        if plot_impedance:
            #make lines of constant resistance
            res_log = np.linspace(-4, 4, 9)
            react_log = np.linspace(-5, 5, 2001)
            res = 2**res_log
            react = 10**react_log
            react2 = np.append(-1.0 * react[::-1], np.array([0]))
            react = np.append(react2, react)
            for r in res:
                z = 1j * react + r
                gam = (z - 1) / (z + 1)
                x = np.real(gam)
                y = np.imag(gam)
                if abs(r - 1) > 1e-6:
                    ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25)
                else:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4)
            #make lines of constant reactance
            react_log = np.linspace(-3, 3, 7)
            res_log = np.linspace(-5, 5, 2001)
            res = 10**res_log
            react = 2**react_log
            react2 = np.append(-1.0 * react[::-1], np.array([0]))
            react = np.append(react2, react)
            for chi in react:
                z = 1j * chi + res
                gam = (z - 1) / (z + 1)
                x = np.real(gam)
                y = np.imag(gam)
                if abs(chi - 1) > 1e-6 and abs(chi +
                                               1) > 1e-6 and abs(chi) > 1e-6:
                    ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25)
                else:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4)
        if plot_admittance:
            #make lines of constant conductance
            res_log = np.linspace(-4, 4, 9)
            react_log = np.linspace(-5, 5, 2001)
            res = 2**res_log
            react = 10**react_log
            react = np.append(-1.0 * react[::-1], react)
            for r in res:
                y = 1.0 / r + 1.0 / (1j * react)
                gam = (1.0 / y - 1) / (1.0 / y + 1)
                x = np.real(gam)
                y = np.imag(gam)
                if abs(r - 1) > 1e-6:
                    ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25)
                else:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4)
            #make lines of constant susceptance
            react_log = np.linspace(-3, 3, 7)
            res_log = np.linspace(-5, 5, 2001)
            res = 10**res_log
            react = 2**react_log
            react = np.append(-1.0 * react[::-1], react)
            for chi in react:
                y = 1.0 / (1j * chi) + 1.0 / res
                gam = (1.0 / y - 1) / (1.0 / y + 1)
                x = np.real(gam)
                y = np.imag(gam)
                if abs(chi - 1) > 1e-6 and abs(chi + 1) > 1e-6:
                    ax.plot(x, y, c='k', linewidth=0.75, alpha=0.25)
                else:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=0.4)
            y = 1.0 / res
            gam = (1.0 / y - 1) / (1.0 / y + 1)
            x = np.real(gam)
            y = np.imag(gam)
            ax.plot(x, y, c='k', linewidth=1.0, alpha=0.75)
        if plot_labels:
            #naive text placement only works for default python figure size with 1 subplot
            ax.text(-0.15, 1.04, r'$\Gamma$ = 1j', fontdict=font)
            ax.text(-1.4, -0.035, r'$\Gamma$ = -1', fontdict=font)
            ax.text(-0.17, -1.11, r'$\Gamma$ = -1j', fontdict=font)
            ax.text(1.04, -0.035, r'$\Gamma$ = 1', fontdict=font)
        if plot_ticks:
            num_minorticks = 3
            num_thetas = num_thetas * (num_minorticks + 1)
            thetas = np.linspace(0, 2.0 * math.pi * (1.0 - 1.0 / num_thetas),
                                 num_thetas)
            r_inner = 0.985
            r_outer = 1.0
            rads = np.linspace(r_inner, r_outer, 2)
            ticknum = 0
            for theta in thetas:
                x = rads * np.cos(theta)
                y = rads * np.sin(theta)
                if ticknum % (num_minorticks + 1) != 0:
                    ax.plot(x, y, c='k', linewidth=1.0, alpha=1.0)
                ticknum = ticknum + 1

        return ax
    except Exception as e:
        print('\nError in %s' % inspect.stack()[0][3])
        print(e)
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
	def __init__(self, *args, **kwargs):
		self.lon_degs = 45
		self.lat_degs = 15
		PolarAxes.__init__(self, *args, **kwargs)
    def __init__(self, refstd, fig=None, rect=111, label='_'):
        """
        Set up Taylor diagram axes, i.e. single quadrant polar
        plot, using mpl_toolkits.axisartist.floating_axes. refstd is
        the reference standard deviation to be compared to.

        """

        from matplotlib.projections import PolarAxes
        from mpl_toolkits.axisartist import floating_axes
        from mpl_toolkits.axisartist import grid_finder

        self.refstd = refstd  # Reference standard deviation.

        tr = PolarAxes.PolarTransform()

        # Correlation labels.
        rlocs = np.concatenate((np.arange(10)/10., [0.95, 0.99]))
        tlocs = np.arccos(rlocs)  # Conversion to polar angles.
        gl1 = grid_finder.FixedLocator(tlocs)  # Positions.
        dict_formatter = {
            list(zip(tlocs, map(str, rlocs)))
            }
        tf1 = grid_finder.DictFormatter(dict_formatter)

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

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

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

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

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

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

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

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

        # Contours along standard deviations.
        ax.grid(False)

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

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

        # Collect sample points for latter use (e.g. legend).
        self.samplePoints = [l]
Exemple #13
0
 def cla(self):
     PolarAxes.cla(self)
     self.set_thetagrids([0, 15, 30, 45, 60, 75, 90])
Exemple #14
0
def TaylorDiagram(stddev,
                  corrcoef,
                  refstd,
                  fig,
                  colors,
                  normalize=True,
                  position=111):
    """Plot a Taylor diagram.

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

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

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

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

    # define transform
    tr = PolarAxes.PolarTransform()

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

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

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

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

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

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

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

    return ax, aux
def fractional_polar_axes(f, thlim=(0, 180), rlim=(0, 1), step=(30, 0.2),
                          thlabel=None, rlabel=None, ticklabels=False):
    """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.)
    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()
    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
Exemple #16
0
def curvelinear_test2(fig):
    """
    polar projection, but in a rectangular box.
    """

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

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

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

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

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

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

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

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

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

    fig.add_subplot(ax1)

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

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

    ax1.grid(True)
Exemple #17
0
def Taylor_diag(series,names):
    """ Taylor Diagram : obs is reference data sample
        in a full diagram (0 --> npi)
        --------------------------------------------------------------------------
        Input: series     - dict with all time series (lists) to analyze  
               series[0]  - is the observation, the reference by default.
    """
    from matplotlib.projections import PolarAxes
    corr,std ={},{}
    for i in series.keys():
        corr[i] = ma.corrcoef(series[0],series[i])[1,0]
        std[i] = ma.std(series[i])/ma.std(series[0])
       
    ref = 1# ma.std(series[0])
    #print corr
    
    rlocs = np.concatenate((np.arange(0,-10,-0.25),[-0.95,-0.99],np.arange(0,10,0.25),[0.95,0.99]))
    str_rlocs = np.concatenate((np.arange(0,10,0.25),[0.95,0.99],np.arange(0,10,0.25),[0.95,0.99]))
    tlocs = np.arccos(rlocs)        # Conversion to polar angles
    gl1 = GF.FixedLocator(tlocs)    # Positions
    tf1 = GF.DictFormatter(dict(zip(tlocs, map(str,rlocs))))
    

    str_locs2 = np.arange(-10,11,0.5)
    tlocs2 =  np.arange(-10,11,0.5)      # Conversion to polar angles
       
    g22 = GF.FixedLocator(tlocs2)  
    tf2 = GF.DictFormatter(dict(zip(tlocs2, map(str,str_locs2))))

    
    
    
    tr = PolarAxes.PolarTransform()
    
    smin = 0
    smax = 2.5

    ghelper = FA.GridHelperCurveLinear(tr,
                                           extremes=(0,np.pi, # 1st quadrant
                                                     smin,smax),
                                           grid_locator1=gl1,
                                           #grid_locator2=g11,
                                           tick_formatter1=tf1,
                                           tick_formatter2=tf2,
                                           )
    fig = plt.figure(figsize=(10,5), dpi=100)
    ax = FA.FloatingSubplot(fig, 111, grid_helper=ghelper)

    fig.add_subplot(ax)
    ax.axis["top"].set_axis_direction("bottom") 
    ax.axis["top"].toggle(ticklabels=True, label=True)
    ax.axis["top"].major_ticklabels.set_axis_direction("top")
    ax.axis["top"].label.set_axis_direction("top")
    ax.axis["top"].label.set_text("Correlation Coefficient")

    ax.axis["left"].set_axis_direction("bottom") 
    ax.axis["left"].label.set_text("Standard Deviation")

    ax.axis["right"].set_axis_direction("top") 
    ax.axis["right"].toggle(ticklabels=True, label=True)
    ax.axis["right"].set_visible(True)
    ax.axis["right"].major_ticklabels.set_axis_direction("bottom")
    #ax.axis["right"].label.set_text("Standard Deviation")

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

    ax.grid(True)

    ax = ax.get_aux_axes(tr)

    t = np.linspace(0, np.pi)
    r = np.zeros_like(t) + ref
    ax.plot(t,r, 'k--', label='_')


    rs,ts = np.meshgrid(np.linspace(smin,smax),
                            np.linspace(0,np.pi))

    
    rms = np.sqrt(ref**2 + rs**2 - 2*ref*rs*np.cos(ts))
    CS =ax.contour(ts, rs,rms,cmap=cm.bone)
    plt.clabel(CS, inline=1, fontsize=10)
    

    ax.plot(np.arccos(0.9999),ref,'k',marker='*',ls='', ms=10)
    aux = range(1,len(corr))
    #del aux[ref]


    
    colors = plt.matplotlib.cm.jet(np.linspace(0,1,len(corr)))
    
    for i in aux:
        ax.plot(np.arccos(corr[i]), std[i],c=colors[i],alpha=0.7,marker='o',label="%s" %names[i])
        ax.text(np.arccos(corr[i]), std[i],"%s"%i)
    legend(bbox_to_anchor=(1.5, 1),prop=dict(size='large'),loc='best')
    plt.savefig('example.png', dpi=500)
    return
def curvelinear_test3(fig):
    """
    polar projection, but in a rectangular box.
    """
    global ax1, axis
    import numpy as np
    import  angle_helper
    from matplotlib.projections import PolarAxes
    from matplotlib.transforms import Affine2D

    from mpl_toolkits.axes_grid.parasite_axes import SubplotHost

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

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

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

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

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

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


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

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

    fig.add_subplot(ax1)

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



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

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

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


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

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

    ax1.grid(True)
Exemple #19
0
    def __init__(self,
                 refstd,
                 fig=None,
                 rect=111,
                 label='_',
                 srange=(0, 1.5),
                 extend=False):
        """
        Set up Taylor diagram axes, i.e. single quadrant polar
        plot, using `mpl_toolkits.axisartist.floating_axes`.
        Parameters:
        * refstd: reference standard deviation to be compared to
        * fig: input Figure or None
        * rect: subplot definition
        * label: reference label
        * srange: stddev axis extension, in units of *refstd*
        * extend: extend diagram to negative correlations
        """
        from matplotlib.projections import PolarAxes
        import mpl_toolkits.axisartist.floating_axes as FA
        import mpl_toolkits.axisartist.grid_finder as GF
        import matplotlib.pyplot as plt
        self.refstd = refstd  # Reference standard deviation
        tr = PolarAxes.PolarTransform()
        rlocs = np.array([0, 0.2, 0.5, 0.7, 0.8, 0.9, 0.95, 0.99, 1])
        if extend:  # Diagram extended to negative correlations
            self.tmax = np.pi
            rlocs = np.concatenate((-rlocs[:0:-1], rlocs))
        else:
            self.tmax = np.pi / 2
        tlocs = np.arccos(rlocs)  # Conversion to polar angles
        gl1 = GF.FixedLocator(tlocs)  # Positions
        tf1 = GF.DictFormatter(dict(zip(tlocs, map(str, rlocs))))

        # Standard deviation axis extent (in units of reference stddev)
        self.smin = srange[0] * self.refstd
        self.smax = srange[1] * self.refstd
        ghelper = FA.GridHelperCurveLinear(tr,
                                           extremes=(0, self.tmax, self.smin,
                                                     self.smax),
                                           grid_locator1=gl1,
                                           tick_formatter1=tf1)
        if fig is None: fig = plt.figure()
        ax = FA.FloatingSubplot(fig, rect, grid_helper=ghelper)
        fig.add_subplot(ax)
        ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
        ax.axis["top"].toggle(ticklabels=True, label=True)
        ax.axis["top"].major_ticklabels.set_axis_direction("top")
        ax.axis["top"].label.set_axis_direction("top")
        ax.axis["top"].label.set_text("Correlation")
        ax.axis["left"].set_axis_direction("bottom")  # "X axis"
        ax.axis["left"].label.set_text("Standard deviation")
        ax.axis["left"].toggle(ticklabels=False)
        ax.axis["right"].set_axis_direction("top")  # "Y-axis"
        ax.axis["right"].toggle(ticklabels=True)
        ax.axis["right"].major_ticklabels.set_axis_direction(
            "bottom" if extend else "left")
        if self.smin:
            ax.axis["bottom"].toggle(ticklabels=False, label=False)
        else:
            ax.axis["bottom"].set_visible(False)  # Unused
        self._ax = ax  # Graphical axes
        self.ax = ax.get_aux_axes(tr)  # Polar coordinates
        # Add reference point and stddev contour
        l, = self.ax.plot([0],
                          self.refstd,
                          'k*',
                          ls='',
                          ms=10,
                          label=label,
                          clip_on=False)
        t = np.linspace(0, self.tmax)
        r = np.zeros_like(t) + self.refstd
        self.ax.plot(t, r, 'k--', label='_')
        # Collect sample points for latter use (e.g. legend)
        self.samplePoints = [l]
Exemple #20
0
    def __init__(self, refstd, fig=None, rect=111, label='_', srange=(0, 1.5)):
        """
        Set up Taylor diagram axes, i.e. single quadrant polar
        plot, using `mpl_toolkits.axisartist.floating_axes`.

        Parameters:

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

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

        self.refstd = refstd            # Reference standard deviation

        tr = PolarAxes.PolarTransform()

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

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

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

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

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

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

        ax.axis["left"].set_axis_direction("bottom")  # "X axis"
        ax.axis["left"].label.set_text("Desviación estándar")

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

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

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

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

        # Collect sample points for latter use (e.g. legend)
        self.samplePoints = [l]
Exemple #21
0
def test_axis_direction():
    # Remove this line when this test image is regenerated.
    plt.rcParams['text.kerning_factor'] = 6

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

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

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

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

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

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

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

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

    fig.add_subplot(ax1)

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

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

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

    grid_helper.grid_finder.grid_locator1.set_params(nbins=5)
    grid_helper.grid_finder.grid_locator2.set_params(nbins=5)

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

    ax1.grid(True)
def Taylor_diag(series, names, styles, colors):
    """ Taylor Diagram : obs is reference data sample
        in a full diagram (0 --> npi)
        --------------------------------------------------------------------------
        Input: series     - dict with all time series (lists) to analyze  
               series[0]  - is the observation, the reference by default.
    """
    from matplotlib.projections import PolarAxes
    taylor_stats = np.array([
        AnDA_Taylor_stats(series[i], series[list(series.keys())[0]])
        for i in series.keys()
    ])
    crmsd, corr, std = taylor_stats.T
    ref = std[0]
    rlocs = np.concatenate((np.arange(0, 10, 0.25), [0.95, 0.99]))
    str_rlocs = np.concatenate((np.arange(0, 10, 0.25), [0.95, 0.99]))
    tlocs = np.arccos(rlocs)  # Conversion to polar angles
    gl1 = GF.FixedLocator(tlocs)  # Positions
    tf1 = GF.DictFormatter(dict(zip(tlocs, map(str, rlocs))))
    str_locs2 = np.arange(0, 11, 0.5)
    tlocs2 = np.arange(0, 11, 0.5)  # Conversion to polar angles
    g22 = GF.FixedLocator(tlocs2)
    tf2 = GF.DictFormatter(dict(zip(tlocs2, map(str, str_locs2))))
    tr = PolarAxes.PolarTransform()
    smin = 0
    smax = (120 / 100) * np.max(std)
    ghelper = FA.GridHelperCurveLinear(
        tr,
        extremes=(
            0,
            np.pi / 2,  # 1st quadrant
            smin,
            smax),
        grid_locator1=gl1,
        #grid_locator2=g11,
        tick_formatter1=tf1,
        tick_formatter2=tf2,
    )
    fig = plt.figure(figsize=(10, 5), dpi=100)
    ax = FA.FloatingSubplot(fig, 111, grid_helper=ghelper)
    fig.add_subplot(ax)
    ax.axis["top"].set_axis_direction("bottom")
    ax.axis["top"].toggle(ticklabels=True, label=True)
    ax.axis["top"].major_ticklabels.set_axis_direction("top")
    ax.axis["top"].label.set_axis_direction("top")
    ax.axis["top"].label.set_text("Correlation Coefficient")
    ax.axis["left"].set_axis_direction("bottom")
    ax.axis["left"].label.set_text("Standard Deviation")
    ax.axis["right"].set_axis_direction("top")
    ax.axis["right"].toggle(ticklabels=True, label=True)
    ax.axis["right"].set_visible(True)
    ax.axis["right"].major_ticklabels.set_axis_direction("bottom")
    ax.axis["right"].label.set_text("Standard Deviation")
    ax.axis["bottom"].set_visible(False)
    ax.grid(True)
    ax = ax.get_aux_axes(tr)
    t = np.linspace(0, np.pi / 2)
    r = np.zeros_like(t) + ref
    ax.plot(t, r, 'k--', label='_')
    rs, ts = np.meshgrid(np.linspace(smin, smax), np.linspace(0, np.pi / 2))
    rms = np.sqrt(ref**2 + rs**2 - 2 * ref * rs * np.cos(ts))
    CS = ax.contour(ts, rs, rms, cmap=cm.bone)
    plt.clabel(CS, inline=1, fontsize=10)
    ax.plot(np.arccos(0.9999), ref, 'k', marker='*', ls='', ms=10)
    aux = range(1, len(corr))
    #colors = plt.matplotlib.cm.jet(np.linspace(0,1,len(corr)))
    for i in reversed(aux):
        ax.plot(np.arccos(corr[i]),
                std[i],
                c=colors[i],
                alpha=0.7,
                marker=styles[i],
                label="%s" % names[i])
        #ax.text(np.arccos(corr[i]), std[i],"%s"%i)
    # inset axes....
    '''axins = ax.inset_axes([1.1, 0, 0.3, 0.3])
    def pol2cart(phi, rho):
        x = rho * np.cos(phi)
        y = rho * np.sin(phi)
        return(x, y)
    x = np.empty(len(aux))
    y = np.empty(len(aux))
    for i in reversed(aux):
        x[i-1], y[i-1] = pol2cart(np.arccos(corr[i]), std[i]) 
        axins.plot(x[i-1], y[i-1], c=colors[i],alpha=0.7,marker=styles[i],label="%s" %names[i])
        #axins.text(x[i-1], y[i-1],"%s"%i)
    # sub region of the original image
    x1, x2, y1, y2 = np.min(x)-(1/50)*np.min(x), np.max(x)+(1/50)*np.max(x),\
                     np.min(y)-(1)*np.min(y), np.max(y)+(1)*np.max(y)
    axins.set_xlim(x1,x2)
    axins.set_ylim(y1,y2)
    axins.set_xticks([])
    axins.set_yticks([])
    axins.set_xticklabels('')
    axins.set_yticklabels('')'''
    plt.legend(bbox_to_anchor=(1.5, 1), prop=dict(size='small'), loc='best')
Exemple #23
0
def curvelinear_test4(fig):
    """
    polar projection, but in a rectangular box.
    """
    global ax1, axis
    import numpy as np
    import  angle_helper
    from matplotlib.projections import PolarAxes

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

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

    from grid_finder import FixedLocator
    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)


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

    fig.add_subplot(ax1)


    #ax1.grid(True)


    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)


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


    ax2 = ax1.get_aux_axes(tr)

    xx, yy = [67, 90, 75, 30], [2, 5, 8, 4]
    ax2.scatter(xx, yy)
    l, = ax2.plot(xx, yy, "k-")
    l.set_clip_path(ax1.patch)
	def set_xlim(self, *args, **kwargs):
		"""
		Override set_xlim and set_ylim to be between -pi, pi and 0, 1.0
		"""
		PolarAxes.set_xlim(self, -2*numpy.pi, 2*numpy.pi)
		PolarAxes.set_ylim(self, 0, 1)
Exemple #25
0
def curvelinear_test3(fig):
    """
    polar projection, but in a rectangular box.
    """
    global ax1, axis
    import numpy as np
    import angle_helper
    from matplotlib.projections import PolarAxes

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

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


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

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

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


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

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


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

    fig.add_subplot(ax1)


    #ax1.grid(True)


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

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

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


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


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


    ax2 = ax1.get_aux_axes(tr)

    xx, yy = [67, 90, 75, 30], [2, 5, 8, 4]
    ax2.scatter(xx, yy)
    l, = ax2.plot(xx, yy, "k-")
    l.set_clip_path(ax1.patch)
Exemple #26
0
def test_polar_box():
    # Remove this line when this test image is regenerated.
    plt.rcParams['text.kerning_factor'] = 6

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

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

    # polar projection, which involves cycle, and also has limits in
    # its coordinates, needs a special method to find the extremes
    # (min, max of the coordinate within the view).
    extreme_finder = angle_helper.ExtremeFinderCycle(20,
                                                     20,
                                                     lon_cycle=360,
                                                     lat_cycle=None,
                                                     lon_minmax=None,
                                                     lat_minmax=(0, np.inf))

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

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

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

    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)

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

    fig.add_subplot(ax1)

    ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 45, axes=ax1)
    axis.label.set_text("Test")
    axis.label.set_visible(True)
    axis.get_helper().set_extremes(2, 12)

    ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 6, axes=ax1)
    axis.label.set_text("Test 2")
    axis.get_helper().set_extremes(-180, 90)

    # A parasite axes with given transform
    ax2 = ParasiteAxes(ax1, tr, viewlim_mode="equal")
    assert ax2.transData == tr + ax1.transData
    # Anything you draw in ax2 will match the ticks and grids of ax1.
    ax1.parasites.append(ax2)
    ax2.plot(np.linspace(0, 30, 50), np.linspace(10, 10, 50))

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

    ax1.grid(True)
Exemple #27
0
        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()
    
#%%
    
taylor(skillscores)
    
#%% Create a plotting function. In this case for Taylor diagrams.

    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))))
    
    STDgrid=np.arange(0,np.round(skillscores.OSTD[0]+1,1),.5)
    gfs=FixedLocator(STDgrid)
    tfs=DictFormatter(dict(zip(STDgrid, map(str,STDgrid))))
    
    ra0, ra1 =0, np.pi/2
    cz0, cz1 = 0, np.round(skillscores.OSTD[0]+1,1)
    grid_helper = floating_axes.GridHelperCurveLinear(
        tr, extremes=(ra0, ra1, cz0, cz1),
        grid_locator1=gf,