Пример #1
0
    def plot_interactive(self, ax=None, fig=None, **kwargs):
        """
        Plot ND array on matplotlib WCS axes with interactive widgets
        to explore the non spatial axes.

        Parameters
        ----------
        ax : `~astropy.visualization.wcsaxes.WCSAxes`, optional
            WCS axis object to plot on.
        fig : `~matplotlib.figure.Figure`
            Figure object.
        **kwargs : dict
            Keyword arguments passed to `~matplotlib.pyplot.imshow`.

        Examples
        --------

        You can try this out e.g. using a Fermi-LAT diffuse model cube with an energy axis::

            %matplotlib inline
            from gammapy.maps import Map

            m = Map.read("$GAMMAPY_EXTRA/datasets/vela_region/gll_iem_v05_rev1_cutout.fits")
            m.plot_interactive(cmap='gnuplot2')
        """
        import matplotlib.pyplot as plt
        from astropy.visualization import simple_norm
        from ipywidgets.widgets.interaction import interact, fixed
        import ipywidgets as widgets

        kwargs.setdefault('interpolation', 'nearest')
        kwargs.setdefault('origin', 'lower')
        kwargs.setdefault('cmap', 'afmhot')

        @interact(
            index=widgets.IntSlider(min=0,
                                    max=self.data.shape[0] - 1,
                                    step=1,
                                    value=1,
                                    description=self.geom.axes_names[0] +
                                    ' slice'),
            stretch=widgets.RadioButtons(options=['linear', 'sqrt', 'log'],
                                         value='sqrt',
                                         description='Plot stretch'),
            ax=fixed(ax),
            fig=fixed(fig),
        )
        def _plot_interactive(index, stretch, ax=None, fig=None):
            if self.geom.is_image:
                raise TypeError('Use .plot() for 2D Maps')

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

            if ax is None:
                ax = fig.add_subplot(1, 1, 1, projection=self.geom.wcs)

            axes = self.geom.get_axis_by_name(self.geom.axes_names[0])

            data = self.get_image_by_idx([index]).data
            norm = simple_norm(data[np.isfinite(data)], stretch)

            caxes = ax.imshow(data, norm=norm, **kwargs)
            fig.colorbar(caxes, ax=ax)
            ax.set_title('{:.2f}-{:.2f} {} '.format(
                axes.edges[index],
                axes.edges[index + 1],
                self.geom.axes[0].unit.name,
            ))

            try:
                ax.coords['glon'].set_axislabel('Galactic Longitude')
                ax.coords['glat'].set_axislabel('Galactic Latitude')
            except KeyError:
                ax.coords['ra'].set_axislabel('Right Ascension')
                ax.coords['dec'].set_axislabel('Declination')
            except AttributeError:
                log.info(
                    "Can't set coordinate axes. No WCS information available.")

            plt.show()
Пример #2
0
    def plot_interactive(self, rc_params=None, **kwargs):
        """
        Plot map with interactive widgets to explore the non spatial axes.

        Parameters
        ----------
        rc_params : dict
            Passed to ``matplotlib.rc_context(rc=rc_params)`` to style the plot.
        **kwargs : dict
            Keyword arguments passed to `WcsNDMap.plot`.

        Examples
        --------
        You can try this out e.g. using a Fermi-LAT diffuse model cube with an energy axis::

            from gammapy.maps import Map

            m = Map.read("$GAMMAPY_DATA/fermi_3fhl/gll_iem_v06_cutout.fits")
            m.plot_interactive(add_cbar=True, stretch="sqrt")

        If you would like to adjust the figure size you can use the ``rc_params`` argument::

            rc_params = {'figure.figsize': (12, 6), 'font.size': 12}
            m.plot_interactive(rc_params=rc_params)
        """
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from ipywidgets.widgets.interaction import interact, fixed
        from ipywidgets import SelectionSlider, RadioButtons

        if self.geom.is_image:
            raise TypeError("Use .plot() for 2D Maps")

        kwargs.setdefault("interpolation", "nearest")
        kwargs.setdefault("origin", "lower")
        kwargs.setdefault("cmap", "afmhot")

        rc_params = rc_params or {}
        stretch = kwargs.pop("stretch", "sqrt")

        interact_kwargs = {}

        for axis in self.geom.axes:
            if axis.node_type == "edges":
                options = [
                    "{:.2e} - {:.2e} {}".format(val_min, val_max, axis.unit)
                    for val_min, val_max in zip(axis.edges[:-1], axis.edges[1:])
                ]
            else:
                options = ["{:.2e} {}".format(val, axis.unit) for val in axis.center]

            interact_kwargs[axis.name] = SelectionSlider(
                options=options,
                description="Select {}:".format(axis.name),
                continuous_update=False,
                style={"description_width": "initial"},
                layout={"width": "50%"},
            )
            interact_kwargs[axis.name + "_options"] = fixed(options)

        interact_kwargs["stretch"] = RadioButtons(
            options=["linear", "sqrt", "log"],
            value=stretch,
            description="Select stretch:",
            style={"description_width": "initial"},
        )

        @interact(**interact_kwargs)
        def _plot_interactive(**ikwargs):
            idx = [
                ikwargs[ax.name + "_options"].index(ikwargs[ax.name])
                for ax in self.geom.axes
            ]
            img = self.get_image_by_idx(idx)
            stretch = ikwargs["stretch"]
            with mpl.rc_context(rc=rc_params):
                fig, ax, cbar = img.plot(stretch=stretch, **kwargs)
                plt.show()
Пример #3
0
    def plot_interactive(self, rc_params=None, **kwargs):
        """
        Plot map with interactive widgets to explore the non spatial axes.

        Parameters
        ----------
        rc_params : dict
            Passed to ``matplotlib.rc_context(rc=rc_params)`` to style the plot.
        **kwargs : dict
            Keyword arguments passed to `WcsNDMap.plot`.

        Examples
        --------
        You can try this out e.g. using a Fermi-LAT diffuse model cube with an energy axis::

            from gammapy.maps import Map

            m = Map.read("$GAMMAPY_DATA/fermi_3fhl/gll_iem_v06_cutout.fits")
            m.plot_interactive(add_cbar=True, stretch="sqrt")

        If you would like to adjust the figure size you can use the ``rc_params`` argument::

            rc_params = {'figure.figsize': (12, 6), 'font.size': 12}
            m.plot_interactive(rc_params=rc_params)
        """
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from ipywidgets.widgets.interaction import interact, fixed
        from ipywidgets import SelectionSlider, RadioButtons

        if self.geom.is_image:
            raise TypeError("Use .plot() for 2D Maps")

        kwargs.setdefault("interpolation", "nearest")
        kwargs.setdefault("origin", "lower")
        kwargs.setdefault("cmap", "afmhot")

        rc_params = rc_params or {}
        stretch = kwargs.pop("stretch", "sqrt")

        interact_kwargs = {}

        for axis in self.geom.axes:
            if axis.node_type == "edges":
                options = [
                    "{:.2e} - {:.2e} {}".format(val_min, val_max, axis.unit)
                    for val_min, val_max in zip(axis.edges[:-1], axis.edges[1:])
                ]
            else:
                options = ["{:.2e} {}".format(val, axis.unit) for val in axis.center]

            interact_kwargs[axis.name] = SelectionSlider(
                options=options,
                description="Select {}:".format(axis.name),
                continuous_update=False,
                style={"description_width": "initial"},
                layout={"width": "50%"},
            )
            interact_kwargs[axis.name + "_options"] = fixed(options)

        interact_kwargs["stretch"] = RadioButtons(
            options=["linear", "sqrt", "log"],
            value=stretch,
            description="Select stretch:",
            style={"description_width": "initial"},
        )

        @interact(**interact_kwargs)
        def _plot_interactive(**ikwargs):
            idx = [
                ikwargs[ax.name + "_options"].index(ikwargs[ax.name])
                for ax in self.geom.axes
            ]
            img = self.get_image_by_idx(idx)
            stretch = ikwargs["stretch"]
            with mpl.rc_context(rc=rc_params):
                fig, ax, cbar = img.plot(stretch=stretch, **kwargs)
                plt.show()