Example #1
0
def plot_missing_values(data, data_gaps, data_column='', title='', var_name='', var_unit='', fig_filename='',
                        circular=False, label='observations'):
    # Get style
    plot.get_default_plot_style()
    # Get values
    values = plot.get_values(data, data_column)
    # Get var label
    var_label = plot.get_var_label(var_name, var_unit)
    # Plot
    ax = plt.axes()
    ax.plot(values.index, values, ':', alpha=0.3, label=label)
    ax.plot(values.loc[data_gaps.loc[:, 'pos_ini']], '.k', markersize=10, label='Gaps_initial_postion')
    ax.plot(values.loc[data_gaps.loc[:, 'pos_fin']], '.r', markersize=10, label='Gaps_final_postion')
    ax.legend(loc='upper right', facecolor='white')
    plot.plot_title(ax, title)

    if circular is True:
        circular_labels, circular_ticks = plot.get_circular_ticks()
        plt.yticks(circular_ticks, circular_labels)

    ax.set_ylabel(var_label)
    # fixing the x tick labels are all squashed together
    plt.gcf().autofmt_xdate()

    plot.save_figure(fig_filename)
Example #2
0
def plot_histogram(data,
                   title='',
                   var_name='',
                   var_unit='',
                   fig_filename='',
                   rug=False,
                   data_column='',
                   circular=False,
                   kernel=False,
                   bins='auto'):
    plot.get_default_plot_style()

    values = plot.get_values(data, data_column)
    var_label = plot.get_var_label(var_name, var_unit)

    # Remove null values
    values_clean = values.dropna(axis=0, how='all')
    ax = sns.distplot(values_clean,
                      rug=rug,
                      hist_kws={'edgecolor': 'black'},
                      kde=kernel,
                      bins=bins,
                      norm_hist=True)

    plot.plot_title(ax, title)

    if circular:
        circular_labels, circular_ticks = plot.get_circular_ticks()
        plt.xticks(circular_ticks, circular_labels)

    ax.set_xlabel(var_label)

    plot.save_figure(fig_filename)
Example #3
0
def plot_rose(data,
              data_column,
              dir_column,
              title='',
              var_name='',
              var_unit='',
              fig_filename='',
              legend_position='upper left',
              xlabels=('E', 'N-E', 'N', 'N-W', 'W', 'S-W', 'S', 'S-E')):
    plot.get_default_plot_style(context='talk')

    var_label = plot.get_var_label(var_name, var_unit)

    ax = plot_windrose(data,
                       kind='bar',
                       var_name=data_column,
                       direction_name=dir_column,
                       normed=True,
                       opening=0.8,
                       edgecolor=n(b'white'))

    plot.plot_title(ax, title)

    ax.set_xlabel(var_label)
    ax.legend(loc=legend_position, fontsize='small')
    ax.set_xticklabels(xlabels)

    plot.save_figure(fig_filename)
Example #4
0
def peaks_plot(data,
               peaks,
               data_column='',
               title='',
               var_name='',
               var_unit='',
               fig_filename='',
               circular=False,
               data_label='',
               peaks_label=''):
    # Get style
    plot.get_default_plot_style()
    # Get values
    values = plot.get_values(data, data_column)
    # Get var label
    var_label = plot.get_var_label(var_name, var_unit)
    # Plot
    ax = plt.axes()
    ax.plot(values.index, values, ':', alpha=0.3, label=data_label)
    # ax.plot(peaks.index, peaks, '.r', markersize=10, label=peaks_label)
    ax.legend(loc='upper right', facecolor='white')
    plot.plot_title(ax, title)

    if circular:
        circular_labels, circular_ticks = plot.get_circular_ticks()
        plt.yticks(circular_ticks, circular_labels)

    ax.set_ylabel(var_label)
    # fixing the x tick labels are all squashed together
    plt.gcf().autofmt_xdate()
    plt.xlim([1959, 2018])

    plot.save_figure(fig_filename)
Example #5
0
def plot_fit_kde(x, y, data, data_name, title='', var_name='', var_unit='', kde=True, hist=False, cumulative=False,
             fig_filename='', fit_label='fitting', hist_label='empirical', kde_label='kernel'):
    plot.get_default_plot_style()

    # kw_params is a keyworded variable length argument
    kw_params = {'hist_kws': {'label': hist_label, 'edgecolor': 'black'}, 'kde_kws': {'label': kde_label}}
    if cumulative:
        # noinspection PyTypeChecker
        kw_params['hist_kws'].update({'cumulative': True})
        # noinspection PyTypeChecker
        kw_params['kde_kws'].update({'cumulative': True})

    var_label = plot.get_var_label(var_name, var_unit)

    ax = sns.distplot(data[data_name], kde=kde, hist=hist, **kw_params)

    ax.plot(x, y, label=fit_label)

    ax.legend(loc='upper right', facecolor='white')

    plot.plot_title(ax, title)

    ax.set_xlabel(var_label)

    plot.save_figure(fig_filename)
Example #6
0
def plot_empirical(dist, fig_filename=''):
    # width is in axis units
    width, _, _ = plot.calculation_width(dist)

    plt.bar(dist.index, dist, width, edgecolor='black', linewidth=0.5)

    plot.save_figure(fig_filename)
Example #7
0
def plot_extremal_cdf(x_extremal,
                      y_extremal,
                      ecdf_extemal,
                      n_sim_boot,
                      boot_extremal,
                      alpha,
                      title='',
                      var_name='',
                      var_unit='',
                      fig_filename='',
                      circular=False,
                      extremal_label='',
                      empirical_label=''):
    # TODO: hacer paquete opcional
    from tqdm import tqdm

    # Get style
    plot.get_default_plot_style()

    # Prepare label and units
    var_label = plot.get_var_label(var_name, var_unit)

    ax = plt.axes()
    # for sim in tqdm(range(n_sim_boot)):
    #     ax.plot(x_extremal, boot_extremal['y_boot'][sim], 'grey', alpha=0.35)

    ax.plot(ecdf_extemal.index,
            ecdf_extemal,
            '.',
            color='#ff7f0e',
            label=empirical_label)
    ax.plot(x_extremal, y_extremal, color='#1f77b4', label=extremal_label)
    ax.plot(x_extremal,
            boot_extremal['lower_band'],
            '--',
            color='#1f77b4',
            label='Lower {}% confidence band'.format((1 - alpha) * 100))
    ax.plot(x_extremal,
            boot_extremal['upper_band'],
            '--',
            color='#1f77b4',
            label='Upper {}% confidence band'.format((1 - alpha) * 100))
    ax.legend()

    plot.plot_title(ax, title)

    if circular:
        circular_labels, circular_ticks = plot.get_circular_ticks()
        plt.yticks(circular_ticks, circular_labels)

    ax.set_xlabel(var_label)
    ax.set_ylabel('CDF')

    # fixing the x tick labels are all squashed together
    plt.gcf().autofmt_xdate()

    plot.save_figure(fig_filename)
Example #8
0
def plot_variability(data,
                     frecuency,
                     title='',
                     var_name='',
                     var_unit='',
                     x_step=1,
                     fliersize=1,
                     linewidth=0.5,
                     color='skyblue',
                     palette=None,
                     fig_filename='',
                     circular=False):
    plot.get_default_plot_style()

    var_label = plot.get_var_label(var_name, var_unit)

    # gettattr return the value of the named attribute,
    # i.e. data.index.daily is equivalent to getattr(data.index, 'daily')
    x = getattr(data.index, frecuency)
    ax = sns.boxplot(x=x,
                     y=data,
                     fliersize=fliersize,
                     linewidth=linewidth,
                     color=color,
                     palette=palette)

    plot.plot_title(ax, title)

    if circular:
        circular_labels, circular_ticks = plot.get_circular_ticks()
        plt.yticks(circular_ticks, circular_labels)

    if frecuency == 'month':
        months_labels, months_ticks = plot.get_months_ticks()
        plt.xticks(months_ticks, months_labels)
    else:
        if x_step > 1:
            x_labels, x_ticks = plot.get_x_ticks(x, ax.get_xlim(), x_step)
            plt.xticks(x_ticks, x_labels)
        # fixing the x tick labels are all squashed together
        ax.xaxis_date()
        plt.gcf().autofmt_xdate()

    ax.xaxis.grid(True)
    ax.set_xlabel('')
    ax.set_ylabel(var_label)

    plot.save_figure(fig_filename)
Example #9
0
def plot_fit_kde_ecdf(x_gev, y_gev, x_ecdf, y_ecdf, x_ecdf_kde, y_ecdf_kde, var_name='', var_unit='', label_fit='',
                      label_observation='', label_kde='', title='', fig_filename=''):

    plot.get_default_plot_style()

    var_label = plot.get_var_label(var_name, var_unit)

    ax = plt.axes()
    ax.plot(x_gev, y_gev, 'k', label=label_fit)
    ax.plot(x_ecdf, y_ecdf, '.b', label=label_observation)
    ax.plot(x_ecdf_kde, y_ecdf_kde, 'r', label=label_kde)
    ax.legend(loc='upper right', facecolor='white')
    plot.plot_title(ax, title)

    ax.set_xlabel(var_label)
    # fixing the x tick labels are all squashed together
    plt.gcf().autofmt_xdate()

    plot.save_figure(fig_filename)
Example #10
0
def plot_scatter(data,
                 x_column,
                 y_column,
                 title='',
                 x_var_name='',
                 x_var_unit='',
                 y_var_name='',
                 y_var_unit='',
                 circular=None,
                 fig_filename='',
                 mark_size=15):
    plot.get_default_plot_style()

    x_var_label = plot.get_var_label(x_var_name, x_var_unit)
    y_var_label = plot.get_var_label(y_var_name, y_var_unit)

    ax = sns.jointplot(x_column,
                       y_column,
                       data=data,
                       stat_func=None,
                       joint_kws={'s': mark_size},
                       marginal_kws={'hist_kws': {
                           'edgecolor': 'black'
                       }})

    plt.subplots_adjust(top=0.9)
    plt.gcf().suptitle(title)

    if circular == 'x':
        circular_labels, circular_ticks = plot.get_circular_ticks()
        ax.ax_joint.set_xticks(circular_ticks)
        ax.ax_joint.set_xticklabels(circular_labels, rotation=45)
        plt.subplots_adjust(bottom=0.15)
    elif circular == 'y':
        circular_labels, circular_ticks = plot.get_circular_ticks()
        ax.ax_joint.set_yticks(circular_ticks)
        ax.ax_joint.set_yticklabels(circular_labels)
        plt.subplots_adjust(left=0.15)

    ax.set_axis_labels(x_var_label, y_var_label)

    plot.save_figure(fig_filename)
Example #11
0
def test_river_discharge_ecdf():
    name = 'river_flow.txt'
    data_path = os.path.join(tests.full_data_path, 'saih', name)

    # Read Saih
    data = saih.read_file(data_path)

    # Empirical cdf
    cumulative = True
    data = empirical_distributions.kde_sm(data, cumulative=cumulative)

    # Plot
    plt.figure()
    plt.show()
    ax = plt.axes()
    ax.plot(data.index, data)
    plot.plot_title(ax, 'Cummulative density function')
    ax.set_xlabel('$Q (m^3 \, s^{-1})$')
    ax.set_ylabel('CDF')
    plot.save_figure('CDF_river_discharge')
Example #12
0
def plot_kde(data_empirical,
             data_kernel,
             cumulative,
             title='',
             var_name='',
             var_unit='',
             fig_filename='',
             circular=False,
             label_empirical='',
             label_kernel=''):

    plot.get_default_plot_style()

    values_empirical = plot.get_values(data_empirical, '')
    var_label = plot.get_var_label(var_name, var_unit)

    ax = plt.axes()
    ax.plot(values_empirical.index, values_empirical, label=label_empirical)
    if cumulative:
        values_kernel = plot.get_values(data_kernel, '')
        ax.plot(values_kernel.index, values_kernel, label=label_kernel)
    ax.legend(loc='upper right', facecolor='white')

    plot.plot_title(ax, title)

    if circular:
        circular_labels, circular_ticks = plot.get_circular_ticks()
        plt.yticks(circular_ticks, circular_labels)

    plot.plot_title(ax, title)
    ax.set_xlabel(var_label)

    if cumulative:
        ax.set_ylabel('CDF')
    else:
        ax.set_ylabel('PDF')

    # fixing the x tick labels are all squashed together
    plt.gcf().autofmt_xdate()

    plot.save_figure(fig_filename)
Example #13
0
def plot_series(data,
                title='',
                var_name='',
                var_unit='',
                fig_filename='',
                data_column='',
                circular=False,
                show_trends=False,
                label='observations'):
    plot.get_default_plot_style()

    values = plot.get_values(data, data_column)
    var_label = plot.get_var_label(var_name, var_unit)

    ax = plt.axes()
    if show_trends is False:
        ax.plot(values.index, values, linewidth=0.5)
    else:
        # TODO Comprobar que funciona correctamente con más ejemplos

        # UnivariateSpline needs conversion from DateTimeIndex to float
        splined_index = values.index.values.astype('d')
        splined_values = UnivariateSpline(splined_index, values)

        ax.plot(values.index, values, ':', alpha=0.3, label=label)
        ax.plot(values.index, splined_values(splined_index))

        ax.legend(loc='upper right', facecolor='white')

    plot.plot_title(ax, title)

    if circular:
        circular_labels, circular_ticks = plot.get_circular_ticks()
        plt.yticks(circular_ticks, circular_labels)

    ax.set_ylabel(var_label)
    # fixing the x tick labels are all squashed together
    plt.gcf().autofmt_xdate()

    plot.save_figure(fig_filename)
Example #14
0
def plot_anual_variability(data,
                           daily_agg='mean',
                           plot_agg=np.mean,
                           ci='sd',
                           color='darkblue',
                           fig_filename=''):
    plot.get_default_plot_style()

    # Aggregate by day
    data_aggregated = getattr(data.resample('D'), daily_agg)
    # Split years
    timeseries_data = time_series.generate_year_stack(data_aggregated())
    # Fill gaps (one week maximum)
    data_filled = timeseries_data.fillna(method='ffill', axis=1, limit=7)
    # Remove incomplete years
    data_clean = data_filled.dropna()
    # Convert to numpy array
    data_values = data_clean.values

    sns.tsplot(data=data_values, estimator=plot_agg, ci=ci, color=color)

    plot.save_figure(fig_filename)
Example #15
0
def plot_ecdf_sm_dots(data,
                      title='',
                      var_name='',
                      var_unit='',
                      fig_filename='',
                      data_column='',
                      label='Observations'):
    plot.get_default_plot_style()

    values = plot.get_values(data, data_column)
    var_label = plot.get_var_label(var_name, var_unit)

    ax = plt.axes()
    ax.plot(values.index, values, '.', label=label)
    ax.legend(loc='upper right', facecolor='white')
    plot.plot_title(ax, title)

    ax.set_xlabel(var_label)
    # fixing the x tick labels are all squashed together
    plt.gcf().autofmt_xdate()

    plt.show()
    plot.save_figure(fig_filename)
Example #16
0
def plot_empirical_fit(dist,
                       fitting_function,
                       params,
                       x_step=200,
                       cumulative=False,
                       fig_filename=''):
    # width is in axis units
    width, x_min, x_max = plot.calculation_width(dist)

    plt.bar(dist.index, dist, width, edgecolor='black', linewidth=0.5)

    x = np.linspace(x_min, x_max, x_step)

    if cumulative:
        cdf = getattr(fitting_function, 'cdf')
        p = cdf(x, *params)
    else:
        pdf = getattr(fitting_function, 'pdf')
        p = pdf(x, *params)

    plt.plot(x, p, color='orange')

    plot.save_figure(fig_filename)