Esempio n. 1
0
        def _add_inner_title(ax, title, loc, size=None, **kwargs):

            if size is None:
                size = dict(size=pp.rcParams['legend.fontsize'])

            at = AnchoredText(title, loc=loc, prop=size, pad=0., borderpad=0.5, frameon=False, **kwargs)

            at.set_zorder(200)
            ax.add_artist(at)
            at.txt._text.set_path_effects([withStroke(foreground="w", linewidth=3)])
            return at
Esempio n. 2
0
def add_inner_title(ax, title, loc, size=None, **kwargs):
    from matplotlib.offsetbox import AnchoredText
    from matplotlib.patheffects import withStroke

    if size is None:
        size = dict(size=pp.rcParams["legend.fontsize"])

    at = AnchoredText(title, loc=loc, prop=size, pad=0.0, borderpad=0.5, frameon=False, **kwargs)

    at.set_zorder(200)

    ax.add_artist(at)

    at.txt._text.set_path_effects([withStroke(foreground="w", linewidth=3)])

    return at
Esempio n. 3
0
    def _(self, index, ax, kind='vawt', cm='seismic', ptype='seis'):
        data = self.data(index)
        handle = None
        if kind == 'vawt':
            wiggles(data.T, wiggleInterval=1, ax=ax)
        elif kind == 'img':
            handle = img(data.T,
                         extent=[
                             self.startInline,
                             self.endInline,
                             self.startCrline,
                             self.endCrline,
                         ],
                         ax=ax,
                         cm=cm,
                         ptype=ptype)
            ax.invert_yaxis()
        else:
            pass
        ax.get_figure().suptitle("Z slice: {}".format(index.value))
        from matplotlib.offsetbox import AnchoredText
        z_text = AnchoredText(r"$\downarrow$Cross-line",
                              loc=2,
                              prop=dict(size=10),
                              frameon=False,
                              bbox_to_anchor=(0., 0.),
                              bbox_transform=ax.transAxes)
        ax.add_artist(z_text)
        inline_text = AnchoredText(r"In-line $\rightarrow$ ",
                                   loc=1,
                                   prop=dict(size=10),
                                   frameon=False,
                                   bbox_to_anchor=(1., 0.),
                                   bbox_transform=ax.transAxes)
        ax.add_artist(inline_text)

        return handle
Esempio n. 4
0
def add_inner_title(ax, title, loc, size=None, **kwargs):
    from matplotlib.offsetbox import AnchoredText
    from matplotlib.patheffects import withStroke
    if size is None:
        size = dict(size=plt.rcParams['ytick.labelsize'])
    at = AnchoredText(title,
                      loc=loc,
                      prop=size,
                      pad=0.,
                      borderpad=0.5,
                      frameon=False,
                      **kwargs)
    ax.add_artist(at)
    at.txt._text.set_path_effects([withStroke(foreground="w", linewidth=2)])
    return at
Esempio n. 5
0
def plot_seismo_and_best_fit_curve(t: np.ndarray, x: np.ndarray,
                                   params: Tuple[float, float, float, float]):
    amplitude, dampening, phase, frequency = params
    fig, ax = get_base_plot()
    ax.plot(t, damped_oscillator(t, *params), label="Best fit curve")
    ax.plot(t, x, label="Seismogram")
    ax.legend()
    ax.set_title(r"Damped oscillation $x(t) = A * exp(-\delta t) * sin(\phi + \omega * t)$")
    param_string = "\n".join((r"$A = ${amplitude:.2e}".format(amplitude=amplitude),
                              r"$\delta = ${dampening:.2f}".format(dampening=dampening),
                              r"$\phi = ${phase:.2f}".format(phase=phase),
                              r"$\omega = ${frequency:.2f}".format(frequency=frequency)))
    text = AnchoredText(param_string, loc="lower right")
    ax.add_artist(text)
    plt.show()
Esempio n. 6
0
    def add_inner_title(ax, title, loc, size=None, **kwargs):
        if size is None:
            size = dict(size=7)  # size=plt.rcParams['legend.fontsize']

        at = AnchoredText(title,
                          loc=loc,
                          prop=size,
                          pad=0.,
                          borderpad=0.25,
                          frameon=False,
                          **kwargs)
        ax.add_artist(at)
        at.txt._text.set_path_effects(
            [withStroke(foreground="w", linewidth=3)])
        return at
Esempio n. 7
0
 def add_annotation(self,
                    s,
                    loc='upper left',
                    pad=0.4,
                    borderpad=0.,
                    prop=None):
     if prop is None:
         prop = {"size": 18, "color": "k"}
     anchored_text = AnchoredText(s,
                                  loc=loc,
                                  pad=pad,
                                  borderpad=borderpad,
                                  frameon=False,
                                  prop=prop)
     self.ax.add_artist(anchored_text)
Esempio n. 8
0
def add_inner_title(ax, title, loc, **kwargs):
    from matplotlib.offsetbox import AnchoredText
    from matplotlib.patheffects import withStroke
    #    prop = dict(path_effects=[withStroke(foreground='w', linewidth=3)],
    #                size=plt.rcParams['legend.fontsize'])
    prop = dict(size=plt.rcParams['legend.fontsize'])
    at = AnchoredText(title,
                      loc=loc,
                      prop=prop,
                      pad=0.,
                      borderpad=0.5,
                      frameon=False,
                      **kwargs)
    ax.add_artist(at)
    return at
Esempio n. 9
0
def fit_gaussian_peak(x, y, bin_size=1, display_offset=0):

    init_amplitude = np.sum(y) * bin_size
    init_mu = np.sum(y * x) / np.sum(y)
    init_sigma = np.sqrt(np.sum(y * (x - init_mu) ** 2) / np.sum(y))

    popt, pcov = curve_fit(gauss, x, y, p0=[init_amplitude, init_mu, init_sigma])
    var = popt
    var_err = np.sqrt(np.diagonal(pcov))
    text = write_gaus_info(var, var_err)

    x_fit = np.linspace(x[0], x[-1], 1000)

    fig = plt.figure()
    gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
    ax0 = fig.add_subplot(gs[0])
    ax0.plot(x + display_offset, y, 'b-', label='data')
    ax0.plot(x_fit + display_offset, gauss(x_fit, *popt), 'g--', label='fit')
    ax0.plot(x + display_offset, gauss(x, init_amplitude, init_mu, init_sigma), 'r*', label='Initial values')
    ax0.set_ylabel('count')
    ax0.legend(loc=2)

    text_gaus = 'y = A $\\frac{1}{\sigma \sqrt{2 \pi}} e^{-(\\frac{x-\mu}{\sigma})}$'
    anchored_text = AnchoredText(text, loc=6, frameon=False)
    anchored_text_gaus = AnchoredText(text_gaus, loc=1, frameon=False)
    ax0.add_artist(anchored_text)
    ax0.add_artist(anchored_text_gaus)

    ax1 = fig.add_subplot(gs[1], sharex=ax0)
    ax1.plot(x + display_offset, (y - gauss(x, *popt)) / y, marker='o', linestyle='None', color='black')
    ax1.axhline(0, color='gray', linestyle='dashed')
    ax1.set_ylabel('Residual')
    ax1.set_xlabel('Index')
    print('Peak fitted')

    return popt, pcov, fig
def plotPermDist(ax, dist, trueVal, pval):
    with sns.plotting_context('notebook'):
        sns.set(style="white", palette="muted", font_scale=1.2)
        sns.despine(left=True)

        _ = sns.distplot(dist, bins=25, ax=ax)
        ax.axvline(trueVal, color='r', linewidth=2, alpha=0.8, linestyle='--')
        ax.add_artist(
            AnchoredText('si={0:.3f}\np={1:.3f}'.format(trueVal, pval),
                         loc='upper right',
                         frameon=False))
        _ = ax.set_xlabel('Spatial Information')
        _ = ax.set_ylabel('')
        ax.set_yticks([])
    return ax
Esempio n. 11
0
    def visualise_peak(self, frq, y_max, peak_tupel, **kwargs):
        y_x = kwargs.get('y_x', None)
        y_y = kwargs.get('y_y', None)
        y_z = kwargs.get('y_z', None)
        rr = kwargs.get('rr', None)

        N = y_max.size

        #plt.xkcd() #HAHA! COMIC STYLE - XKCD
        fig, ax = plt.subplots(1)
        fig.suptitle('Maximum power spectrum with peak.', fontsize="large")

        # plotting the spectrum
        if y_y is not None:
            ax.plot(frq,
                    2.0 / N * np.abs(y_x[0:N / 2]),
                    'r',
                    label='Power spectrum X')
        if y_y is not None:
            ax.plot(frq,
                    2.0 / N * np.abs(y_y[0:N / 2]),
                    'b',
                    label='Power spectrum Y')
        if y_z is not None:
            ax.plot(frq,
                    2.0 / N * np.abs(y_z[0:N / 2]),
                    'g',
                    label='Power spectrum Z')

        ax.plot(frq,
                2.0 / N * np.abs(y_max[0:N / 2]),
                'y',
                label='Maximum Power spectrum')
        ax.plot(peak_tupel[0], peak_tupel[1], 'rx', label='Peak')

        text = 'Peak = %f ; %f' % (peak_tupel[0], peak_tupel[1])
        #ax.add_artist(anchored_text)
        if rr is not None:
            text += '\n' + 'RR = %f' % rr
        anchored_text = AnchoredText(text,
                                     loc=4,
                                     prop=dict(color='Black', size=9))
        ax.add_artist(anchored_text)

        ax.set_xlabel('Frequency in Hz')
        ax.set_ylabel('Power spectrum density')
        ax.set_xlim([0.1, 0.6])
        plt.legend(loc='best', fontsize=9)
Esempio n. 12
0
def corr_plot(dataframe, fig_height=None, fig_width=None, **kwargs):
    """
    Plot correlation matrix of a dataframe, and save to local directory.
    ----------------------------------------
    :param dataframe: dataframe to be plot.
    :param fig_height: height of the figure to be plot, default=None.
    :param fig_width: width of the figure to be plot, default=None.
    :return: None
    """
    corr_matrix = dataframe.corr()
    n = len(corr_matrix)
    fig, axes = plt.subplots(nrows=n, ncols=n, sharex='col')
    if fig_height is not None:
        fig.set_figheight(fig_height)
    if fig_width is not None:
        fig.set_figwidth(fig_width)
    subplot = 1
    for col in corr_matrix.columns:
        for idx in corr_matrix.index:
            plt.subplot(n, n, subplot)
            ax = axes[corr_matrix.columns.get_loc(col)][
                corr_matrix.index.get_loc(idx)]
            if col != idx:
                plt.scatter(dataframe[idx], dataframe[col], **kwargs)
                fit_X, fit_y = linear_fit(dataframe[idx], dataframe[col])
                plt.plot(fit_X, fit_y, color='r')
                at = AnchoredText(
                    round(corr_matrix[col][idx], 2),
                    prop=dict(size=12),
                    frameon=True,
                    loc='upper left',
                )
                at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
                ax.add_artist(at)
            else:
                plt.hist(dataframe[col], bins=10, edgecolor='black')
            if subplot % n == 1:
                plt.ylabel(col)
            else:
                plt.setp(ax.get_yticklabels(), visible=False)
            if subplot / n > n - 1:
                plt.xlabel(idx)
            else:
                plt.setp(ax.get_xticklabels(), visible=False)
            subplot += 1
    plt.tight_layout()
    plt.savefig('corr_plot.png', dpi=300)
    return None
Esempio n. 13
0
def add_correlation(data,
                    x,
                    y,
                    method='pearson',
                    signif=2,
                    loc='upper left',
                    fontfamily='Arial',
                    ax=None,
                    **kwargs):
    """Add correlation to a scatterplot

    Parameters
    ----------
    data: DataFrame
        DataFrame with columns x and y, same data used to create the plot
    x: str
        x variable to correlate
    y: str
        y variable to correlate
    method: str, optional
        pearson or spearman
    signif: int, optional
        number of significant figures
    loc: string, optional
        location of label, passed to matplotlib.offsetbox.AnchoredText
    size: int, optional
        text size
    fontfamily: str, optional
        text font family
    ax: Axis object, optional
        Plot to add correlation to
    **kwargs
        Other key word arguments passed to text object

    Returns
    -------
    matplotlib.axes.Axes
    """
    r = calculate_correlation(data, x, y, method)
    label = 'r = ' + str(round(r[0], signif))
    text = AnchoredText(label,
                        loc=loc,
                        frameon=False,
                        prop=dict(fontfamily=fontfamily, **kwargs))
    if ax is None:
        ax = plt.gca()
    ax.add_artist(text)
    return ax
Esempio n. 14
0
def plot_reg_performance(df, density_bins=80):
    '''
    Display true vs. predicted TBR in a density scatter plot.
    Requires a data frame with tbr and tbr_pred columns.
    If density_bins are None, then a regular (non-density-colored) plot is used.
    '''
    xs = df['tbr'].to_numpy()
    ys = df['tbr_pred'].to_numpy()

    linreg = Ridge().fit(xs.reshape(-1, 1), ys.reshape(-1, 1))
    ys_fit = linreg.predict(xs.reshape(-1, 1))

    fig, ax = plt.subplots()

    if density_bins is None:
        ax.scatter(xs, ys, s=5, label='Data')
    else:
        density_scatter(xs, ys, ax=ax, bins=density_bins, s=5, label='Data')

    ax.plot(xs, xs, '--', c='k', linewidth=1,
            dashes=[5, 10], label='Ideal model')
    ax.plot(xs, ys_fit, '--', c='r', linewidth=1,
            dashes=[5, 10], label='Trained model')

    ax.set_xlabel('True TBR')
    ax.set_ylabel('Predicted TBR')
    ax.legend(loc='lower right')

    metric_text = ''

    # TODO: this is imperfect as there may be other non-input columns in the data frame
    in_columns = list(df.columns)
    in_columns.remove('tbr')
    in_columns.remove('tbr_pred')

    for init_metric in get_metric_factory().values():
        metric = init_metric()

        if metric_text:
            metric_text += '\n'
        metric_value = metric.evaluate(
            df[in_columns], df['tbr'].to_numpy(), df['tbr_pred'].to_numpy())
        metric_text += f'${metric.latex_name}$ = {metric_value:0.06f}'

    anchored_text = AnchoredText(metric_text, loc=2)
    ax.add_artist(anchored_text)

    return fig, ax
Esempio n. 15
0
def titlebox(ax, text, color,  bgcolor=None, size=8, boxsize="10%", pad=0.02,
            loc=10, **kwargs):
    """Sets a colored box about the title with the width of the plot"""
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("top", size=boxsize, pad=pad)
    cax.get_xaxis().set_visible(False)
    cax.get_yaxis().set_visible(False)
    cax.spines['top'].set_visible(True)
    cax.spines['right'].set_visible(True)
    plt.setp(cax.spines.values(), color=color)
    if bgcolor != None:
        cax.set_facecolor(bgcolor) 
    else:
        cax.set_facecolor('white')
    at = AnchoredText(text, loc=loc, frameon=False, prop=dict(size=size, color=color))
    cax.add_artist(at)
Esempio n. 16
0
    def _add_label(self, label: str, value: float):
        ''' Adds a label and value to the plot's legend

        Args:
            label (str): name of the label
            value (int, float): value of the label
        '''

        string = '{}: '.format(label) + '%.3f' % value
        if self._labels is None:
            self._labels = string
        else:
            self._labels += '\n' + string
        text_box = AnchoredText(self._labels, frameon=True, loc=4, pad=0.5)
        plt.setp(text_box.patch, facecolor='white', edgecolor='w')
        plt.gca().add_artist(text_box)
Esempio n. 17
0
def gauss_fit_column(input_file):
    output_pdf2 = input_file[:-16] + 'fit_columns.pdf'
    with tb.open_file(input_file + '.h5', 'r+') as in_file_h5:
        data = np.sum(in_file_h5.root.HistOcc[:], axis=0)
        data1 = np.sum(in_file_h5.root.HistOcc[:], axis=0)
        data1 = np.concatenate(data1)

        y, amplitude, mu, sigma = 100, np.amax(data1), 33., 30.
        a, b, c, m = 0.1, 0.001, 2, 0.001  # a*x + b*x**2 + m

        xticks = np.linspace(0, 20, 9, endpoint=True)
        xtick_data = [1, 10, 20, 30, 40, 50, 60, 70, 80]
        columns = np.linspace(1, 81, 80, endpoint=False)

        coeff, _ = curve_fit(f=gauss,
                             xdata=columns,
                             ydata=data1,
                             p0=(y, amplitude, mu, sigma, a, b, m),
                             bounds=(0.001, 1000000))  #
        #         print coeff[-4:]
        #         print coeff[1],coeff[2],coeff[3]
        #         print np.amax(data1)
        plt.clf()
        plt.title('Occupancy in x on second plane'
                  )  #('Occupancy per column on second plane')
        plt.grid()
        plt.xlabel('mm')  #('row')
        plt.ylabel('#')
        plt.bar(range(1, 81), data1, label='entries per column')
        plt.plot(columns,
                 gauss(columns, *coeff),
                 label='fit',
                 color='crimson',
                 linewidth=2.5,
                 alpha=0.8)
        plt.xticks(xtick_data, xticks)
        plt.legend()
        ax = plt.axes()
        box = AnchoredText('mu = %.1f mm \nsigma = %.2f mm \nA = %.f' %
                           (coeff[2] * 0.25, coeff[3] * 0.25, coeff[1]),
                           loc=2)
        ax.add_artist(box)
        plt.savefig(output_pdf2)


#         print output_pdf2
    return coeff[1] * coeff[3] * np.sqrt(2 * np.pi) / np.sum(data1)
Esempio n. 18
0
def progress(i, y, ax1, ax2, n, test, fig):
    #    if i==1:
    #style.use('fivethirtyeight')
    #fig = plt.figure()
    #ax1 = fig.add_subplot(1,1,1)
    #plt.ylabel('convergence')
    #plt.xlabel('iteration')
    #    else:
    err_range = (np.amax(y) - np.amin(y)) / 2.0

    #ax2.cla()
    ax1.errorbar(i, np.mean(y), yerr=err_range, fmt='o')
    if i != 0:
        #Artist.remove(ax1.texts)
        #fig.text.remove()
        #print(ax1.get_extents)
        [Artist.remove(txt) for txt in ax1.texts]
    [txt.set_visible(False) for txt in ax1.texts]
    #if i != 0:
    #    textvar = ax1.texts
    #textvar.remove(True)
    #ax1.remove(textvar)
    #ax1.texts.set_visible(False)
    #    [txt.set_visible(False) for txt in ax1.texts]
    #for txt in ax1.texts:
    #txt.set_visible(False)

    text_box = AnchoredText(np.amin(y), frameon=True, loc=1, pad=0.5)
    plt.setp(text_box.patch, facecolor='white', alpha=1)
    ax1.add_artist(text_box)

    #plot_text = ax1.text(3, 9, np.amin(y),bbox=dict(facecolor='white', alpha=1))
    #plot_text._bbox_patch._mutation_aspect = 0.1
    #plot_text.get_bbox_patch().set_boxstyle("square", pad=1)

    #ax2.text(n,4,np.amin(y),bbox=dict(facecolor='white', alpha=1))

    ax2.plot(range(3), y, c=[0, 0, 0])

    #ax2.xaxis.font(12)
    ax2.tick_params(labelsize='small')

    #fig.clf()
    #ax2.draw()

    #ax2.text()
    plt.pause(0.5)  #time it waits for plot to update
Esempio n. 19
0
def titlebox(ax,
             text,
             color,
             bgcolor=None,
             size=8,
             boxsize=0.1,
             pad=0.05,
             **kwargs):
    """
    Sets a colored title box above the plot, spanning the entire plot width. 
    
    Parameters
    ----------
    ax : matplotlib axis object
      The axis on which you want to add the titlebox.
    text: str
      The title tect
    bgcolor: str or None
      The background color of the title box. Default is no color (blank).
    size:  int
      Size of the text font
    boxsize: float [0, 1]
      Fraction of the total plot height to be occupied by the box. Default is 10% (0.1).
    pad: float
      The padding space between the title box and the top of the plot. 
     
    """
    boxsize = str(boxsize * 100) + '%'
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("top", size=boxsize, pad=pad)
    cax.get_xaxis().set_visible(False)
    cax.get_yaxis().set_visible(False)
    cax.spines["top"].set_visible(False)
    cax.spines["right"].set_visible(False)
    cax.spines["bottom"].set_visible(False)
    cax.spines["left"].set_visible(False)

    plt.setp(cax.spines.values(), color=color)
    if bgcolor != None:
        cax.set_facecolor(bgcolor)
    else:
        cax.set_facecolor("white")
    at = AnchoredText(text,
                      loc=10,
                      frameon=False,
                      prop=dict(size=size, color=color))
    cax.add_artist(at)
Esempio n. 20
0
    def _build_plot(self, integr):
        super()._clean_frame()
        f = Figure(figsize=(5, 5), dpi=100)
        a = f.add_subplot()
        a.plot(integr.start_x, integr.start_y, "b")

        #a.spines['left'].set_position('zero')
        #a.spines['bottom'].set_position('zero')
        #a.spines['top'].set_visible(False)
        #a.spines['right'].set_visible(False)
        str_answ = "rectangle = {0}\ntrapezoid = {1}\nsimpson = {2}".format(
            integr.rectangle(), integr.trapezoid(), integr.simpson())
        a.add_artist(AnchoredText(str_answ, loc=2))

        canvas = FigureCanvasTkAgg(f)
        super()._destroy_objects.append(canvas._tkcanvas)
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
Esempio n. 21
0
    def field_count_hist(grp_df, rate_var, vol_var, title, xlab, filedesc):
        # Annotation Box Stats
        y = grp_df['YEAR'].mean()
        total_area = grp_df['Area_acres'].sum()
        total_vol = grp_df[vol_var].sum()
        m = total_vol / total_area.round(1)

        # Bins
        et_bins = np.linspace(bin_min, bin_max,
                              ((bin_max - bin_min) / bin_size) + 1)

        # Make Figure
        font_size = 12
        ann_font_size = 10
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.hist(grp_df[rate_var], bins=et_bins, align='mid', edgecolor='black')
        ax.set_title(title, size=font_size)
        ax.set_xlabel(xlab, size=font_size)
        ax.set_ylabel('Field Count', size=font_size)
        ax.set_xticks(np.arange(0, bin_max + (2 * bin_size), 2 * bin_size))
        ax.tick_params(axis='x', labelsize=font_size)
        ax.tick_params(axis='y', labelsize=font_size)
        ymin, ymax = plt.ylim()  # return the current ylim
        plt.ylim((ymin, ymax + ymax * 0.3))  # shift ymax for annotation space
        # Add mean vertical line
        ax.axvline(m, color='gray', linestyle='dashed', linewidth=1)

        # Add Annotation Text Box
        antext = ('Year {:.0f}\n' + 'Mean ET = {:.1f} ft\n' +
                  'Total Area = {:.1f} acres\n' +
                  'ET Volume = {:.1f} ac-ft').format(y, m, total_area,
                                                     total_vol)
        at = AnchoredText(antext,
                          prop=dict(size=ann_font_size),
                          frameon=True,
                          loc=2)
        at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
        ax.add_artist(at)
        # Save Figure
        file_name = '{:.0f}_{}_Fields'.format(y, filedesc)
        fig.tight_layout(pad=3)
        plt.savefig(os.path.join(output_folder, file_name), dpi=300)
        plt.close(fig)
        fig.clf()
        return True
Esempio n. 22
0
    def plotStats(self, ax, lines):
        """Make the stats box 'plot'.

        Parameters
        ----------
        ax : `maplotlib.axes`
            Axes to use.
        lines : `list` of `str`
            The data to include in the text box
        """
        text = "\n".join([line for line in lines])

        stats_text = AnchoredText(text, loc="center", pad=0.5,
                                  prop=dict(size=14, ma="left", backgroundcolor="white",
                                            color="black", family='monospace'))
        ax.add_artist(stats_text)
        ax.axis('off')
Esempio n. 23
0
def plot_fitted_curve(d, X,Y,output):
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.plot(X, Y, 'ro', markersize=0.5)
    ax1.plot(X, output[0], '--')
    ax1.plot(X, output[1])
    ax1.set_ylabel(d['abbr']+' '+d['unit'])
    if output[2]>0.: # moves legend based on direction of trend
        loc=2
    elif output[2]<0.:
        loc=1
    txt = AnchoredText('RMSE='+str(output[3])+' '+d['unit']+'\n$r^2$='+str(output[4])+'%', loc=loc)
    ax1.add_artist(txt)
    plt.xticks(np.arange(0, len(X), 12), years)
    plt.savefig(savepath+d['species']+'_nonlin_regression.png')
    plt.close()
    return
Esempio n. 24
0
    def add_stamp(self, text=None, **kwargs):
        """Add common stamp with text.

        NOTE add_stamp cannot be used on a subplot that has been de-selected
        and then re-selected. It will write over existing text.

        """
        if self.stamp != '':
            stamp = tex_join('\n', self.stamp, text)
        else:
            stamp = text
        if self.loc == 'inside':
            a_text = AnchoredText(tex_dollars(stamp), loc=2, frameon=False,
                                  **kwargs)
            plt.gca().add_artist(a_text)
        elif self.loc == 'outside':
            plt.gca().set_title(tex_dollars(stamp))
Esempio n. 25
0
def AddAnchored(*args,**kwargs):
    """
    Init definition: AnchoredText(self, s, loc, pad=0.4, borderpad=0.5, prop=None, **kwargs)
    Docstring:       AnchoredOffsetbox with Text
    Init docstring:
    *s* : string
    *loc* : location code
    *prop* : font property
    *pad* : pad between the text and the frame as fraction of the font
            size.
    *borderpad* : pad between the frame and the axes (or bbox_to_anchor).

    other keyword parameters of AnchoredOffsetbox are also allowed.
    """

    at = AnchoredText(*args,**kwargs)
    plt.gca().add_artist(at)
Esempio n. 26
0
def add_inner_title(title, loc, ax=None, size=None, **kwargs):
    if ax == None:
        ax = plt.gca()
    from matplotlib.offsetbox import AnchoredText
    from matplotlib.patheffects import withStroke
    if size is None:
        size = dict(size=plt.rcParams['legend.fontsize'])
    at = AnchoredText(title,
                      loc=loc,
                      prop=size,
                      pad=0.7,
                      borderpad=0.01,
                      frameon=False,
                      **kwargs)
    ax.add_artist(at)
    at.txt._text.set_path_effects([withStroke(foreground="w", linewidth=3)])
    return at
Esempio n. 27
0
def plot_fitted_curve(d, X, Y, output, times, timestep, savepath=''):
    if timestep == 'H':
        t = 'hourly'
        s = 0.05
        l = 0.2
    elif timestep == 'M':
        t = 'monthly'
        s = 0.5
        l = 2
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.plot(times, Y, 'ro', markersize=s)
    ax1.plot(times, output[0], '--', linewidth=l)
    ax1.plot(times, output[1], 'k')
    ''' Uncomment to add linear trendline and print trend 
    z = np.polyfit(X,Y,1)
    p = np.poly1d(z)    
    ax1.plot(times, p(X), '--', color='k', alpha=0.7)
    if timestep == 'M':
        tt = 12
    else:
        tt=8760
    print('Linear trend = ', np.round(z[0]*tt,2), d['unit'], '$yr^{-1}$')
    '''
    if 'abbr' in d:
        ax1.set_ylabel(d['abbr'] + ' (' + d['unit'] + ')')
    else:
        ax1.set_ylabel(d['longname'] + ' (' + d['unit'] + ')')

    if 'yscale' in d:
        yb, yt = ax1.get_ylim()
        if yt - yb > 1e4:
            ax1.set_yscale(d['yscale'])
    if output[2] > 0.:  # moves legend based on direction of trend
        loc = 2
    elif output[2] < 0.:
        loc = 1
    txt = AnchoredText('RMSE=' + str(output[3]) + ' ' + d['unit'] +
                       '\n$r^2$=' + str(output[4]) + '%',
                       loc=loc)
    ax1.add_artist(txt)
    plt.savefig(savepath + d['variable'] + '/' + d['variable'] + '_' + t +
                '_mean.png',
                dpi=200)
    plt.close()
    return
def plot(df: pd.DataFrame, model: MaterialModel, filename: str):
    dfc = df.copy()
    dfc = dfc.sort_values(by="strain")
    cls = model.__class__

    dfc_c = dfc.copy()
    dfc_c['stress'] = np.nan
    dfc_c['strain'] = dfc_c['strain'] * 4 / 3

    dfc['comp_stress'] = dfc.apply(lambda row: model(row['strain'], row['strain_rate'], row['temperature']), axis=1)
    dfc_c['comp_stress'] = dfc_c.apply(lambda row: model(row['strain'], row['strain_rate'], row['temperature']), axis=1)

    dfc['stress'] = dfc['stress'] / 1e6
    dfc['comp_stress'] = dfc['comp_stress'] / 1e6
    dfc_c['stress'] = dfc_c['stress'] / 1e6
    dfc_c['comp_stress'] = dfc_c['comp_stress'] / 1e6

    grouped = dfc.groupby(['strain_rate', 'temperature'])
    grouped_c = dfc_c.groupby(['strain_rate', 'temperature'])

    ncols = 4
    nrows = int(np.ceil(grouped.ngroups / ncols))

    fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(24, 18), sharey=False, facecolor='1.0')

    flattened_axes = axes.flatten()
    for ax in flattened_axes:
        ax.set_visible(False)

    for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
        ax.set_visible(True)
        grouped_c.get_group(key).plot(x='strain', y='comp_stress', c='red', ax=ax, label='Model')
        grouped.get_group(key).plot(x='strain', y='stress', ax=ax, label='Experiment')
        ax.set_title(labels[cls])
        ax.set_xlabel('True strain')
        ax.set_ylabel('True stress [MPa]')

        box_text = 'Strain rate: {}s-1\nTemperature: {}K'.format(*key)
        text_box = AnchoredText(box_text, frameon=True, loc='lower left', pad=0.1)
        plt.setp(text_box.patch, facecolor='white', alpha=0.85)
        ax.add_artist(text_box)
        ax.legend(loc='lower right', ncol=1, framealpha=0.85, edgecolor='black', fancybox=False)

        plt.subplots_adjust(wspace=0.3, hspace=0.35)
    plt.savefig(filename)
    plt.close(fig)
Esempio n. 29
0
def plot_graph(series_dict, xlab, threshold):
    fig, ax = plt.subplots(1, figsize=(16, 9))
    j = 0
    for country, series in series_dict.items():
        x = np.arange(0, series.size)
        for i in x:
            if i != max(x):
                ax.plot(
                    x[i:i + 2],
                    series[i:i + 2],
                    alpha=0.1 + 0.9 * float(i) / (series.size),
                    color=cmap(j),
                    label=country,
                )
            else:
                ax.plot(
                    x[i:i + 2],
                    series[i:i + 2],
                    alpha=0.1 + 0.9 * float(i) / (series.size),
                    color=cmap(j),
                    label=country,
                    marker="o",
                    markevery=[-1],
                )
        ax.text(x[-1] + 0.5, series[-1], country, color=cmap(j))
        j += 1
        if j > cmap.N:
            j = 0
        # ax.plot(x, series, label=country, marker="o", markevery=[-1])

    # for line in ax.lines:
    #     x, y = line.get_xydata()[-1]
    #    ax.text(x + 0.5, y, line.get_label(), color=line.get_color())

    at = AnchoredText(
        f"Source: https://github.com/CSSEGISandData/COVID-19, {dt.datetime.today()}",
        prop=dict(size=8),
        loc=4,
    )
    ax.add_artist(at)
    ax.set_xlim(0, ax.get_xlim()[1])
    ax.set_xlabel(f"Days after {threshold} {xlab}", fontsize=20)
    ax.set_ylabel(f"Number of {xlab}", fontsize=20)
    ax.set_yscale("log")
    plt.tight_layout()
    return fig, ax
Esempio n. 30
0
def plot_lines(text, *args, **kwargs):
    patchopts = kwargs.pop('patchopts', None)
    sep = kwargs.pop('separator', u'\n')
    if not isinstance(text, str):
        linefmt = kwargs.pop('linefmt', u'{}')
        if isinstance(linefmt, str):
            fmt = linefmt
            linefmt = lambda *a: fmt.format(*a)
        lines = []
        lst = [
            linefmt(*line) if isinstance(line,
                                         (list, tuple)) else linefmt(line)
            for line in text
        ]
        text = sep.join(lst)

    header, footer = kwargs.pop('header', None), kwargs.pop('footer', None)
    if header: text = header + sep + text
    if footer: text = text + sep + footer

    if kwargs.pop('dump', False):
        print('Text:\n', text, sep='')

    # if bbox is None: bbox = dict(facecolor='white', alpha=1)
    outside = kwargs.pop('outside', None)
    loc = kwargs.pop('loc', None)
    if outside:
        loc = 'upper left'
        kwargs.setdefault('borderpad', 0.0)
    if isinstance(loc, str):
        loc = location_numbers[loc]
    if not loc:
        loc = 1
    prop = kwargs.pop('prop', {})
    ax = plt.gca()
    if outside:
        kwargs['bbox_to_anchor'] = outside
        kwargs['bbox_transform'] = ax.transAxes

    at = AnchoredText(text, loc, *args, prop=prop, **kwargs)
    if patchopts:
        at.patch.set(**patchopts)

    ax.add_artist(at)
    return at
Esempio n. 31
0
def make_map(projection=ccrs.PlateCarree()):
    """                                                                          
    Generate fig and ax using cartopy                                                                    
    input: projection                                                                                    
    output: fig and ax                             
    """
    alpha = 0.5
    subplot_kw = dict(projection=projection)
    fig, ax = plt.subplots(figsize=(9, 13), subplot_kw=subplot_kw)
    gl = ax.gridlines(draw_labels=True)
    gl.xlabels_top = gl.ylabels_right = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER

    # Put a background image on for nice sea rendering.
    ax.stock_img()

    # Create a feature for States/Admin 1 regions at 1:50m from Natural Earth
    states_provinces = cfeature.NaturalEarthFeature(
        category='cultural',
        name='admin_1_states_provinces_lines',
        scale='50m',
        facecolor='none')

    SOURCE = 'Natural Earth'
    LICENSE = 'public domain'

    ax.add_feature(cfeature.LAND, zorder=0, alpha=alpha)
    ax.add_feature(cfeature.COASTLINE, zorder=1, alpha=alpha)
    ax.add_feature(cfeature.BORDERS, zorder=1, alpha=2 * alpha)

    ax.add_feature(states_provinces, edgecolor='gray', zorder=1)

    # Add a text annotation for the license information to the
    # the bottom right corner.
    text = AnchoredText(r'$\mathcircled{{c}}$ {}; license: {}'
                        ''.format(SOURCE, LICENSE),
                        loc=4,
                        prop={'size': 9},
                        frameon=True)
    ax.add_artist(text)

    ax.set_xlim(-132, -65)  #lon limits
    ax.set_ylim(20, 55)  #lat limits
    return fig, ax
Esempio n. 32
0
def main(args):
    """ execute the code """
    prs_true, truebeta = TruePRS(args.outprefix, args.bfile, args.h2, 
                                 args.ncausal, args.plinkexe, args.causalmean,
                                 )
    prs_true = liabilities(args.outprefix, args.h2, args.ncausal, prs_true, 
                           noenv=args.noenv)
    if args.GWAS:
        gwas = PlinkGWAS(args.plinkexe, args.bfile, args.outprefix, args.covs, 
                  args.nosex, args.threads, args.maxmem, validate=args.validate)
        merged = gwas.merge(truebeta, on='SNP')
        slope, intercept, r2, p_value, std_err = stats.linregress(merged.beta, 
                                                                  merged.BETA)
        ax = merged.plot.scatter(x='beta', y='BETA', s=2, alpha=0.5)
        ax.add_artist(AnchoredText('$R^{2} = %.3f $' % r2**2, 2))  
        plt.tight_layout()
        plt.savefig('%s_truebetavsinferred.png'%(args.outprefix))  
        plt.close()
Esempio n. 33
0
    def plot_topology(self, circuits, equipments_multipoint, partition_by_station_dict, cities, destdir):

        (ymin, xmin, ymax, xmax) = equipments_multipoint.buffer(0.2).bounds
        sidebar_width = (xmax - xmin) * 0.4
        sidebar_height = ymax - ymin
        self.root.info('Plotting Voltages %s' % str((ymin, xmin, ymax, xmax)))
        ax = plt.axes(projection=ccrs.PlateCarree())
        ax.set_extent([xmin, xmax + sidebar_width, ymin, ymax])

        for circuit in circuits:
            plt.plot(circuit.members[0].lon, circuit.members[0].lat, marker='s', markerfacecolor='black',
                     linestyle="None", markersize=1, zorder=10, transform=ccrs.PlateCarree())
            plt.plot(circuit.members[-1].lon, circuit.members[-1].lat, marker='s', markerfacecolor='black',
                     linestyle="None", markersize=1, zorder=10, transform=ccrs.PlateCarree())
            # ax.annotate(circuit.members[0].id, (circuit.members[0].lon, circuit.members[0].lat))
            # ax.annotate(circuit.members[-1].id, (circuit.members[-1].lon, circuit.members[-1].lat))

            for line in circuit.members[1:-1]:
                x, y = line.geom.xy
                plt.plot(x, y, color=self.color_dict[line.voltage.split(';')[0]], alpha=1,
                         linewidth=self.thickness_dict[line.voltage.split(';')[0]], solid_capstyle='round',
                         zorder=self.zorder_dict[line.voltage.split(';')[0]], transform=ccrs.PlateCarree())

        if cities:
            for city in cities:
                if xmax > city.lon > xmin and ymax > city.lat > ymin:
                    plt.plot(city.lon, city.lat, marker='s', markerfacecolor='#ff0000', linestyle="None",
                             markersize=log(city.population, 10), zorder=1.5)
                    if city.population >= 200000 and 'DEUTSCHLAND' not in city.name:
                        label = city.name
                        ax.annotate(label, (city.lon, city.lat))

        # sidebar
        ax.add_patch(patches.Rectangle((xmax, ymin), sidebar_width, sidebar_height, facecolor="white", zorder=10))
        im = image.imread('../util/logo2.png')
        ax.imshow(im, aspect='auto', extent=(
            xmax + sidebar_width / 4, xmax + 3 * sidebar_width / 4, ymax - sidebar_height / 3,
            ymax - sidebar_height / 2),
                  zorder=11)
        text = AnchoredText('(c) OpenGridMap', loc=1, prop={'size': 12}, frameon=True, borderpad=0.8)
        text.set_zorder(11)
        ax.add_artist(text)
        plt.plot([], [], marker='s', markerfacecolor='black', linestyle="None", markersize=1, zorder=11,
                 label='station')
        for voltage in self.color_dict.keys():
            label = str(voltage) + 'V'
            plt.plot([], [], color=self.color_dict[voltage], lw=self.thickness_dict[voltage], zorder=11, label=label)
        l = plt.legend(numpoints=1, loc=4)
        l.set_zorder(11)

        plt.savefig(destdir + '/topology.png', bbox_inches='tight', pad_inches=0, dpi=600)

        ax.stock_img()
        plt.savefig(destdir + '/topology_geographical.png', bbox_inches='tight', pad_inches=0, dpi=600)

        countries = cfeature.NaturalEarthFeature(
            category='cultural',
            name='admin_0_countries',
            scale='10m',
            facecolor='none')
        states_provinces = cfeature.NaturalEarthFeature(
            category='cultural',
            name='admin_1_states_provinces_shp',
            scale='10m',
            facecolor='none')
        ax.add_feature(states_provinces, edgecolor='#ffffff', linewidth=0.3)
        ax.add_feature(countries, edgecolor='#333333', linewidth=0.5)
        kw = dict(resolution='50m', category='cultural', name='populated_places_simple')
        places_shp = shpreader.natural_earth(**kw)
        shp = shpreader.Reader(places_shp)
        for record, place in zip(shp.records(), shp.geometries()):
            if xmax > place.x > xmin and ymax > place.y > ymin:
                name = record.attributes['name'].decode('latin-1')
                plt.plot(place.x, place.y, marker='o', markerfacecolor='#ff0000', linestyle="None",
                         markersize=2, zorder=11)
                ax.annotate(name, (place.x, place.y), fontsize=4)
        plt.savefig(destdir + '/topology_administrative.png', bbox_inches='tight', pad_inches=0, dpi=600)

        # Voronoi partitions
        if partition_by_station_dict:
            for station in partition_by_station_dict.keys():
                partition_polygon = partition_by_station_dict[station]
                if hasattr(partition_polygon, 'geoms'):
                    for polygon in partition_polygon:
                        Plotter.plot_polygon(polygon, '#888888', zorder=2)
                else:
                    Plotter.plot_polygon(partition_polygon, '#888888', zorder=2)
            plt.plot([], [], color='#888888', lw=2, zorder=5, label='Voronoi partitions')
            plt.savefig(destdir + '/topology_voronoi.png', bbox_inches='tight', pad_inches=0, dpi=600)
        plt.clf()
        plt.close()