Example #1
0
    def crosscorrs(self, clusters=None, bin_width=0.0015, limit=0.03, 
                         figsize=(9,5)):
        """ Plots of cross-correlations of clustered spike times. """

        times = self.clusters.select(clusters).times()
        colors = plt.get_colors(max(self.clusters.keys()) + 1, self.cm)
        
        # Set the number of rows and columns to plot
        n_rows, n_cols = [len(times)]*2
        fig, axes = plt.generate_crosscorr_axes(n_rows, n_cols, num=4,
                                                figsize=figsize)
        
        for (ii, jj) in axes:
            ax = axes[(ii,jj)]
            cl1, cl2 = times.keys()[ii], times.keys()[jj]
            t1, t2 = times[cl1], times[cl2]
            # Get the cross-correlation for different clusters
            if ii != jj:
                plt.crosscorr(t1, t2, ax=ax, bin_width=bin_width, limit=limit)
                ax.set_xticklabels('')
                ax.set_yticklabels('')
            
            # If cluster 1 is the same as cluster 2, get the autocorrelation
            else:
                plt.autocorr(t1, ax=ax, color=colors[cl1],
                                 bin_width=bin_width, limit=limit)
                ax.set_ylabel('{}'.format(cl1))
                ax.set_xticklabels('')
                ax.set_yticklabels('')
        
        return fig
Example #2
0
    def spikes(self, clusters=None, limit=50, figsize=None):
        """ Generates plots of clustered spike waveforms.
        """

        cls = self.clusters.select(clusters)
        cl_spikes = cls.spikes()
        colors = plt.get_colors(max(self.clusters.keys()) + 1, self.cm)

        fig, axes = plt.generate_axes(len(cls),
                                      4,
                                      num=2,
                                      sharex=True,
                                      figsize=figsize)
        for ax, cl in zip(axes, cl_spikes):
            ax.clear()
            spks = cl_spikes[cl]
            plt.spikes(spks,
                       ax=ax,
                       color=colors[cl],
                       patch_size=spks.shape[1] / 4)
            ax.set_title('Cluster {}'.format(cl))
            ax.set_ylabel('Voltage (uV)')
            ax.set_xticklabels('')

        fig.tight_layout()

        return fig
Example #3
0
    def autocorrs(self, clusters=None, bin_width=0.0015, limit=0.03, 
                        figsize=None):
        """ Plots of autocorrelations of clustered spike times.

            **Keywords**:
                *clusters*: list or iterable
                 List of clusters to plot
                *bin_width*: float
                 Width of bins in the autocorrelation calculation
                *limit*: float
                 Time limit over which to calculate the autocorrelation
        """
        
        cls = self.clusters.select(clusters)
        cl_times = cls.times()
        colors = plt.get_colors(max(self.clusters.keys()) + 1, self.cm)

        fig, axes = plt.generate_axes(len(cls), 4, num=3, figsize=figsize,
                                      sharex=True)
        for ax, cl in zip(axes, cl_times):
            ax.clear()
            tstamps = cl_times[cl]
            plt.autocorr(tstamps, ax=ax, color=colors[cl], 
                         bin_width=bin_width, limit=limit)
            ax.set_title('Cluster {}'.format(cl))
            ax.set_xlabel('Lag (ms)')
        
        fig.tight_layout()
        
        return fig
Example #4
0
    def plot_top_countries_by_crops(self, grp_cnt, col_name='', xlabel=''):
        """
        Plot top countries based on how much global ag area they occupy
        :param grp_cnt:
        :param col_name:
        :param xlabel:
        :return:
        """
        logger.info('plot_top_countries_by_crops')
        cols = plots.get_colors()

        # Number of countries to plot is given by constants.PLOT_CNTRS
        ax = grp_cnt[col_name][:constants.PLOT_CNTRS].plot(kind='barh',
                                                           color=cols[0],
                                                           linewidth=0)

        # Remove spines from top and right of plot
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)

        # Remove y-axis label
        ax.set_ylabel('')
        ax.set_xlabel(xlabel)

        # Ensure that the axis ticks only show up on the bottom and left of the plot
        ax.get_xaxis().tick_bottom()
        ax.get_yaxis().tick_left()

        # Final layout adjustment and output
        plt.tight_layout()
        plt.savefig(constants.out_dir + 'cntrs_by_area.png', dpi=constants.DPI)
        plt.close()
Example #5
0
    def plot_top_countries_by_crops(self, grp_cnt, col_name='', xlabel=''):
        """
        Plot top countries based on how much global ag area they occupy
        :param grp_cnt:
        :param col_name:
        :param xlabel:
        :return:
        """
        logger.info('plot_top_countries_by_crops')
        cols = plots.get_colors()

        # Number of countries to plot is given by constants.PLOT_CNTRS
        ax = grp_cnt[col_name][:constants.PLOT_CNTRS].plot(kind='barh', color=cols[0], linewidth=0)

        # Remove spines from top and right of plot
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)

        # Remove y-axis label
        ax.set_ylabel('')
        ax.set_xlabel(xlabel)

        # Ensure that the axis ticks only show up on the bottom and left of the plot
        ax.get_xaxis().tick_bottom()
        ax.get_yaxis().tick_left()

        # Final layout adjustment and output
        plt.tight_layout()
        plt.savefig(constants.out_dir + 'cntrs_by_area.png', dpi=constants.DPI)
        plt.close()
Example #6
0
 def _scatter_helper(self, clusters=None, limit=500):
     """ A helper method to generate the data for the scatter plots. """
     
     cls = self.clusters.select(clusters)
     # Here, limit the data so that we don't plot everything
     cls = Clusters({cl:plt.limit_data(cls[cl], limit) for cl in cls})
     
     # Get the color and feature arrays for fast plotting
     colors = plt.get_colors(max(self.clusters.keys()) + 1, self.cm)
     col_array = plt.color_array(cls, colors)
     feats = cls.features().flatten()
     
     return feats, col_array
Example #7
0
    def _scatter_helper(self, clusters=None, limit=500):
        """ A helper method to generate the data for the scatter plots. """

        cls = self.clusters.select(clusters)
        # Here, limit the data so that we don't plot everything
        cls = Clusters({cl: plt.limit_data(cls[cl], limit) for cl in cls})

        # Get the color and feature arrays for fast plotting
        colors = plt.get_colors(max(self.clusters.keys()) + 1, self.cm)
        col_array = plt.color_array(cls, colors)
        feats = cls.features().flatten()

        return feats, col_array
Example #8
0
    def plot_cnt_decade(self, inp_fao_df, cnt, already_processed=False):
        """
        Plot percentage of cropland area occupied by each crop functional type for a country
        :param inp_fao_df:
        :param cnt:
        :param already_processed:
        :return:
        """
        out_dec_df = self.per_CFT_by_decade(inp_fao_df, cnt, already_processed)

        out_dec_df = out_dec_df.set_index(self.cft_type)
        ax = out_dec_df.drop(self.name_country_col, axis=1).T.\
            plot(kind='bar', stacked=True, color=plots.get_colors(palette='tableau'), linewidth=0)

        plots.simple_axis(ax)  # Simple axis, no axis on top and right of plot

        # Transparent legend in lower left corner
        leg = plt.legend(loc='lower left', fancybox=None)
        leg.get_frame().set_linewidth(0.0)
        leg.get_frame().set_alpha(0.5)

        # Set X and Y axis labels and title
        ax.set_title(cnt)
        ax.set_xlabel('')
        plt.ylim(ymax=100)
        ax.set_ylabel(
            'Percentage of cropland area \noccupied by each crop functional type'
        )
        fmt = '%.0f%%'  # Format you want the ticks, e.g. '40%'
        yticks = mtick.FormatStrFormatter(fmt)
        ax.yaxis.set_major_formatter(yticks)

        # remove ticks from X axis
        plt.tick_params(
            axis='x',  # changes apply to the x-axis
            which='both',  # both major and minor ticks are affected
            bottom='off',  # ticks along the bottom edge are off
            top='off')  # ticks along the top edge are off

        # Rotate the X axis labels to be horizontal
        locs, labels = plt.xticks()
        plt.setp(labels, rotation=0)

        plt.tight_layout()
        plt.savefig(constants.out_dir + os.sep + cnt + '.png',
                    bbox_inches='tight',
                    dpi=600)
        plt.close()
Example #9
0
    def plot_stacked_country_cft(self,
                                 df,
                                 arr_legend,
                                 path_out,
                                 fname,
                                 ncols=2,
                                 xlabel='',
                                 ylabel='',
                                 title=''):
        """

        :param df:
        :param arr_legend:
        :param path_out:
        :param fname:
        :param xlabel:
        :param ylabel:
        :param title:
        :return:
        """
        df = (df.reset_index().fillna(0.0))

        ax = (df.plot.bar(stacked=True,
                          colormap=plots.get_colors(palette='tableau',
                                                    cmap=True),
                          linewidth=0,
                          use_index=False))

        # Legend
        leg = ax.legend(fancybox=None, ncol=ncols, prop={'size': 6})
        leg.get_frame().set_linewidth(0.0)
        leg.get_frame().set_alpha(0.5)

        # Create nice-looking grid for ease of visualization
        ax.grid(which='minor', alpha=0.2, linestyle='--')
        ax.grid(which='major', alpha=0.5, linestyle='--')

        plt.xticks(df.index, df[self.FAO_code])
        plt.ylabel(ylabel)
        plt.xlabel(xlabel)
        plt.title(title)

        plt.tight_layout()
        plt.savefig(path_out + os.sep + fname, dpi=constants.DPI)
        plt.close()
Example #10
0
    def plot_cnt_mean_decade(self, inp_fao_df, cnt, already_processed=False):
        """
        Plot mean crop functional type area in each decade
        :param inp_fao_df:
        :param cnt:
        :param already_processed:
        :return:
        """
        out_dec_df = self.per_CFT_by_decade(inp_fao_df, cnt, already_processed)

        out_dec_df = out_dec_df.set_index(self.cft_type)
        ax = out_dec_df.drop(self.name_country_col, axis=1).T.\
            plot(kind='bar', stacked=True, color=plots.get_colors(palette='tableau'), linewidth=0)

        plots.simple_axis(ax)  # Simple axis, no axis on top and right of plot

        # Transparent legend in lower left corner
        leg = plt.legend(loc='lower left', fancybox=None)
        leg.get_frame().set_linewidth(0.0)
        leg.get_frame().set_alpha(0.5)

        # Set X and Y axis labels and title
        ax.set_title(cnt)
        ax.set_xlabel('')
        plt.ylim(ymax=100)
        ax.set_ylabel('Mean crop functional type area in each decade')
        fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
        yticks = mtick.FormatStrFormatter(fmt)
        ax.yaxis.set_major_formatter(yticks)

        # remove ticks from X axis
        plt.tick_params(
            axis='x',          # changes apply to the x-axis
            which='both',      # both major and minor ticks are affected
            bottom='off',      # ticks along the bottom edge are off
            top='off')         # ticks along the top edge are off

        # Rotate the X axis labels to be horizontal
        locs, labels = plt.xticks()
        plt.setp(labels, rotation=0)

        plt.tight_layout()
        plt.savefig(constants.out_dir + os.sep + 'Mean_' + cnt + '.png', bbox_inches='tight', dpi=600)
        plt.close()
Example #11
0
 def spikes(self, clusters=None, limit=50, figsize=None):
     """ Generates plots of clustered spike waveforms.
     """
     
     cls = self.clusters.select(clusters)
     cl_spikes = cls.spikes()
     colors = plt.get_colors(max(self.clusters.keys()) + 1, self.cm)
     
     fig, axes = plt.generate_axes(len(cls), 4, num=2, sharex=True,
                                   figsize=figsize)
     for ax, cl in zip(axes, cl_spikes):
         ax.clear()
         spks = cl_spikes[cl]
         plt.spikes(spks, ax=ax, color=colors[cl], patch_size=spks.shape[1]/4)
         ax.set_title('Cluster {}'.format(cl))
         ax.set_ylabel('Voltage (uV)')
         ax.set_xticklabels('')
     
     fig.tight_layout()
     
     return fig
Example #12
0
    def crosscorrs(self,
                   clusters=None,
                   bin_width=0.0015,
                   limit=0.03,
                   figsize=(9, 5)):
        """ Plots of cross-correlations of clustered spike times. """

        times = self.clusters.select(clusters).times()
        colors = plt.get_colors(max(self.clusters.keys()) + 1, self.cm)

        # Set the number of rows and columns to plot
        n_rows, n_cols = [len(times)] * 2
        fig, axes = plt.generate_crosscorr_axes(n_rows,
                                                n_cols,
                                                num=4,
                                                figsize=figsize)

        for (ii, jj) in axes:
            ax = axes[(ii, jj)]
            cl1, cl2 = times.keys()[ii], times.keys()[jj]
            t1, t2 = times[cl1], times[cl2]
            # Get the cross-correlation for different clusters
            if ii != jj:
                plt.crosscorr(t1, t2, ax=ax, bin_width=bin_width, limit=limit)
                ax.set_xticklabels('')
                ax.set_yticklabels('')

            # If cluster 1 is the same as cluster 2, get the autocorrelation
            else:
                plt.autocorr(t1,
                             ax=ax,
                             color=colors[cl1],
                             bin_width=bin_width,
                             limit=limit)
                ax.set_ylabel('{}'.format(cl1))
                ax.set_xticklabels('')
                ax.set_yticklabels('')

        return fig
Example #13
0
    def autocorrs(self,
                  clusters=None,
                  bin_width=0.0015,
                  limit=0.03,
                  figsize=None):
        """ Plots of autocorrelations of clustered spike times.

            **Keywords**:
                *clusters*: list or iterable
                 List of clusters to plot
                *bin_width*: float
                 Width of bins in the autocorrelation calculation
                *limit*: float
                 Time limit over which to calculate the autocorrelation
        """

        cls = self.clusters.select(clusters)
        cl_times = cls.times()
        colors = plt.get_colors(max(self.clusters.keys()) + 1, self.cm)

        fig, axes = plt.generate_axes(len(cls),
                                      4,
                                      num=3,
                                      figsize=figsize,
                                      sharex=True)
        for ax, cl in zip(axes, cl_times):
            ax.clear()
            tstamps = cl_times[cl]
            plt.autocorr(tstamps,
                         ax=ax,
                         color=colors[cl],
                         bin_width=bin_width,
                         limit=limit)
            ax.set_title('Cluster {}'.format(cl))
            ax.set_xlabel('Lag (ms)')

        fig.tight_layout()

        return fig
Example #14
0
    def plot_stacked_country_cft(self, df, arr_legend, path_out, fname, ncols=2, xlabel='', ylabel='', title=''):
        """

        :param df:
        :param arr_legend:
        :param path_out:
        :param fname:
        :param xlabel:
        :param ylabel:
        :param title:
        :return:
        """
        df = (df
              .reset_index()
              .fillna(0.0))

        ax = (df
              .plot
              .bar(stacked=True, colormap=plots.get_colors(palette='tableau', cmap=True), linewidth=0, use_index=False))

        # Legend
        leg = ax.legend(fancybox=None, ncol=ncols, prop={'size': 6})
        leg.get_frame().set_linewidth(0.0)
        leg.get_frame().set_alpha(0.5)

        # Create nice-looking grid for ease of visualization
        ax.grid(which='minor', alpha=0.2, linestyle='--')
        ax.grid(which='major', alpha=0.5, linestyle='--')

        plt.xticks(df.index, df[self.FAO_code])
        plt.ylabel(ylabel)
        plt.xlabel(xlabel)
        plt.title(title)

        plt.tight_layout()
        plt.savefig(path_out + os.sep + fname, dpi=constants.DPI)
        plt.close()
def plot_cnt_decade(inp_fao_df,cnt):
    out_dec_df = per_CFT_by_decade(inp_fao_df,cnt)
    out_ann_df = per_CFT_annual(inp_fao_df,cnt)

    out_dec_df = out_dec_df.set_index('functional_crop_type')
    ax = out_dec_df.drop('country_name', axis=1).T.plot(kind='bar',stacked=True,color=plots.get_colors(5),linewidth=0)

    plots.simple_axis(ax) # Simple axis, no axis on top and right of plot

    # Transparent legend in lower left corner
    leg = plt.legend(loc='lower left',fancybox=None)
    leg.get_frame().set_linewidth(0.0)
    leg.get_frame().set_alpha(0.5)

    # Set X and Y axis labels and title
    ax.set_title(cnt)
    ax.set_xlabel('')
    plt.ylim(ymax = 100)
    ax.set_ylabel('Percentage of cropland area \noccupied by each crop functional type')
    fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
    yticks = mtick.FormatStrFormatter(fmt)
    ax.yaxis.set_major_formatter(yticks)

    # remove ticks from X axis
    plt.tick_params(\
        axis='x',          # changes apply to the x-axis
        which='both',      # both major and minor ticks are affected
        bottom='off',      # ticks along the bottom edge are off
        top='off')         # ticks along the top edge are off

    # Rotate the X axis labels to be horizontal
    locs, labels = plt.xticks()
    plt.setp(labels, rotation=0)

    plt.tight_layout()
    plt.savefig(constants.out_dir+os.sep+cnt+'.png', bbox_inches='tight', dpi=600)
    plt.close()