Python matplotlib.pyplot.vlines() Examples

The following are 30 code examples of matplotlib.pyplot.vlines(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: scheduler_test.py    From efficientdet-tf with GNU General Public License v3.0 7 votes vote down vote up
def test_scheduler(self):
        epochs = 10

        max_lr = 3e-3
        alpha = 1e-2

        steps_per_epoch = 1024 
        scheduler = optim.WarmupCosineDecayLRScheduler(
            max_lr,
            steps_per_epoch, 
            (steps_per_epoch * (epochs - 1)), alpha=alpha)

        lrs = [scheduler(i) for i in range(epochs * steps_per_epoch)]
        epoch_ends_at = [i * steps_per_epoch for i in range(epochs)]

        print('Last lr', lrs[-1])

        plt.plot(range(epochs * steps_per_epoch), lrs)
        plt.vlines(epoch_ends_at, 0, max_lr)
        plt.show(block=True) 
Example #2
Source File: _find_default_scale.py    From numdifftools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_all_benchmarks(method='forward', order=4, x_values=(0.1, 0.5, 1.0, 5), n_max=11,
                       show_plot=True):

    epsilon = MinStepGenerator(num_steps=3, scale=None, step_nom=None)
    scales = {}
    for n in range(1, n_max):
        plt.figure(n)
        scale_n = scales.setdefault(n, [])
        # for (name, x) in itertools.product( function_names, x_values):
        for name in function_names:
            fun0, dfun = get_function(name, n)
            if dfun is None:
                continue
            fd = Derivative(fun0, step=epsilon, method=method, n=n, order=order)
            for x in x_values:
                r = benchmark(x=x, dfun=dfun, fd=fd, name=name, scales=None, show_plot=show_plot)
                print(r)
                scale = r['scale']
                if np.isfinite(scale):
                    scale_n.append(scale)

        plt.vlines(np.mean(scale_n), 1e-12, 1, 'r', linewidth=3)
        plt.vlines(np.median(scale_n), 1e-12, 1, 'b', linewidth=3)

    _print_summary(method, order, x_values, scales) 
Example #3
Source File: burst_plot.py    From FRETBursts with GNU General Public License v2.0 6 votes vote down vote up
def time_ph(d, i=0, num_ph=1e4, ph_istart=0):
    """Plot 'num_ph' ph starting at 'ph_istart' marking burst start/end.
    TODO: Update to use the new matplotlib eventplot.
    """
    b = d.mburst[i]
    SLICE = slice(ph_istart, ph_istart+num_ph)
    ph_d = d.ph_times_m[i][SLICE][~d.A_em[i][SLICE]]
    ph_a = d.ph_times_m[i][SLICE][d.A_em[i][SLICE]]

    BSLICE = (b.stop < ph_a[-1])
    start, end = b[BSLICE].start, b[BSLICE].stop

    u = d.clk_p # time scale
    plt.vlines(ph_d*u, 0, 1, color='k', alpha=0.02)
    plt.vlines(ph_a*u, 0, 1, color='k', alpha=0.02)
    plt.vlines(start*u, -0.5, 1.5, lw=3, color=green, alpha=0.5)
    plt.vlines(end*u, -0.5, 1.5, lw=3, color=red, alpha=0.5)
    xlabel("Time (s)")


##
#  Histogram plots
# 
Example #4
Source File: draw_pmf.py    From machine-learning-note with MIT License 6 votes vote down vote up
def custom_made_discrete_dis_pmf():
    """
    https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_discrete.html
    :return:
    """
    xk = np.arange(7)  # 所有可能的取值
    print(xk)  # [0 1 2 3 4 5 6]
    pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)  # 各个取值的概率
    custm = stats.rv_discrete(name='custm', values=(xk, pk))

    X = custm.rvs(size=20)
    print(X)

    fig, ax = plt.subplots(1, 1)
    ax.plot(xk, custm.pmf(xk), 'ro', ms=8, mec='r')
    ax.vlines(xk, 0, custm.pmf(xk), colors='r', linestyles='-', lw=2)
    plt.title('Custom made discrete distribution(PMF)')
    plt.ylabel('Probability')
    plt.show()

# custom_made_discrete_dis_pmf() 
Example #5
Source File: draw_pmf.py    From machine-learning-note with MIT License 6 votes vote down vote up
def poisson_pmf(mu=3):
    """
    泊松分布
    https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.poisson.html#scipy.stats.poisson
    :param mu: 单位时间(或单位面积)内随机事件的平均发生率
    :return:
    """
    poisson_dis = stats.poisson(mu)
    x = np.arange(poisson_dis.ppf(0.001), poisson_dis.ppf(0.999))
    print(x)
    fig, ax = plt.subplots(1, 1)
    ax.plot(x, poisson_dis.pmf(x), 'bo', ms=8, label='poisson pmf')
    ax.vlines(x, 0, poisson_dis.pmf(x), colors='b', lw=5, alpha=0.5)
    ax.legend(loc='best', frameon=False)
    plt.ylabel('Probability')
    plt.title('PMF of poisson distribution(mu={})'.format(mu))
    plt.show()

# poisson_pmf(mu=8) 
Example #6
Source File: draw_pmf.py    From machine-learning-note with MIT License 6 votes vote down vote up
def binom_pmf(n=1, p=0.1):
    """
    二项分布有两个参数
    https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binom.html#scipy.stats.binom
    :param n:试验次数
    :param p:单次实验成功的概率
    :return:
    """
    binom_dis = stats.binom(n, p)
    x = np.arange(binom_dis.ppf(0.0001), binom_dis.ppf(0.9999))
    print(x)  # [ 0.  1.  2.  3.  4.]
    fig, ax = plt.subplots(1, 1)
    ax.plot(x, binom_dis.pmf(x), 'bo', label='binom pmf')
    ax.vlines(x, 0, binom_dis.pmf(x), colors='b', lw=5, alpha=0.5)
    ax.legend(loc='best', frameon=False)
    plt.ylabel('Probability')
    plt.title('PMF of binomial distribution(n={}, p={})'.format(n, p))
    plt.show()

# binom_pmf(n=20, p=0.6) 
Example #7
Source File: VMat.py    From NucleoATAC with MIT License 6 votes vote down vote up
def plot_1d(self,filename=None):
        """plot the 1d insertion representation of the matrix"""
        fig = plt.figure()
        xlim = len(self.one_d)/2
        plt.plot(range(-xlim,xlim+1),self.one_d)
        plt.vlines(-73,0,max(self.one_d)*1.1,linestyles='dashed')
        plt.vlines(73,0,max(self.one_d)*1.1,linestyles='dashed')
        plt.xlabel("Position relative to dyad")
        plt.ylabel("Insertion Frequency")
        if filename:
            fig.savefig(filename)
            plt.close(fig)
            #Also save text output!
            filename2 = ".".join(filename.split(".")[:-1]+['txt'])
            np.savetxt(filename2,self.one_d,delimiter="\t")
        else:
            fig.show() 
Example #8
Source File: knee_locator.py    From python-urbanPlanning with MIT License 6 votes vote down vote up
def plot_knee(self, ):
        font1 = {'family' : 'STXihei',
                 'weight' : 'normal',
                 'size'   : 50,
                 }
        """Plot the curve and the knee, if it exists"""
        import matplotlib.pyplot as plt

        plt.figure(figsize=(8*3, 8*3))
        plt.plot(self.x, self.y,'ro-',label="POI聚类总数")
        plt.xlabel('聚类距离',font1)
#        plt.ylabel('POI独立点',font1)
        plt.ylabel('聚类总数',font1)
        plt.tick_params(labelsize=40)
        plt.legend(prop=font1)

#        plt.axis["right"].set_visible(False)
#        plt.axis["top"].set_visible(False)
        plt.vlines(self.knee, plt.ylim()[0], plt.ylim()[1],colors='black')

    # Niceties for users working with elbows rather than knees 
Example #9
Source File: spectre.py    From myScripts with GNU General Public License v2.0 6 votes vote down vote up
def plotSpectre(transitions, eneval, spectre):
    """ plot the UV-visible spectrum using matplotlib. Absissa are converted in nm. """

    # lambda in nm
    lambdaval = [cst.h * cst.c / (val * cst.e) * 1.e9 for val in eneval]

    # plot gaussian spectra
    plt.plot(lambdaval, spectre, "r-", label = "spectre")

    # plot transitions
    plt.vlines([val[1] for val in transitions], \
               0., \
               [val[2] for val in transitions], \
               color = "blue", \
               label = "transitions" )

    plt.xlabel("lambda   /   nm")
    plt.ylabel("Arbitrary unit")
    plt.title("UV-visible spectra")
    plt.grid()
    plt.legend(fancybox = True, shadow = True)
    plt.show() 
Example #10
Source File: knee_locator.py    From python-urbanPlanning with MIT License 6 votes vote down vote up
def plot_knee(self, ):
        font1 = {'family' : 'STXihei',
                 'weight' : 'normal',
                 'size'   : 50,
                 }
        """Plot the curve and the knee, if it exists"""
        import matplotlib.pyplot as plt

        plt.figure(figsize=(8*3, 8*3))
        plt.plot(self.x, self.y,'ro-',label="建设用地聚类最大总数")
        plt.xlabel('聚类距离',font1)
#        plt.ylabel('POI独立点',font1)
        plt.ylabel('聚类最大总数',font1)
        plt.tick_params(labelsize=40)
        plt.legend(prop=font1)

#        plt.axis["right"].set_visible(False)
#        plt.axis["top"].set_visible(False)
        plt.vlines(self.knee, plt.ylim()[0], plt.ylim()[1],colors='black')

    # Niceties for users working with elbows rather than knees 
Example #11
Source File: Plot.py    From Wave-U-Net with MIT License 6 votes vote down vote up
def draw_violin_sdr(json_folder):
    acc, voc = compute_mean_metrics(json_folder, compute_averages=False)
    acc = acc[~np.isnan(acc)]
    voc = voc[~np.isnan(voc)]
    data = [acc, voc]
    inds = [1,2]

    fig, ax = plt.subplots()
    ax.violinplot(data, showmeans=True, showmedians=False, showextrema=False, vert=False)
    ax.scatter(np.percentile(data, 50, axis=1),inds, marker="o", color="black")
    ax.set_title("Segment-wise SDR distribution")
    ax.vlines([np.min(acc), np.min(voc), np.max(acc), np.max(voc)], [0.8, 1.8, 0.8, 1.8], [1.2, 2.2, 1.2, 2.2], color="blue")
    ax.hlines(inds, [np.min(acc), np.min(voc)], [np.max(acc), np.max(voc)], color='black', linestyle='--', lw=1, alpha=0.5)

    ax.set_yticks([1,2])
    ax.set_yticklabels(["Accompaniment", "Vocals"])

    fig.set_size_inches(8, 3.)
    fig.savefig("sdr_histogram.pdf", bbox_inches='tight') 
Example #12
Source File: survival2.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def plotting_proc(self, g):
        """
        For internal use
        """
        survival = self.results[g][0]
        t = self.ts[g]
        e = (self.event)[g]
        if self.censoring != None:
            c = self.censorings[g]
            csurvival = survival[c != 0]
            ct = t[c != 0]
            if len(ct) != 0:
                plt.vlines(ct,csurvival+0.02,csurvival-0.02)
        x = np.repeat(t[e != 0], 2)
        y = np.repeat(survival[e != 0], 2)
        if self.ts[g][-1] in t[e != 0]:
            x = np.r_[0,x]
            y = np.r_[1,1,y[:-1]]
        else:
            x = np.r_[0,x,self.ts[g][-1]]
            y = np.r_[1,1,y]
        plt.plot(x,y) 
Example #13
Source File: knee_locator.py    From kneed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_knee(self, figsize: Optional[Tuple[int, int]] = None):
        """
        Plot the curve and the knee, if it exists

        :param figsize: Optional[Tuple[int, int]
            The figure size of the plot. Example (12, 8)
        :return: NoReturn
        """
        import matplotlib.pyplot as plt

        if figsize is None:
            figsize = (6, 6)

        plt.figure(figsize=figsize)
        plt.title("Knee Point")
        plt.plot(self.x, self.y, "b", label="data")
        plt.vlines(
            self.knee, plt.ylim()[0], plt.ylim()[1], linestyles="--", label="knee/elbow"
        )
        plt.legend(loc="best")

    # Niceties for users working with elbows rather than knees 
Example #14
Source File: knee_locator.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def plot_knee_normalized(self, ):
        """Plot the normalized curve, the distance curve (xd, ysn) and the
        knee, if it exists.
        """
        import matplotlib.pyplot as plt

        plt.figure(figsize=(8, 8))
        plt.plot(self.xsn, self.ysn)
        plt.plot(self.xd, self.yd, 'r')
        plt.xticks(np.arange(min(self.xsn), max(self.xsn) + 0.1, 0.1))
        plt.yticks(np.arange(min(self.xd), max(self.ysn) + 0.1, 0.1))

        plt.vlines(self.norm_knee, plt.ylim()[0], plt.ylim()[1]) 
Example #15
Source File: decision_making.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def expected_loss_plot(estimate_range, true_s, risk_range=1, function='absolute', u=1,o=1,u_f=1,o_f=1,
                        verbose=False):
    """Function to plot expected losses and the Bayes action for a range of estimates
    relative to a distribution of possible true values.
    It is possible to plot this for several risk factors at once.

            Args:
                estimate_range (np.array): Range of value estimates.
                true_s (np.array): Array of possible true value occurrences (from a probability distribution)
                u (int or float, optional): Underestimation re-weighting factor.
                o (int or float, optional): Overestimation re-weighting factor.
                u_f (int or float, optional): Fatal underestimation re-weighting factor.
                o_f (int or float, optional): Fatal overestimation re-weighting factor.
                r (int, float or np.array, optional): Risk-affinity re-weighting factor.
            Returns:
                Plot of expected losses for risk neutrality
                or several risk factors.

    """
    ax = plt.subplot(111)
    if isinstance(risk_range, (int,float)):
        r_range=[risk_range]
    else:
        r_range=risk_range
    for r in r_range:
        loss_e, bayes_a, bayes_a_loss_e = expected_loss_for_range(estimate_range, true_s, function, u,o,u_f,o_f, r)
        _color = next(ax._get_lines.prop_cycler)
        plt.plot(estimate_range, loss_e, label="r =" + str(r), color=_color['color'])
        plt.scatter(bayes_a, bayes_a_loss_e, s=70,
                        color=_color['color'])  # , label = "Bayes action r "+str(r))
        plt.vlines(bayes_a, 0, 10 * np.max(loss_e), color=_color['color'], linestyles="--")
        if verbose == True:
            print("Bayes action (minimum) at risk r %.2f: %.2f --- expected loss: %.2f"\
                  % (r, bayes_a, bayes_a_loss_e))
    plt.legend(loc="upper left", scatterpoints=1, title="Legend")
    plt.xlabel("Estimate")
    plt.ylabel("Expected loss")
    plt.xlim(estimate_range[0], estimate_range[-1])
    plt.ylim(0, 1.1 * np.max(loss_e))
    plt.grid()
    plt.show() 
Example #16
Source File: decision_making.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def loss_plot(estimate_range, true_s, risk_range=1, function='absolute', u=1,o=1,u_f=1,o_f=1,
                        verbose=False):
    """Function to plot losses for a range of estimates
    relative to a single given true value.
    It is possible to plot this for several risk factors at once.

            Args:
                estimate_range (np.array): Range of value estimates.
                true_s (int or float): Array of possible true value occurrences (from a probability distribution)
                u (int or float, optional): Underestimation re-weighting factor.
                o (int or float, optional): Overestimation re-weighting factor.
                u_f (int or float, optional): Fatal underestimation re-weighting factor.
                o_f (int or float, optional): Fatal overestimation re-weighting factor.
                r (int, float or np.array, optional): Risk-affinity re-weighting factor.
            Returns:
                Plot of losses for risk neutrality
                or several risk factors given a single determined true value.

    """
    ax = plt.subplot(111)
    if isinstance(risk_range, (int,float)):
        r_range=[risk_range]
    else:
        r_range=risk_range
    for r in r_range:
        loss_i, bayes_a, bayes_a_loss = loss_for_range(estimate_range, true_s, function, u,o,u_f,o_f, r)
        _color = next(ax._get_lines.prop_cycler)
        plt.plot(estimate_range, loss_i, label="r =" + str(r), color=_color['color'])
        plt.scatter(bayes_a, bayes_a_loss, s=70,
                        color=_color['color'])  # , label = "Bayes action r "+str(r))
        plt.vlines(bayes_a, 0, 10 * np.max(loss_i), color=_color['color'], linestyles="--")
        if verbose == True:
            print("Bayes action (minimum) at risk r %.2f: %.2f --- expected loss: %.2f"\
                  % (r, bayes_a, bayes_a_loss))
    plt.legend(loc="upper left", scatterpoints=1, title="Legend")
    plt.xlabel("Estimate")
    plt.ylabel("Expected loss")
    plt.xlim(estimate_range[0], estimate_range[-1])
    plt.ylim(0, 1.1 * np.max(loss_i))
    plt.grid()
    plt.show() 
Example #17
Source File: poiRegression.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def simpleLR(X0,X1,w0,w1,w2):
    y=w0+w1*X0  #单解释变量
    plt.scatter(X0,y,c='r',marker='x')
    plt.plot(X0,y,label='linear fit',linestyle='--')
    plt.hlines(y=0,xmin=-10,xmax=60,lw=1,color='red')
    plt.vlines(x=0,ymin=-100,ymax=600,lw=1,color='red')    
#    plt.plot(,linestyle='-')
    plt.show()
    
    if X1.shape and w1 and w2:
        y=w0+w1*X0+w2*X1  #多解释变量
        fig=plt.figure()
        ax=Axes3D(fig)
        ax.scatter(X0, X1, y)
        plt.show() 
Example #18
Source File: knee_locator.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def plot_knee_normalized(self, ):
        """Plot the normalized curve, the distance curve (xd, ysn) and the
        knee, if it exists.
        """
        import matplotlib.pyplot as plt

        plt.figure(figsize=(8, 8))
        plt.plot(self.xsn, self.ysn)
        plt.plot(self.xd, self.yd, 'r')
        plt.xticks(np.arange(min(self.xsn), max(self.xsn) + 0.1, 0.1))
        plt.yticks(np.arange(min(self.xd), max(self.ysn) + 0.1, 0.1))

        plt.vlines(self.norm_knee, plt.ylim()[0], plt.ylim()[1]) 
Example #19
Source File: Plot.py    From Wave-U-Net with MIT License 5 votes vote down vote up
def draw_spectrogram(example_wav="musb_005_angela thomas wade_audio_model_without_context_cut_28234samples_61002samples_93770samples_126538.wav"):
    y, sr = Utils.load(example_wav, sr=None)
    spec = np.abs(librosa.stft(y, 512, 256, 512))
    norm_spec = librosa.power_to_db(spec**2)
    black_time_frames = np.array([28234, 61002, 93770, 126538]) / 256.0

    fig, ax = plt.subplots()
    img = ax.imshow(norm_spec)
    plt.vlines(black_time_frames, [0, 0, 0, 0], [10, 10, 10, 10], colors="red", lw=2, alpha=0.5)
    plt.vlines(black_time_frames, [256, 256, 256, 256], [246, 246, 246, 246], colors="red", lw=2, alpha=0.5)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.1)
    plt.colorbar(img, cax=cax)

    ax.xaxis.set_label_position("bottom")
    #ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x * 256.0 / sr))
    #ax.xaxis.set_major_formatter(ticks_x)
    ax.xaxis.set_major_locator(ticker.FixedLocator(([i * sr / 256. for i in range(len(y)//sr + 1)])))
    ax.xaxis.set_major_formatter(ticker.FixedFormatter(([str(i) for i in range(len(y)//sr + 1)])))

    ax.yaxis.set_major_locator(ticker.FixedLocator(([float(i) * 2000.0 / (sr/2.0) * 256. for i in range(6)])))
    ax.yaxis.set_major_formatter(ticker.FixedFormatter([str(i*2) for i in range(6)]))

    ax.set_xlabel("t (s)")
    ax.set_ylabel('f (KHz)')

    fig.set_size_inches(7., 3.)
    fig.savefig("spectrogram_example.pdf", bbox_inches='tight') 
Example #20
Source File: draw_pmf.py    From machine-learning-note with MIT License 5 votes vote down vote up
def sampling_and_empirical_dis():
    xk = np.arange(7)  # 所有可能的取值
    print(xk)  # [0 1 2 3 4 5 6]
    pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)  # 各个取值的概率
    custm = stats.rv_discrete(name='custm', values=(xk, pk))

    X1 = custm.rvs(size=20)  # 第一次抽样
    X2 = custm.rvs(size=200)  # 第二次抽样
    # 计算X1&X2中各个结果出现的频率(相当于PMF)
    val1, cnt1 = np.unique(X1, return_counts=True)
    val2, cnt2 = np.unique(X2, return_counts=True)
    pmf_X1 = cnt1 / len(X1)
    pmf_X2 = cnt2 / len(X2)

    plt.figure(1)
    plt.subplot(211)
    plt.plot(xk, custm.pmf(xk), 'ro', ms=8, mec='r', label='theor. pmf')
    plt.vlines(xk, 0, custm.pmf(xk), colors='r', lw=5, alpha=0.2)
    plt.vlines(val1, 0, pmf_X1, colors='b', linestyles='-', lw=3, label='X1 empir. pmf')
    plt.legend(loc='best', frameon=False)
    plt.ylabel('Probability')
    plt.title('Theoretical dist. PMF vs Empirical dist. PMF')
    plt.subplot(212)
    plt.plot(xk, custm.pmf(xk), 'ro', ms=8, mec='r', label='theor. pmf')
    plt.vlines(xk, 0, custm.pmf(xk), colors='r', lw=5, alpha=0.2)
    plt.vlines(val2, 0, pmf_X2, colors='g', linestyles='-', lw=3, label='X2 empir. pmf')
    plt.legend(loc='best', frameon=False)
    plt.ylabel('Probability')
    plt.show() 
Example #21
Source File: plot.py    From ML-Recon with MIT License 5 votes vote down vote up
def plot_pancake(k,powNbody,powRecon,powInput,title):
    pos = np.intersect1d(np.where(np.nan_to_num(powNbody) > 1e-3)[0], np.where(np.nan_to_num(powRecon)> 1e-3)[0])
    plt.figure(figsize=(6,6))
    gs = GridSpec(2, 1, height_ratios=[2,1],width_ratios=[1])
    ax1 = plt.subplot(gs[0, 0])
    #plt.loglog(k[pos],powLPT[pos],'*',label='2LPT',c=c[0])
    plt.loglog(k[pos],powRecon[pos],'*',label='U-Net',c=c[1])
    plt.loglog(k[pos],powNbody[pos],'x',label='FastPM',c=c[2])
    plt.loglog(k,powInput,'^',label='1 mode input',c=c[3])
    plt.vlines(k[np.argmax(np.nan_to_num(powInput))],\
               ymin = 1e-5,\
               ymax = powInput[np.argmax(np.nan_to_num(powInput))],alpha=0.5,linestyles='dashed')
    plt.legend(loc='upper left')
    plt.title(r"displacement "+title)
    plt.ylabel(r'$P(k)}$')
    plt.ylim(ymin = 1e-5)

    plt.subplot(gs[1, 0],sharex=ax1)
    plt.loglog(k[pos],powRecon[pos]/powNbody[pos],'*',label='Recon',c=c[1])
    plt.xlabel('k '+r'[h/Mpc]')
    plt.ylim(ymin = 1e-5)
    plt.ylabel(r'$T(k)$')
    plt.axhline(y=1,color='black',ls='dashed')
    plt.setp(ax1.get_xticklabels(),visible=False)
    plt.xticks(np.round([0.06+0.01*i for i in range(0,4,2)]+ [0.1+0.1*i for i in range(0,7,2)],2),\
                   np.round([0.06+0.01*i for i in range(0,4,2)]+ [0.1+0.1*i for i in range(0,7,2)],2))
    plt.xticks(rotation=45)
    #plt.tight_layout()

#----------plot one slice demonstration--------------# 
Example #22
Source File: nearest_neighbor.py    From dials with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_histogram(self, filename="nn_hist.png", figsize=(12, 8)):
        import matplotlib.pyplot as plt

        plt.figure(figsize=figsize)
        plt.bar(
            self.slot_start,
            self.relative_frequency,
            align="center",
            width=self.slot_width,
            color="black",
            edgecolor=None,
        )
        ymin, ymax = plt.ylim()
        if self.histogram_binning == "log":
            ax = plt.gca()
            ax.set_xscale("log")
        plt.vlines(
            self.max_cell / self.tolerance,
            ymin,
            ymax,
            linestyles="--",
            colors="g",
            label="estimated max cell",
        )
        plt.vlines(
            self.max_cell,
            ymin,
            ymax,
            colors="g",
            label="estimated max cell (including tolerance)",
        )
        plt.xlabel("Direct space distance (A)")
        plt.ylabel("Frequency")
        plt.legend(loc="upper left")
        plt.savefig(filename)
        plt.clf() 
Example #23
Source File: hyper_param.py    From geoist with MIT License 5 votes vote down vote up
def plot_lcurve(self, ax=None, guides=True):
        """
        Make a plot of the data-misfit x regularization values.

        The estimated corner value is shown as a blue triangle.

        Parameters:

        * ax : matplotlib Axes
            If not ``None``, will plot the curve on this Axes instance.
        * guides : True or False
            Plot vertical and horizontal lines across the corner value.

        """
        if ax is None:
            ax = mpl.gca()
        else:
            mpl.sca(ax)
        x, y = self.dnorm, self.mnorm
        if self.loglog:
            mpl.loglog(x, y, '.-k')
        else:
            mpl.plot(x, y, '.-k')
        if guides:
            vmin, vmax = ax.get_ybound()
            mpl.vlines(x[self.corner_], vmin, vmax)
            vmin, vmax = ax.get_xbound()
            mpl.hlines(y[self.corner_], vmin, vmax)
        mpl.plot(x[self.corner_], y[self.corner_], '^b', markersize=10)
        mpl.xlabel('Data misfit(data norm)')
        mpl.ylabel('Regularization(model norm)') 
Example #24
Source File: _find_default_scale.py    From numdifftools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_error(scales, relativ_error, scale0, title='', label=''):
    plt.semilogy(scales, relativ_error, label=label)
    plt.vlines(scale0, np.nanmin(relativ_error), 1)
    plt.xlabel('scales')
    plt.ylabel('Relative error')
    plt.title(title)
    plt.legend(frameon=False, framealpha=0.5)
    plt.axis([min(scales), max(scales), np.nanmin(relativ_error), 1]) 
Example #25
Source File: utils.py    From DIAG-NRE with MIT License 5 votes vote down vote up
def plot_multi_pr_curves(plot_tuples, plot_title='Precision Recall Curves',
                         figsize=(12, 8), xlim=(0, 1), ylim=(0, 1),
                         basic_font_size=14):
    plt.figure(figsize=figsize)

    for eval_infos, line_name, line_color in plot_tuples:
        precs = eval_infos[0]
        recalls = eval_infos[1]
        avg_prec = eval_infos[3]
        f1_score = eval_infos[6]
        plt.step(recalls, precs,
                 label=line_name + ' (AUC {0:.3f}, F1 {1:.3f})'.format(avg_prec, f1_score),
                 color=line_color)

        dec_prec = eval_infos[4]
        dec_recall = eval_infos[5]
        plt.plot(dec_recall, dec_prec, 'o', color=line_color, markersize=8)
        plt.vlines(dec_recall, 0, dec_prec, linestyles='dashed', colors=line_color)
        plt.hlines(dec_prec, 0, dec_recall, linestyles='dashed', colors=line_color)

    plt.legend(fontsize=basic_font_size)
    plt.title(plot_title, fontsize=basic_font_size+ 2)
    plt.xlabel('Recall', fontsize=basic_font_size)
    plt.ylabel('Precision', fontsize=basic_font_size)
    plt.xticks(fontsize=basic_font_size)
    plt.yticks(fontsize=basic_font_size)
    plt.xlim(xlim)
    plt.ylim(ylim) 
Example #26
Source File: knee_locator.py    From kneed with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_knee_normalized(self, figsize: Optional[Tuple[int, int]] = None):
        """Plot the normalized curve, the difference curve (x_difference, y_normalized) and the knee, if it exists.

        :param figsize: Optional[Tuple[int, int]
        The figure size of the plot. Example (12, 8)
        :return: NoReturn
        """
        import matplotlib.pyplot as plt

        if figsize is None:
            figsize = (6, 6)

        plt.figure(figsize=figsize)
        plt.title("Normalized Knee Point")
        plt.plot(self.x_normalized, self.y_normalized, "b", label="normalized curve")
        plt.plot(self.x_difference, self.y_difference, "r", label="difference curve")
        plt.xticks(
            np.arange(self.x_normalized.min(), self.x_normalized.max() + 0.1, 0.1)
        )
        plt.yticks(
            np.arange(self.y_difference.min(), self.y_normalized.max() + 0.1, 0.1)
        )

        plt.vlines(
            self.norm_knee,
            plt.ylim()[0],
            plt.ylim()[1],
            linestyles="--",
            label="knee/elbow",
        )
        plt.legend(loc="best") 
Example #27
Source File: libplot.py    From magphase with Apache License 2.0 5 votes vote down vote up
def plot_pitch_marks(v_sig, v_pm_smpls):
    lp.figure()
    lp.plot(v_sig)
    lp.vlines(v_pm_smpls, np.min(v_sig), np.max(v_sig), colors='r')
    lp.grid()
    return 
Example #28
Source File: initialize.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def check_sidebands(self):
        rec = self._sample.readout.spectrum()
        ro = self._sample.readout.readout()
        plt.figure(figsize=(15,5))
        plt.plot(rec[0],rec[1]/len(rec[1]),'--o')
        ylim = plt.ylim()
        plt.vlines(self._sample.readout.get_LO(),*ylim,color='r')
        for i,fr in enumerate(np.atleast_1d(self._sample.fr)):
            plt.plot([fr],ro[0][i],'+',ms=50,mew=3)
        plt.ylim(0,ylim[1])
        spread = np.ptp(np.append(np.atleast_1d(self._sample.fr),self._sample.readout.get_LO()))*1.2
        plt.xlim([self._sample.readout.get_LO()-spread,self._sample.readout.get_LO()+spread])
        plt.grid() 
Example #29
Source File: backtest.py    From sanpy with MIT License 5 votes vote down vote up
def plot_backtest(self, viz=None):
        ''' param viz: None OR "trades" OR "hodl".
        '''
        plt.figure(figsize=(15, 8))
        plt.plot(self.performance, label="performance")
        plt.plot(self.benchmark, label="holding")

        if viz == 'trades':
            min_y = min(self.performance.min(), self.benchmark.min())
            max_y = max(self.performance.max(), self.benchmark.max())
            plt.vlines(self.nr_trades['sell'], min_y, max_y, color='red')
            plt.vlines(self.nr_trades['buy'], min_y, max_y, color='green')
        elif viz == 'hodl':
            hodl_periods = []
            for i in range(len(self.trades)):
                state = self.trades[i - 1] if i > 0 else self.trades[i]
                if self.trades[i] and not state:
                    start = self.strategy_returns.index[i]
                elif not self.trades[i] and state:
                    hodl_periods.append([start, self.strategy_returns.index[i]])
            if self.trades[-1]:
                hodl_periods.append([start, self.strategy_returns.index[i]])
            for hodl_period in hodl_periods:
                plt.axvspan(hodl_period[0], hodl_period[1], color='#aeffa8')

        plt.legend()
        plt.show() 
Example #30
Source File: thinkplot.py    From Lie_to_me with MIT License 5 votes vote down vote up
def Hlines(ys, x1, x2, **options):
    """Plots a set of horizontal lines.

    Args:
      ys: sequence of y values
      x1: sequence of x values
      x2: sequence of x values
      options: keyword args passed to plt.vlines
    """
    options = _UnderrideColor(options)
    options = _Underride(options, linewidth=1, alpha=0.5)
    plt.hlines(ys, x1, x2, **options)