Example #1
0
 def annotate_frame(i):
     axes.set_title("{s.name}".format(s=self[i]))
     axes.set_xlabel(
         axis_labels_from_ctype(self[i].coordinate_system[0],
                                self[i].spatial_units[0]))
     axes.set_ylabel(
         axis_labels_from_ctype(self[i].coordinate_system[1],
                                self[i].spatial_units[1]))
Example #2
0
    def _annotate_plot(self, ind):
        """
        Annotate the image.

        This may overwrite some stuff in `GenericMap.plot()`
        """
        # Normal plot
        self.axes.set_title("{s.name}".format(s=self.data[ind]))

        self.axes.set_xlabel(axis_labels_from_ctype(self.data[ind].coordinate_system[0],
                                                    self.data[ind].spatial_units[0]))
        self.axes.set_ylabel(axis_labels_from_ctype(self.data[ind].coordinate_system[1],
                                                    self.data[ind].spatial_units[1]))
Example #3
0
    def _annotate_plot(self, ind):
        """
        Annotate the image.

        This may overwrite some stuff in `sunpy.map.GenericMap.plot`
        """
        # Normal plot
        self.axes.set_title("{s.name}".format(s=self.data[ind]))

        self.axes.set_xlabel(axis_labels_from_ctype(self.data[ind].coordinate_system[0],
                                                    self.data[ind].spatial_units[0]))
        self.axes.set_ylabel(axis_labels_from_ctype(self.data[ind].coordinate_system[1],
                                                    self.data[ind].spatial_units[1]))
Example #4
0
def plots(smaps):
    """
    Plot an image of the Sun in multiple wavelengths, up to nine per figure.

    Inputs:
        smaps: list of SunPy Map objects (up to nine)

    Outputs:
        None.
    """
    nmap = len(smaps)

    if (nmap < 1 or nmap > 9):
        raise Exception('Please input a valid number of smaps.')

    nc = int(np.ceil(np.sqrt(nmap)))
    nr = nc - 1 * (nmap <= (nc**2 - nc))

    fig, ax = plt.subplots(nr,
                           nc,
                           sharex=True,
                           sharey=True,
                           figsize=(2 * nc + 2, 2 * nr + 1))
    if nmap == 1:
        ax = np.array([ax])
        fig.set_size_inches(5, 4.5)  # prevent text overlap

    ax = ax.reshape(-1)

    # hide extra axes
    for i in range(nmap, nr * nc):
        ax[i].axis('off')

    add_plots(smaps, fig, ax)

    # share axis labels over the whole figure
    ylab = axis_labels_from_ctype(smaps[0].coordinate_system[1],
                                  smaps[0].spatial_units[1])
    xlab = axis_labels_from_ctype(smaps[0].coordinate_system[0],
                                  smaps[0].spatial_units[0])
    fig.text(0.5, 0.04, xlab, ha='center')
    fig.text(0.01, 0.5, ylab, va='center', rotation='vertical')

    title = 'AIA ' + smaps[0].meta.get('date').replace('T', ' ')[:-3]
    plt.suptitle(title)

    plt.show()
    return
Example #5
0
    def plot(
            self,
            axes=None,
            annotate=True,  # pylint: disable=W0613
            title="SunPy Composite Plot",
            **matplot_args):
        """Plots the composite map object using matplotlib

        Parameters
        ----------

        axes: `~matplotlib.axes.Axes` or None
            If provided the image will be plotted on the given axes. Else the
            current matplotlib axes will be used.

        annotate : `bool`
            If true, the data is plotted at it's natural scale; with
            title and axis labels.

        title : `str`
            Title of the composite map.

        **matplot_args : `dict`
            Matplotlib Any additional imshow arguments that should be used
            when plotting.

        Returns
        -------
        ret : `list`
            List of axes image or quad contour sets that have been plotted.
        """

        # Get current axes
        if not axes:
            axes = plt.gca()

        if annotate:
            axes.set_xlabel(
                axis_labels_from_ctype(self._maps[0].coordinate_system[0],
                                       self._maps[0].spatial_units[0]))
            axes.set_ylabel(
                axis_labels_from_ctype(self._maps[0].coordinate_system[1],
                                       self._maps[0].spatial_units[1]))

            axes.set_title(title)

        # Define a list of plotted objects
        ret = []
        # Plot layers of composite map
        for m in self._maps:
            # Parameters for plotting
            params = {
                "origin": "lower",
                "extent": list(m.xrange.value) + list(m.yrange.value),
                "cmap": m.plot_settings['cmap'],
                "norm": m.plot_settings['norm'],
                "alpha": m.alpha,
                "zorder": m.zorder,
            }
            params.update(matplot_args)

            if m.levels is False:
                ret.append(axes.imshow(m.data, **params))

            # Use contour for contour data, and imshow otherwise
            if m.levels is not False:
                # Set data with values <= 0 to transparent
                # contour_data = np.ma.masked_array(m, mask=(m <= 0))
                ret.append(axes.contour(m.data, m.levels, **params))
                # Set the label of the first line so a legend can be created
                ret[-1].collections[0].set_label(m.name)

        # Adjust axes extents to include all data
        axes.axis('image')

        # Set current image (makes colorbar work)
        plt.sci(ret[0])
        return ret
Example #6
0
    def plot(
            self,
            axes=None,
            annotate=True,  # pylint: disable=W0613
            title="SunPy Composite Plot",
            **matplot_args):
        """Plots the composite map object using matplotlib

        Parameters
        ----------

        axes: `~matplotlib.axes.Axes` or None
            If provided the image will be plotted on the given axes. Else the
            current matplotlib axes will be used.

        annotate : `bool`
            If true, the data is plotted at it's natural scale; with
            title and axis labels.

        title : `str`
            Title of the composite map.

        **matplot_args : `dict`
            Matplotlib Any additional imshow arguments that should be used
            when plotting.

        Returns
        -------
        ret : `list`
            List of axes image or quad contour sets that have been plotted.
        """

        # Get current axes
        if not axes:
            axes = plt.gca()

        if annotate:
            axes.set_xlabel(
                axis_labels_from_ctype(self._maps[0].coordinate_system[0],
                                       self._maps[0].spatial_units[0]))
            axes.set_ylabel(
                axis_labels_from_ctype(self._maps[0].coordinate_system[1],
                                       self._maps[0].spatial_units[1]))
            axes.set_title(title)

        # Define a list of plotted objects
        ret = []
        # Plot layers of composite map
        for m in self._maps:
            # Parameters for plotting
            bl = m._get_lon_lat(m.bottom_left_coord)
            tr = m._get_lon_lat(m.top_right_coord)
            x_range = list(
                u.Quantity([bl[0], tr[0]]).to(m.spatial_units[0]).value)
            y_range = list(
                u.Quantity([bl[1], tr[1]]).to(m.spatial_units[1]).value)
            params = {
                "origin": "lower",
                "extent": x_range + y_range,
                "cmap": m.plot_settings['cmap'],
                "norm": m.plot_settings['norm'],
                "alpha": m.alpha,
                "zorder": m.zorder,
            }
            params.update(matplot_args)

            # The request to show a map layer rendered as a contour is indicated by a
            # non False levels property.  If levels is False, then the layer is
            # rendered using imshow.
            if m.levels is False:
                # Check for the presence of masked map data
                if m.mask is None:
                    ret.append(axes.imshow(m.data, **params))
                else:
                    ret.append(
                        axes.imshow(
                            np.ma.array(np.asarray(m.data), mask=m.mask),
                            **params))
            else:
                # Check for the presence of masked map data
                if m.mask is None:
                    ret.append(axes.contour(m.data, m.levels, **params))
                else:
                    ret.append(
                        axes.contour(
                            np.ma.array(np.asarray(m.data), mask=m.mask),
                            m.levels, **params))

                # Set the label of the first line so a legend can be created
                ret[-1].collections[0].set_label(m.name)

        # Adjust axes extents to include all data
        axes.axis('image')

        # Set current image (makes colorbar work)
        plt.sci(ret[0])
        return ret
Example #7
0
    def plot(self, axes=None, annotate=True,  # pylint: disable=W0613
             title="SunPy Composite Plot", **matplot_args):
        """Plots the composite map object using matplotlib

        Parameters
        ----------

        axes: `~matplotlib.axes.Axes` or None
            If provided the image will be plotted on the given axes. Else the
            current matplotlib axes will be used.

        annotate : `bool`
            If true, the data is plotted at it's natural scale; with
            title and axis labels.

        title : `str`
            Title of the composite map.

        **matplot_args : `dict`
            Matplotlib Any additional imshow arguments that should be used
            when plotting.

        Returns
        -------
        ret : `list`
            List of axes image or quad contour sets that have been plotted.
        """

        # Get current axes
        if not axes:
            axes = plt.gca()

        if annotate:
            axes.set_xlabel(axis_labels_from_ctype(self._maps[0].coordinate_system[0],
                                                   self._maps[0].spatial_units[0]))
            axes.set_ylabel(axis_labels_from_ctype(self._maps[0].coordinate_system[1],
                                                   self._maps[0].spatial_units[1]))
            axes.set_title(title)

        # Define a list of plotted objects
        ret = []
        # Plot layers of composite map
        for m in self._maps:
            # Parameters for plotting
            bl = m._get_lon_lat(m.bottom_left_coord)
            tr = m._get_lon_lat(m.top_right_coord)
            x_range = list(u.Quantity([bl[0], tr[0]]).to(m.spatial_units[0]).value)
            y_range = list(u.Quantity([bl[1], tr[1]]).to(m.spatial_units[1]).value)
            params = {
                "origin": "lower",
                "extent": x_range + y_range,
                "cmap": m.plot_settings['cmap'],
                "norm": m.plot_settings['norm'],
                "alpha": m.alpha,
                "zorder": m.zorder,
            }
            params.update(matplot_args)

            # The request to show a map layer rendered as a contour is indicated by a
            # non False levels property.  If levels is False, then the layer is
            # rendered using imshow.
            if m.levels is False:
                # Check for the presence of masked map data
                if m.mask is None:
                    ret.append(axes.imshow(m.data, **params))
                else:
                    ret.append(axes.imshow(np.ma.array(np.asarray(m.data), mask=m.mask), **params))
            else:
                # Check for the presence of masked map data
                if m.mask is None:
                    ret.append(axes.contour(m.data, m.levels, **params))
                else:
                    ret.append(axes.contour(np.ma.array(np.asarray(m.data), mask=m.mask), m.levels, **params))

                # Set the label of the first line so a legend can be created
                ret[-1].collections[0].set_label(m.name)

        # Adjust axes extents to include all data
        axes.axis('image')

        # Set current image (makes colorbar work)
        plt.sci(ret[0])
        return ret
Example #8
0
 def annotate_frame(i):
     axes.set_title("{s.name}".format(s=self[i]))
     axes.set_xlabel(axis_labels_from_ctype(self[i].coordinate_system[0],
                                            self[i].spatial_units[0]))
     axes.set_ylabel(axis_labels_from_ctype(self[i].coordinate_system[1],
                                            self[i].spatial_units[1]))
Example #9
0
    def plot(self, axes=None, annotate=True,
             title="SunPy Composite Plot", **matplot_args):
        """Plots the composite map object by calling :meth:`~sunpy.map.GenericMap.plot`
        or :meth:`~sunpy.map.GenericMap.draw_contours`.

        By default, each map is plotted as an image.  If a given map has levels
        defined (via :meth:`~sunpy.map.CompositeMap.set_levels`), that map will instead
        be plotted as contours.

        Parameters
        ----------

        axes: `~matplotlib.axes.Axes` or None
            If provided the image will be plotted on the given axes. Else the
            current matplotlib axes will be used.

        annotate : `bool`
            If true, the data is plotted at it's natural scale; with
            title and axis labels.

        title : `str`
            Title of the composite map.

        **matplot_args : `dict`
            Any additional Matplotlib arguments that should be used
            when plotting.

        Returns
        -------
        ret : `list`
            List of axes image or quad contour sets that have been plotted.

        Notes
        -----
        If a line-width Matplotlib argument (``linewidth``, ``linewidths``, or ``lw``)
        is provided, it will apply only to those maps that are plotted as contours.

        If a transformation is required to overlay the maps with the correct
        alignment, the plot limits may need to be manually set because
        Matplotlib autoscaling may not work as intended.
        """

        # If axes are not provided, create a WCSAxes based on the first map
        if not axes:
            axes = wcsaxes_compat.gca_wcs(self._maps[0].wcs)

        if annotate:
            axes.set_xlabel(axis_labels_from_ctype(self._maps[0].coordinate_system[0],
                                                   self._maps[0].spatial_units[0]))
            axes.set_ylabel(axis_labels_from_ctype(self._maps[0].coordinate_system[1],
                                                   self._maps[0].spatial_units[1]))
            axes.set_title(title)

        # Define a list of plotted objects
        ret = []
        # Plot layers of composite map
        for m in self._maps:
            # Parameters for plotting
            params = {
                "alpha": m.alpha,
                "zorder": m.zorder,
            }
            params.update(matplot_args)

            # The request to show a map layer rendered as a contour is indicated by a
            # non False levels property.
            if m.levels is False:
                # Check if any linewidth argument is provided, if so, then delete it from params.
                for item in ['linewidth', 'linewidths', 'lw']:
                    if item in matplot_args:
                        del params[item]

                # We tell GenericMap.plot() that we need to autoalign the map
                if wcsaxes_compat.is_wcsaxes(axes):
                    params['autoalign'] = True

                params['annotate'] = False
                ret.append(m.plot(**params))
            else:
                ret.append(m.draw_contours(m.levels, **params))

                # Set the label of the first line so a legend can be created
                ret[-1].collections[0].set_label(m.name)

        # Adjust axes extents to include all data
        axes.axis('image')

        # Set current image (makes colorbar work)
        plt.sci(ret[0])
        return ret
Example #10
0
    def plot(self, axes=None, annotate=True,  # pylint: disable=W0613
             title="SunPy Composite Plot", **matplot_args):
        """Plots the composite map object using matplotlib

        Parameters
        ----------

        axes: `~matplotlib.axes.Axes` or None
            If provided the image will be plotted on the given axes. Else the
            current matplotlib axes will be used.

        annotate : `bool`
            If true, the data is plotted at it's natural scale; with
            title and axis labels.

        title : `str`
            Title of the composite map.

        **matplot_args : `dict`
            Matplotlib Any additional imshow arguments that should be used
            when plotting.

        Returns
        -------
        ret : `list`
            List of axes image or quad contour sets that have been plotted.
        """

        # Get current axes
        if not axes:
            axes = plt.gca()

        if annotate:
            axes.set_xlabel(axis_labels_from_ctype(self._maps[0].coordinate_system[0],
                                                   self._maps[0].spatial_units[0]))
            axes.set_ylabel(axis_labels_from_ctype(self._maps[0].coordinate_system[1],
                                                   self._maps[0].spatial_units[1]))

            axes.set_title(title)

        # Define a list of plotted objects
        ret = []
        # Plot layers of composite map
        for m in self._maps:
            # Parameters for plotting
            params = {
                "origin": "lower",
                "extent": list(m.xrange.value) + list(m.yrange.value),
                "cmap": m.plot_settings['cmap'],
                "norm": m.plot_settings['norm'],
                "alpha": m.alpha,
                "zorder": m.zorder,
            }
            params.update(matplot_args)

            if m.levels is False:
                ret.append(axes.imshow(m.data, **params))

            # Use contour for contour data, and imshow otherwise
            if m.levels is not False:
                # Set data with values <= 0 to transparent
                # contour_data = np.ma.masked_array(m, mask=(m <= 0))
                ret.append(axes.contour(m.data, m.levels, **params))
                # Set the label of the first line so a legend can be created
                ret[-1].collections[0].set_label(m.name)

        # Adjust axes extents to include all data
        axes.axis('image')

        # Set current image (makes colorbar work)
        plt.sci(ret[0])
        return ret
Example #11
0
    def plot(self, axes=None, annotate=True,
             title="SunPy Composite Plot", **matplot_args):
        """Plots the composite map object by calling :meth:`~sunpy.map.GenericMap.plot`
        or :meth:`~sunpy.map.GenericMap.draw_contours`.

        By default, each map is plotted as an image.  If a given map has levels
        defined (via :meth:`~sunpy.map.CompositeMap.set_levels`), that map will instead
        be plotted as contours.

        Parameters
        ----------

        axes: `~matplotlib.axes.Axes` or None
            If provided the image will be plotted on the given axes. Else the
            current matplotlib axes will be used.

        annotate : `bool`
            If true, the data is plotted at it's natural scale; with
            title and axis labels.

        title : `str`
            Title of the composite map.

        **matplot_args : `dict`
            Any additional Matplotlib arguments that should be used
            when plotting.

        Returns
        -------
        ret : `list`
            List of axes image or quad contour sets that have been plotted.

        Notes
        -----
        Images are plotted using either `~matplotlib.axes.Axes.imshow` or
        `~matplotlib.axes.Axes.pcolormesh`, and contours are plotted using
        `~matplotlib.axes.Axes.contour`.
        The Matplotlib arguments accepted by the plotting method are passed to it.
        (For compatability reasons, we enforce a more restrictive set of
        accepted `~matplotlib.axes.Axes.pcolormesh` arguments.)
        If any Matplotlib arguments are not used by any plotting method,
        a ``TypeError`` will be raised.
        The ``sunpy.map.compositemap`` module includes variables which list the
        full set of arguments passed to each plotting method. These are:

        >>> import sunpy.map.compositemap
        >>> sorted(sunpy.map.compositemap.ACCEPTED_IMSHOW_KWARGS)
        {ACCEPTED_IMSHOW_KWARGS}
        >>> sorted(sunpy.map.compositemap.ACCEPTED_PCOLORMESH_KWARGS)
        {ACCEPTED_PCOLORMESH_KWARGS}
        >>> sorted(sunpy.map.compositemap.ACCEPTED_CONTOUR_KWARGS)
        {ACCEPTED_CONTOUR_KWARGS}

        If a transformation is required to overlay the maps with the correct
        alignment, the plot limits may need to be manually set because
        Matplotlib autoscaling may not work as intended.
        """

        # If axes are not provided, create a WCSAxes based on the first map
        if not axes:
            axes = wcsaxes_compat.gca_wcs(self._maps[0].wcs)

        if annotate:
            axes.set_xlabel(axis_labels_from_ctype(self._maps[0].coordinate_system[0],
                                                   self._maps[0].spatial_units[0]))
            axes.set_ylabel(axis_labels_from_ctype(self._maps[0].coordinate_system[1],
                                                   self._maps[0].spatial_units[1]))
            axes.set_title(title)

        # Checklist to determine unused keywords in `matplot_args`
        unused_kwargs = set(matplot_args.keys())

        # Define a list of plotted objects
        ret = []
        # Plot layers of composite map
        for m in self._maps:
            # Parameters for plotting
            params = {
                "alpha": m.alpha,
                "zorder": m.zorder,
            }
            params.update(matplot_args)

            # The request to show a map layer rendered as a contour is indicated by a
            # non False levels property.
            if m.levels is False:
                # We tell GenericMap.plot() that we need to autoalign the map
                if wcsaxes_compat.is_wcsaxes(axes):
                    params['autoalign'] = True

                # Filter `matplot_args`
                if params.get('autoalign', None) in (True, 'pcolormesh'):
                    accepted_kwargs = ACCEPTED_PCOLORMESH_KWARGS
                else:
                    accepted_kwargs = ACCEPTED_IMSHOW_KWARGS
                for item in matplot_args.keys():
                    if item not in accepted_kwargs:
                        del params[item]
                    else:  # mark as used
                        unused_kwargs -= {item}

                params['annotate'] = False
                ret.append(m.plot(**params))
            else:
                # Filter `matplot_args`
                for item in matplot_args.keys():
                    if item not in ACCEPTED_CONTOUR_KWARGS:
                        del params[item]
                    else:  # mark as used
                        unused_kwargs -= {item}

                ret.append(m.draw_contours(m.levels, **params))

                # Set the label of the first line so a legend can be created
                ret[-1].collections[0].set_label(m.name)

        if len(unused_kwargs) > 0:
            raise TypeError(f'plot() got unexpected keyword arguments {unused_kwargs}')

        # Adjust axes extents to include all data
        axes.axis('image')

        # Set current image (makes colorbar work)
        plt.sci(ret[0])
        return ret