當前位置: 首頁>>代碼示例>>Python>>正文


Python pyplot.hist方法代碼示例

本文整理匯總了Python中matplotlib.pyplot.hist方法的典型用法代碼示例。如果您正苦於以下問題:Python pyplot.hist方法的具體用法?Python pyplot.hist怎麽用?Python pyplot.hist使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在matplotlib.pyplot的用法示例。


在下文中一共展示了pyplot.hist方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: plot_test_txt

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def plot_test_txt():  # from utils.utils import *; plot_test()
    # Plot test.txt histograms
    x = np.loadtxt('test.txt', dtype=np.float32)
    box = xyxy2xywh(x[:, :4])
    cx, cy = box[:, 0], box[:, 1]

    fig, ax = plt.subplots(1, 1, figsize=(6, 6))
    ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
    ax.set_aspect('equal')
    fig.tight_layout()
    plt.savefig('hist2d.jpg', dpi=300)

    fig, ax = plt.subplots(1, 2, figsize=(12, 6))
    ax[0].hist(cx, bins=600)
    ax[1].hist(cy, bins=600)
    fig.tight_layout()
    plt.savefig('hist1d.jpg', dpi=200) 
開發者ID:zbyuan,項目名稱:pruning_yolov3,代碼行數:19,代碼來源:utils.py

示例2: plotnoduledist

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def plotnoduledist(annopath):
    import pandas as pd 
    df = pd.read_csv(annopath+'train/annotations.csv')
    diameter = df['diameter_mm'].reshape((-1,1))

    df = pd.read_csv(annopath+'val/annotations.csv')
    diameter = np.vstack([df['diameter_mm'].reshape((-1,1)), diameter])

    df = pd.read_csv(annopath+'test/annotations.csv')
    diameter = np.vstack([df['diameter_mm'].reshape((-1,1)), diameter])
    fig = plt.figure()
    plt.hist(diameter, normed=True, bins=50)
    plt.ylabel('probability')
    plt.xlabel('Diameters')
    plt.title('Nodule Diameters Histogram')
    plt.savefig('nodulediamhist.png') 
開發者ID:uci-cbcl,項目名稱:DeepLung,代碼行數:18,代碼來源:utils.py

示例3: plothistdiameter

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def plothistdiameter(trainpath='/media/data1/wentao/tianchi/preprocessing/newtrain/', 
                     testpath='/media/data1/wentao/tianchi/preprocessing/newtest/'):
    diameterlist = []
    for fname in os.listdir(trainpath):
        if fname.endswith('_label.npy'):
            label = np.load(trainpath+fname)
            for lidx in xrange(label.shape[0]):
                diameterlist.append(label[lidx, -1])
    for fname in os.listdir(testpath):
        if fname.endswith('_label.npy'):
            label = np.load(testpath+fname)
            for lidx in xrange(label.shape[0]):
                diameterlist.append(label[lidx, -1])
    fig = plt.figure()
    plt.hist(diameterlist, 50)
    plt.xlabel('Nodule Diameter')
    plt.ylabel('# Nodules')
    plt.title('Nodule Size Histogram')
    plt.savefig('processnodulesizehist.png') 
開發者ID:uci-cbcl,項目名稱:DeepLung,代碼行數:21,代碼來源:utils.py

示例4: analyze_zh

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def analyze_zh():
    translation_path = os.path.join(train_translation_folder, train_translation_zh_filename)

    with open(translation_path, 'r') as f:
        sentences = f.readlines()

    sent_lengths = []

    for sentence in tqdm(sentences):
        seg_list = list(jieba.cut(sentence.strip()))
        # Update word frequency
        sent_lengths.append(len(seg_list))

    num_bins = 100
    n, bins, patches = plt.hist(sent_lengths, num_bins, facecolor='blue', alpha=0.5)
    title = 'Chinese Sentence Lengths Distribution'
    plt.title(title)
    plt.show() 
開發者ID:foamliu,項目名稱:Machine-Translation,代碼行數:20,代碼來源:analyze_data.py

示例5: analyze_en

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def analyze_en():
    translation_path = os.path.join(train_translation_folder, train_translation_en_filename)

    with open(translation_path, 'r') as f:
        sentences = f.readlines()

    sent_lengths = []

    for sentence in tqdm(sentences):
        sentence_en = sentence.strip().lower()
        tokens = [normalizeString(s) for s in nltk.word_tokenize(sentence_en)]
        seg_list = list(jieba.cut(sentence.strip()))
        # Update word frequency
        sent_lengths.append(len(seg_list))

    num_bins = 100
    n, bins, patches = plt.hist(sent_lengths, num_bins, facecolor='blue', alpha=0.5)
    title = 'English Sentence Lengths Distribution'
    plt.title(title)
    plt.show() 
開發者ID:foamliu,項目名稱:Machine-Translation,代碼行數:22,代碼來源:analyze_data.py

示例6: plot_histogram

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def plot_histogram(lfw_dir):
    """
    Function to plot the distribution of cluster sizes in LFW.
    """
    filecount_dict = {}
    for root, dirs, files in os.walk(lfw_dir):
        for dirname in dirs:
            n_photos = len(os.listdir(os.path.join(root, dirname)))
            filecount_dict[dirname] = n_photos
    print("No of unique people: {}".format(len(filecount_dict.keys())))
    df = pd.DataFrame(filecount_dict.items(), columns=['Name', 'Count'])
    print("Singletons : {}\nTwo :{}\n".format((df['Count'] == 1).sum(),
                                              (df['Count'] == 2).sum()))
    plt.hist(df['Count'], bins=max(df['Count']))
    plt.title('Cluster Sizes')
    plt.xlabel('No of images in folder')
    plt.ylabel('No of folders')
    plt.show() 
開發者ID:varun-suresh,項目名稱:Clustering,代碼行數:20,代碼來源:demo.py

示例7: plotRRintHist

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def plotRRintHist(RRints):
    """ 
    Histogram distribution of poincare points projected onto the x-axis
    
    Input    :
    
     - RRints: [list] of RR intervals
        
    Output   :
        
     - RR interval histogram plot    
    """    
    plt.hist(RRints, bins = 'auto')
    plt.xlabel('RR Interval')
    plt.ylabel('Number of RR Intervals')
    plt.title('RR Interval Histogram')
    plt.show() 
開發者ID:pickus91,項目名稱:HRV,代碼行數:19,代碼來源:poincare.py

示例8: plotWidthHist

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def plotWidthHist(RRints):    
    """  
    Histogram distribution of poincare points projected along the direction of 
    line-of-identity, or along the line perpendicular to the line-of-identity.
    
    Input    :
    
     - RRints: [list] of RR intervals
        
    Output   :
        
     - 'Width', or delta-RR interval, histogram plot      
     """   
    ax1 = RRints[:-1]
    ax2 = RRints[1:]
    x1 = (np.cos(np.pi / 4) * ax1) - (np.sin(np.pi / 4) * ax2)
    plt.hist(x1, bins = 'auto')
    plt.title('Width (Delta-RR Interval) Histogram')
    plt.show() 
開發者ID:pickus91,項目名稱:HRV,代碼行數:21,代碼來源:poincare.py

示例9: plotLengthHist

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def plotLengthHist(RRints):    
    """
    Histogram distribution of poincare points projected along the line-of-identty.
    
    Input    :
    
     - RRints: [list] of RR intervals
        
    Output   :
        
     - 'Length' histogram plot
     """
     
    ax1 = RRints[:-1]
    ax2 = RRints[1:]
    x2 = (np.sin(np.pi / 4) * ax1) + (np.cos(np.pi / 4) * ax2)
    plt.hist(x2, bins = 'auto')
    plt.title('Length Histogram')
    plt.show() 
開發者ID:pickus91,項目名稱:HRV,代碼行數:21,代碼來源:poincare.py

示例10: plot_probabilities_histogram

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def plot_probabilities_histogram(Y_probs, title=None):
    """Plot a histogram from a numpy array of probabilities

    Args:
        Y_probs: An [n] or [n, 1] np.ndarray of probabilities (floats in [0,1])
    """
    if Y_probs.ndim > 1:
        print("Plotting probabilities from the first column of Y_probs")
        Y_probs = Y_probs[:, 0]
    plt.hist(Y_probs, bins=20)
    plt.xlim((0, 1.025))
    plt.xlabel("Probability")
    plt.ylabel("# Predictions")
    if isinstance(title, str):
        plt.title(title)
    plt.show() 
開發者ID:HazyResearch,項目名稱:metal,代碼行數:18,代碼來源:analysis.py

示例11: plot_predictions_histogram

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def plot_predictions_histogram(Y_preds, Y_gold, title=None):
    """Plot a histogram comparing int predictions vs true labels by class

    Args:
        Y_gold: An [n] or [n, 1] np.ndarray of gold labels
        Y_preds: An [n] or [n, 1] np.ndarray of predicted int labels
    """
    labels = list(set(Y_gold).union(set(Y_preds)))
    edges = [x - 0.5 for x in range(min(labels), max(labels) + 2)]

    plt.hist([Y_preds, Y_gold], bins=edges, label=["Predicted", "Gold"])
    ax = plt.gca()
    ax.set_xticks(labels)
    plt.xlabel("Label")
    plt.ylabel("# Predictions")
    plt.legend(loc="upper right")
    if isinstance(title, str):
        plt.title(title)
    plt.show() 
開發者ID:HazyResearch,項目名稱:metal,代碼行數:21,代碼來源:analysis.py

示例12: diagnostics_SNR

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def diagnostics_SNR(self): 
        """ Plots SNR distributions of ref and test object spectra """
        print("Diagnostic for SNRs of reference and survey objects")
        fig = plt.figure()
        data = self.test_SNR
        plt.hist(data, bins=int(np.sqrt(len(data))), alpha=0.5, facecolor='r', 
                label="Survey Objects")
        data = self.tr_SNR
        plt.hist(data, bins=int(np.sqrt(len(data))), alpha=0.5, color='b',
                label="Ref Objects")
        plt.legend(loc='upper right')
        #plt.xscale('log')
        plt.title("SNR Comparison Between Reference and Survey Objects")
        #plt.xlabel("log(Formal SNR)")
        plt.xlabel("Formal SNR")
        plt.ylabel("Number of Objects")
        return fig 
開發者ID:annayqho,項目名稱:TheCannon,代碼行數:19,代碼來源:dataset.py

示例13: snr_dist

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def snr_dist():
    fig = plt.figure(figsize=(6,4))
    tr_snr = np.load("../tr_SNR.npz")['arr_0']
    snr = np.load("../val_SNR.npz")['arr_0']
    nbins = 25
    plt.hist(tr_snr, bins=nbins, color='k', histtype="step",
            lw=2, normed=True, alpha=0.3, label="Training Set")
    plt.hist(snr, bins=nbins, color='r', histtype="step",
            lw=2, normed=True, alpha=0.3, label="Validation Set")
    plt.legend()
    plt.xlabel("S/N", fontsize=16)
    plt.tick_params(axis='both', labelsize=16)
    plt.ylabel("Normalized Count", fontsize=16)
    fig.tight_layout()
    plt.show()
    #plt.savefig("snr_dist.png") 
開發者ID:annayqho,項目名稱:TheCannon,代碼行數:18,代碼來源:validation_plots.py

示例14: chisq_dist

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def chisq_dist():
    fig = plt.figure(figsize=(6,4))
    ivar = np.load("%s/val_ivar_norm.npz" %DATA_DIR)['arr_0']
    npix = np.sum(ivar>0, axis=1)
    chisq = np.load("%s/val_chisq.npz" %DATA_DIR)['arr_0']
    redchisq = chisq/npix
    nbins = 25
    plt.hist(redchisq, bins=nbins, color='k', histtype="step",
            lw=2, normed=False, alpha=0.3, range=(0,3))
    plt.legend()
    plt.xlabel("Reduced $\chi^2$", fontsize=16)
    plt.tick_params(axis='both', labelsize=16)
    plt.ylabel("Count", fontsize=16)
    plt.axvline(x=1.0, linestyle='--', c='k')
    fig.tight_layout()
    #plt.show()
    plt.savefig("chisq_dist.png") 
開發者ID:annayqho,項目名稱:TheCannon,代碼行數:19,代碼來源:validation_plots.py

示例15: huitu

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import hist [as 別名]
def huitu(suout, shiout, c=['b', 'k'], sign='訓練', cudu=3):

    # 繪製原始數據和預測數據的對比
    plt.subplot(2, 1, 1)
    plt.plot(list(range(len(suout))), suout, c=c[0], linewidth=cudu, label='%s:算法輸出' % sign)
    plt.plot(list(range(len(shiout))), shiout, c=c[1], linewidth=cudu, label='%s:實際值' % sign)
    plt.legend(loc='best')
    plt.title('原始數據和向量機輸出數據的對比')

    # 繪製誤差和0的對比圖
    plt.subplot(2, 2, 3)
    plt.plot(list(range(len(suout))), suout - shiout, c='r', linewidth=cudu, label='%s:誤差' % sign)
    plt.plot(list(range(len(suout))), list(np.zeros(len(suout))), c='k', linewidth=cudu, label='0值')
    plt.legend(loc='best')
    plt.title('誤差和0的對比')
    # 需要添加一個誤差的分布圖
    plt.subplot(2, 2, 4)
    plt.hist(suout - shiout, 50, facecolor='g', alpha=0.75)
    plt.title('誤差直方圖')
    # 顯示
    plt.show() 
開發者ID:Anfany,項目名稱:Machine-Learning-for-Beginner-by-Python3,代碼行數:23,代碼來源:Sklearn_SVM_Regression.py


注:本文中的matplotlib.pyplot.hist方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。