本文整理汇总了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)
示例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')
示例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')
示例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()
示例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()
示例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()
示例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()
示例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()
示例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()
示例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()
示例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()
示例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
示例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")
示例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")
示例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()