def scatter(x,
            y,
            label=None,
            title=None,
            x_lab=None,
            y_lab=None,
            add_trend_line=False,
            line_color='r',
            line_char=None,
            fig_size=(15, 7.5)):
    '''
    Makes a bar chart from positions (pos) and heights. Use labels to replace pos elements.
    '''
    plt.figure(figsize=(fig_size))

    plt.scatter(x, y, label=label)
    if add_trend_line:
        m, b, r2, pv, std_error = linreg(x, y)
        lab = ''
        if line_char is not None:
            lab = _make_reglin_labels(r2, pv, std_error, line_char)
        else:
            lab = None
        plt.plot(x, m * x + b, '-', c=line_color, label=lab)
    if (label is not None) and (line_char is not None):
        plt.legend()
    if title is not None:
        plt.title(title)
    if y_lab is not None:
        plt.ylabel(y_lab)
    if x_lab is not None:
        plt.xlabel(x_lab)
    plt.show()
    def __init__(self, asuid, species, length, exo, endo, total, N, mm, Sec):
        self.__asuid__ = asuid
        self.__species__ = species.lower()

        self.__length__ = float(length)
        self.__exo__ = float(exo)
        self.__endo__ = float(endo)
        self.__total__ = float(total)

        self.__N__ = array(N)
        self.__mm__ = array(mm) - min(mm)
        self.__Sec__ = array(Sec) - Sec[0]

        self.__sigmaN__ = self.__N__ / self.__total__  #P/A0
        self.__epsilonN__ = (self.__mm__ / self.__length__)  #dL/L0
        self.__sigmaT__ = self.__sigmaN__ * (1 + self.__epsilonN__)  #s(1+e)
        self.__epsilonT__ = ln(1 + self.__epsilonN__)  #ln(1+e)

        self.__fmax__ = max(N)
        self.__uts__ = max(self.__sigmaN__)  #evaluated from engineering stress

        self.__dmax__ = max(self.__mm__)
        self.__ufs__ = max(
            self.__epsilonN__)  #evaluated from engineering strain

        self.__Eindex__ = []
        lower = self.__ufs__ * 0
        upper = self.__ufs__ * 0.33
        self.__Eindex__.append(
            len([
                x for x in takewhile(lambda x: x[1] <= lower,
                                     enumerate(self.__epsilonN__))
            ]))
        self.__Eindex__.append(
            len([
                y for y in takewhile(lambda y: y[1] <= upper,
                                     enumerate(self.__epsilonN__))
            ]))
        xvals = self.__epsilonN__[self.__Eindex__[0]:self.__Eindex__[1]]
        yvals = self.__sigmaN__[self.__Eindex__[0]:self.__Eindex__[1]]
        self.__E__ = linreg(
            xvals, yvals)  #engineering stress and strain via Hooke's Law

        self.__Etanl__ = self.__E__[0]

        t_upper = 0
        t_lower = 0

        for i in range(len(self.__epsilonN__) - 1):
            ub = self.__epsilonN__[i + 1]
            lb = self.__epsilonN__[i]
            uh = self.__sigmaN__[i + 1]
            lh = self.__sigmaN__[i]
            t_upper += (ub - lb) * uh
            t_lower += (ub - lb) * lh

        self.__U__ = (t_upper + t_lower) / 2
    def recalcE(self,
                lower=0.00,
                upper=0.015,
                graphical=False,
                normal=False,
                limits='E_limits.txt'):
        self.__Eindex__ = []
        if normal:
            eps = self.__epsilonT__
            sig = self.__sigmaT__
        else:
            eps = self.__epsilonN__
            sig = self.__sigmaN__
        if graphical:
            file = open(limits, 'r')
            for line in file:
                asuid, species, lims = line[:-1].split('|', 2)
                if asuid == self.__asuid__:
                    x, y = lims.split(',')
                    lowerg = float(x[1:])
                    upperg = float(y[:-1])
                else:
                    pass
            self.__Eindex__.append(
                len([
                    x for x in takewhile(lambda x: x[1] <= lowerg,
                                         enumerate(self.__Sec__))
                ]))
            self.__Eindex__.append(
                len([
                    y for y in takewhile(lambda y: y[1] <= upperg,
                                         enumerate(self.__Sec__))
                ]))

        else:
            self.__Eindex__ = [0, 1]
            low = False
            high = False
            while (not low) and (not high):
                for i, c in enumerate(self.__epsilonN__):
                    if (c >= lower) and (not low):
                        self.__Eindex__[0] = i
                        low = True
                    elif (c >= upper) and (not high):
                        self.__Eindex__[1] = i
                        high = True
                    else:
                        pass
        xvals = eps[self.__Eindex__[0]:self.__Eindex__[1]]
        yvals = sig[self.__Eindex__[0]:self.__Eindex__[1]]

        self.__E__ = linreg(
            xvals, yvals)  #engineering stress and strain via Hooke's Law
def least_squares_plot(configs):
    """
    This function is plotting a points with its errors on the 2D plane.
    :param configs:
    It is a dictionary containing the informations of:
        - Horizontal size of the plot
            * By default: "xsize": 16
        - Vertical size of the plot
            * By default: "ysize": 9
        - Symbol used to denote the point
            * By default: "symbol": 'x'
        - Name of input file
            * By default: "nameofinput": 'data.txt'
        - Name of y axis
            * By default: "nameofvalue": "$X$ value"
        - Name of x axis
            * By default: "nameofarg": "argument $x$"
        - Name of output file with extension
            * By default: "nameofoutput": '0'
        - If show legend:
            * By default: "showlegend": '0'

    """
    arrofdata = np.loadtxt(configs['nameofinput'])
    x = arrofdata[:, 0]
    y = arrofdata[:, 1]
    a, b, r, _, da = linreg(x, y)
    a, b = a.round(), b.round()
    basex = np.linspace(min(x), max(x), 10000)

    pplt.figure(figsize=(configs['xsize'], configs['ysize']))
    pplt.errorbar(x, y, yerr=da, marker=configs['symbol'], color=(200/255, 80/255, 80/255),
                  label=configs['nameofvalue'], ls='')
    pplt.plot(basex, basex * a + b, label="regression line, a = {0}, b = {1}".format(a, b))
    pplt.xlabel(configs['nameofarg'])
    pplt.ylabel(configs['nameofvalue'])
    pplt.tight_layout(0.1)

    if configs['showlegend'] != '0':
        leg = pplt.legend()
        leg.draggable()

    if configs['nameofoutput'] != '0':
        pplt.savefig(configs['nameofoutput'])
    else:
        pplt.show()
def xyplot(spec_set, save=True):
    spl = []
    regx = []
    regy = []

    fig = plt.figure()
    ax = fig.add_subplot(111)

    #plt.ylim(0,0.04)
    #plt.xlim(0,8)
    xlab = 'test (units)'
    ylab = 'test (units)'
    ax.set_xlabel(xlab)
    ax.set_ylabel(ylab)
    ax.set_title('{}_vs_{}.pdf'.format(xlab, ylab))

    car = mpatches.Patch(color='r', label='caryae')
    pro = mpatches.Patch(color='lightcoral', label='proboscideus')
    uni = mpatches.Patch(color='b', label='uniformis')
    hum = mpatches.Patch(color='skyblue', label='humeralis')
    sul = mpatches.Patch(color='dodgerblue', label='sulcatulus')
    vic = mpatches.Patch([], [], color='navy', label='victoriensis')
    ax.legend(handles=[car, pro, hum, sul, uni, vic], loc=4, fontsize=7)

    for spec in spec_set:
        new_l = spec.ufs() * 0.67
        new_u = spec.ufs() * 1.00
        spec.recalcE(lower=new_l, upper=new_u, graphical=False, normal=False)
        x = ln(spec.length())
        y = ln(spec.Etanl())
        #spec.uts() / spec.ufs()

        if spec.species() == 'caryae':
            ax.plot(x, y, color='r', marker='o')
        elif spec.species() == 'proboscideus':
            ax.plot(x, y, color='lightcoral', marker='o')
        elif spec.species() == 'uniformis':
            ax.plot(x, y, color='b', marker='o')
        elif spec.species() == 'humeralis':
            ax.plot(x, y, color='skyblue', marker='o')
        elif spec.species() == 'sulcatulus':
            ax.plot(x, y, color='dodgerblue', marker='o')
        elif spec.species() == 'victoriensis':
            ax.plot(x, y, color='navy', marker='o')
        else:
            pass

        regx.append(x)
        regy.append(y)
        spl.append(
            str(x) + ' ' + str(y) + ' ' + spec.asuid() + ' ' + spec.species())

    x = array(regx)
    y = array(regy)
    regline = linreg(x, y)
    ax.plot(x, regline[0] * x + regline[1], color='black')
    ax.text(
        0.03,
        3,
        r'$y={:.3f}x+{:.3f}$'.format(regline[0], regline[1]) + '\n' +
        r'$R={:.3f}$'.format(regline[2]) + '\n'
        #+r'$p={:.3f}$'.format(regline[3]),
        + r'$p={0:s}$'.format(as_si(regline[3], 2)),
        fontsize=10)

    for i in sorted(spl):
        print(i)

    plt.show()

    if save:
        fig.savefig('plots/xyplots/{}_vs_{}.pdf'.format(xlab, ylab))
        #plt.close()
    else:
        #plt.close()
        print('Plot not saved!!')

    print('m = {}'.format(regline[0]),
          'b = {}'.format(regline[1]),
          'r = {}'.format(regline[2]),
          'p = {}'.format(regline[3]),
          'std_err = {}'.format(regline[4]),
          sep='\n')
#Opens player running statistics
lf_running = pd.read_csv(
    'C:/Users/jmyou/Desktop/bb_data_project/Left_Hitter_run_Stats.csv')
rf_running = pd.read_csv(
    'C:/Users/jmyou/Desktop/bb_data_project/Right_Hitter_run_Stats.csv')
s_running = pd.read_csv(
    'C:/Users/jmyou/Desktop/bb_data_project/Switch_Hitter_run_Stats.csv')

#Gets rid of NaN values, I did this so the following linear regressions would
#make sense.
lf_running = lf_running.dropna(axis=0)
rf_running = rf_running.dropna(axis=0)
s_running = s_running.dropna(axis=0)

#Linear regressions for each group of batters
l_reg = linreg(lf_running.loc[:, 'sprint_speed'], lf_running.loc[:,
                                                                 'hp_to_1b'])
r_reg = linreg(rf_running.loc[:, 'sprint_speed'], rf_running.loc[:,
                                                                 'hp_to_1b'])
s_reg = linreg(s_running.loc[:, 'sprint_speed'], s_running.loc[:, 'hp_to_1b'])

#Best fit lines of each group of hitters
x = np.array([i for i in range(20, 35)])
yr = r_reg[0] * x + r_reg[1]
yl = l_reg[0] * x + l_reg[1]
ys = s_reg[0] * x + s_reg[1]

residual = yr - yl

#Viridis Colors
vir_v = (71 / 255, 33 / 255, 115 / 255)
vir_b = (46 / 255, 111 / 255, 142 / 255)
Exemple #7
0
def linfit(x, y):
    slope, intercept, rvalue, pvalue, stderr = linreg(np.log(x), np.log(y))
    fit = (x**(slope) * np.exp(intercept))
    return (fit, slope, intercept, rvalue, pvalue, stderr)