Example #1
0
    def add_histplot(self, target=False, loc=111, label='Kyoto $K_{p}$', 
                     time_range=None, **kwargs):
        '''
        Make a quick histogram-style plot of the Kp data.

        Returns
        =======
        fig : matplotlib figure object
        ax  : matplotlib axes object

        Other Parameters
        ================
        target : Figure or Axes
             If None (default), a new figure is generated from scratch.
             If a matplotlib Figure object, a new axis is created
             to fill that figure.
             If a matplotlib Axes object, the plot is placed
             into that axis.
        
        loc : int
           Use to specify the subplot placement of the axis
           (e.g. loc=212, etc.) Used if target is a Figure or None.
           Default 111 (single plot).

        label : string
            The label applied to the line when a legend is added to the axes.
            Defaults to 'Kyoto $K_{p}$'.

        time_range : tuple of datetimes
            The time range to plot.  Only the first and last values in the
            tuple (or list) are used if the number of elements is greater than
            two.  Defaults to **None**, meaning that the full time range
            available is used.

        Extra keyword arguments are passed to :function:`matplotlib.pyplot.plot`
        to customize the line style.

        Examples
        ========
        >>> import spacepy.pybats.kyoto as kt
        >>> kp = kt.fetch('kp', (1981, 11), (1981, 11)
        >>> kp.add_histplot(lw=2.0, lc='r', label='Example KP')

        '''

        import matplotlib.pyplot as plt

        # Shortcuts for the lazy.
        bstart=self['binstart']
        bstop =self['binstop']
        npts  =self.attrs['npts']

        # Reformulate time to get histogram-type look.
        newtime=np.zeros(npts*24, dtype=object)
        newkp  =np.zeros(npts*24)

        # Set time range.
        if not time_range:
            time_range = newtime
        
        for i in range(npts*8):
            newtime[3*i  ] = bstart[i]
            newtime[3*i+1] = self['time'][i]
            newtime[3*i+2] = bstop[i]
            newkp[3*i:3*i+3] = self['kp'][i], self['kp'][i], self['kp'][i]
    

        fig, ax = set_target(target, figsize=(10,4), loc=loc)
        line=ax.plot(newtime, newkp, label=label, **kwargs)
        applySmartTimeTicks(ax, time_range, dolabel=True)

        return fig, ax
Example #2
0
    def add_ltut(self, target=None, loc=111, cmap='Greens_r', zlim=[1,1000], 
                 add_cbar=True, clabel='Density $cm^{-3}$', xlabel='full', 
                 title=None, grid=True, ntick=5):
        '''
        Plot log(density) as a contour against local time (y-axis) and
        universal time (x-axis) using the PyBats *target* method of other
        standard plotting methods.  Four items are returned: the Matplotlib
        Figure, Axes, Mesh, and ColorBar objects used (if cbar is set to
        **False**, the returned ColorBar object is simply set to **False**.)

        ========== =======================================================
        Kwarg      Description
        ---------- -------------------------------------------------------
        target     Select plot destination.  Defaults to new figure/axis.
        loc        The location of any generated subplots.  Default is 111.
        add_cbar   Toggles the automatic colorbar.  Default is**True**.
        cmap       Selects Matplotlib color table.  Defaults to *Greens_r*.
        zlim       Limits for z-axis.  Defaults to [0.1, 1000]
        clabel     Sets colorbar label.  Defaults to units.
        xlabel     Sets x-axis labels, use 'full', 'ticks', or **None**.
        title      Sets axis title; defaults to **None**.
        grid       Show white dotted grid?  Defaults to **True**
        ntick      Number of attempted cbar ticks.  Defaults to 5.
        ========== =======================================================
        
        '''
        
        import matplotlib.pyplot as plt
        from matplotlib.ticker import LogLocator, LogFormatterMathtext
        from matplotlib.colors import LogNorm

        # Set ax and fig based on given target.
        if type(target) == plt.Figure:
            fig = target
            ax  = fig.add_subplot(loc)
        elif type(target).__base__ == plt.Axes:
            ax  = target
            fig = ax.figure
        else:
            fig = plt.figure()
            ax  = fig.add_subplot(loc)

        # Enforce values to be within limits.
        z=np.where(self['n']>zlim[0], self['n'], 1.01*zlim[0])
        z[z>zlim[1]] = zlim[1]

        # Create plot:
        mesh = ax.pcolormesh(self._dtime, self._y, z.transpose(), 
                             cmap=plt.get_cmap(cmap), norm=LogNorm(),
                             vmin=zlim[0], vmax=zlim[-1])

        # Use LT ticks and markers on y-axis:
        ax.set_yticks([6, 12, 18])
        ax.set_yticklabels(['Dawn', 'Noon', 'Dusk'])
        ax.set_ylim([4,20])

        # White ticks, slightly thicker:
        ax.tick_params(axis='both', which='both', color='w', width=1.2)

        # Grid marks:
        if grid: ax.grid(c='w')

        if title: ax.set_title(title)
        if xlabel == 'full':
            # Both ticks and label.
            applySmartTimeTicks(ax, self['time'], dolabel=True)
        elif xlabel == 'ticks':
            # Ticks, but no date label.
            applySmartTimeTicks(ax, self['time'], dolabel=False)
        else:
            # A blank x-axis is often useful.
            applySmartTimeTicks(ax, self['time'], dolabel=False)
            ax.set_xticklabels('')
        # Add cbar as necessary:
        if add_cbar:
            #lct = LogLocator
            cbar=plt.colorbar(mesh, ax=ax, pad=0.01, shrink=0.85)#, ticks=lct)
            cbar.set_label(clabel)
        else:
            cbar=None
            
        return fig, ax, mesh, cbar