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


Python pyplot.text方法代碼示例

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


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

示例1: draw_quality_histogram

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def draw_quality_histogram(items):
    """
    畫質量直方圖
    """

    from analyze.quality import get_item_quality

    qualities = [get_item_quality(item) for item in items
                 if len(item.reviews) >= 20]
    plt.title('質量直方圖')
    plt.xlabel('質量')
    plt.ylabel('分布密度')
    plt.hist(qualities, bins=100, range=(0, 1), density=True)

    # 擬合正態分布
    mean = np.mean(qualities)
    std = np.std(qualities)
    x = np.arange(0, 1, 0.01)
    y = stats.norm.pdf(x, loc=mean, scale=std)
    plt.plot(x, y)
    plt.text(0, 5, r'$N={},\mu={:.3f},\sigma={:.3f}$'
                   .format(len(qualities), mean, std)) 
開發者ID:xfgryujk,項目名稱:TaobaoAnalysis,代碼行數:24,代碼來源:draw_plot.py

示例2: data_stat

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def data_stat():
    """data statistic"""
    audio_path = './data/esc10/audio/'
    class_list = [os.path.basename(i) for i in glob(audio_path + '*')]
    nums_each_class = [len(glob(audio_path + cl + '/*.ogg')) for cl in class_list]
    rects = plt.bar(range(len(nums_each_class)), nums_each_class)

    index = list(range(len(nums_each_class)))
    plt.title('Numbers of each class for ESC-10 dataset')
    plt.ylim(ymax=60, ymin=0)
    plt.xticks(index, class_list, rotation=45)
    plt.ylabel("numbers")

    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width() / 2, height, str(height), ha='center', va='bottom')

    plt.tight_layout()
    plt.show() 
開發者ID:JasonZhang156,項目名稱:Sound-Recognition-Tutorial,代碼行數:21,代碼來源:data_analysis.py

示例3: plot_tsne

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def plot_tsne(self, save_eps=False):
        ''' Plot TSNE figure. Set save_eps=True if you want to save a .eps file.
        '''
        tsne = TSNE(n_components=2, init='pca', random_state=0)
        features = tsne.fit_transform(self.features)
        x_min, x_max = np.min(features, 0), np.max(features, 0)
        data = (features - x_min) / (x_max - x_min)
        del features
        for i in range(data.shape[0]):
            plt.text(data[i, 0], data[i, 1], str(self.labels[i]),
                     color=plt.cm.Set1(self.labels[i] / 10.),
                     fontdict={'weight': 'bold', 'size': 9})
        plt.xticks([])
        plt.yticks([])
        plt.title('T-SNE')
        if save_eps:
            plt.savefig('tsne.eps', dpi=600, format='eps')
        plt.show() 
開發者ID:jindongwang,項目名稱:transferlearning,代碼行數:20,代碼來源:feature_vis.py

示例4: plot_attention

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def plot_attention(sentences, attentions, labels, **kwargs):
    fig, ax = plt.subplots(**kwargs)
    im = ax.imshow(attentions, interpolation='nearest',
                   vmin=attentions.min(), vmax=attentions.max())
    plt.colorbar(im, shrink=0.5, ticks=[0, 1])
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")
    ax.set_yticks(range(len(labels)))
    ax.set_yticklabels(labels, fontproperties=getChineseFont())
    # Loop over data dimensions and create text annotations.
    for i in range(attentions.shape[0]):
        for j in range(attentions.shape[1]):
            text = ax.text(j, i, sentences[i][j],
                           ha="center", va="center", color="b", size=10,
                           fontproperties=getChineseFont())

    ax.set_title("Attention Visual")
    fig.tight_layout()
    plt.show() 
開發者ID:EvilPsyCHo,項目名稱:TaskBot,代碼行數:21,代碼來源:plot.py

示例5: draw_boxes

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def draw_boxes(filename, v_boxes, v_labels, v_scores, output_photo_name):
	# load the image
	data = pyplot.imread(filename)
	# plot the image
	pyplot.imshow(data)
	# get the context for drawing boxes
	ax = pyplot.gca()
	# plot each box
	for i in range(len(v_boxes)):
		box = v_boxes[i]
		# get coordinates
		y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax
		# calculate width and height of the box
		width, height = x2 - x1, y2 - y1
		# create the shape
		rect = Rectangle((x1, y1), width, height, fill=False, color='white')
		# draw the box
		ax.add_patch(rect)
		# draw text and score in top left corner
		label = "%s (%.3f)" % (v_labels[i], v_scores[i])
		pyplot.text(x1, y1, label, color='white')
	# show the plot
	#pyplot.show()	
	pyplot.savefig(output_photo_name) 
開發者ID:produvia,項目名稱:ai-platform,代碼行數:26,代碼來源:yolo_image.py

示例6: plot_embedding

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def plot_embedding(data, label, title):
    ids = np.unique(label)
    label_color = label.copy()
    for i, label_id in enumerate(ids):
        label_color[label_color==label_id] = i

    x_min, x_max = np.min(data, 0), np.max(data, 0)
    data = (data - x_min) / (x_max - x_min)

    fig = plt.figure()
    ax = plt.subplot(111)
    for i in range(data.shape[0]):
        plt.text(data[i, 0], data[i, 1], str(label[i]),
                 color=plt.cm.Set1(label_color[i] / 10.),
                 fontdict={'weight': 'bold', 'size': 9})
    plt.xticks([])
    plt.yticks([])
    plt.title(title)
    plt.show()
    return fig 
開發者ID:yolomax,項目名稱:person-reid-lib,代碼行數:22,代碼來源:feature_show.py

示例7: update

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def update(self, conf_mat, classes, normalize=False):
        """This function prints and plots the confusion matrix.
        Normalization can be applied by setting `normalize=True`.
        """
        plt.imshow(conf_mat, interpolation='nearest', cmap=self.cmap)
        plt.title(self.title)
        plt.colorbar()
        tick_marks = np.arange(len(classes))
        plt.xticks(tick_marks, classes, rotation=45)
        plt.yticks(tick_marks, classes)

        if normalize:
            conf_mat = conf_mat.astype('float') / conf_mat.sum(axis=1)[:, np.newaxis]

        thresh = conf_mat.max() / 2.
        for i, j in itertools.product(range(conf_mat.shape[0]), range(conf_mat.shape[1])):
            plt.text(j, i, conf_mat[i, j],                                          
                         horizontalalignment="center",
                         color="white" if conf_mat[i, j] > thresh else "black")
                                                                                                         
        plt.tight_layout()                                                    
        plt.ylabel('True label')                                              
        plt.xlabel('Predicted label')                                         
        plt.draw() 
開發者ID:chasingbob,項目名稱:squeezenet-keras,代碼行數:26,代碼來源:visual_callbacks.py

示例8: draw

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def draw(self):
        self.title_canvas = tk.Canvas(self, bg=self.bgcolor, width=width, height=90, bd=0, highlightthickness=0, relief='ridge')
        self.title_pic = self._resize_ads_qrcode(RES_APP_TITLE, size=(260, 90))
        self.title_canvas.create_image(0, 0, anchor='nw', image=self.title_pic)
        self.title_canvas.pack(padx=35, pady=15)

        self.qrcode = tk.Canvas(self, bg=self.bgcolor, width=200, height=200)
        #self.qrcode_pic = self._resize_ads_qrcode('qrcode.png', size=(200, 200))
        #self.qrcode.create_image(0, 0, anchor='nw', image=self.qrcode_pic)
        self.qrcode.pack(pady=30)


        # 提示
        self.lable_tip = tk.Label(self,
                     text='請稍等',  # 標簽的文字
                     bg=self.bgcolor,  # 背景顏色
                     font=('楷體',12),  # 字體和字體大小
                     width=15, height=2  # 標簽長寬
                     )
        self.lable_tip.pack(pady=2,fill=tk.BOTH)  # 固定窗口位置 
開發者ID:newbietian,項目名稱:WxConn,代碼行數:22,代碼來源:main.py

示例9: load_txt

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def load_txt(fname, polrep='stokes', pol_prim=None, pulse=ehc.PULSE_DEFAULT, zero_pol=True):
    """Read in an image from a text file.

       Args:
            fname (str): path to input text file
            pulse (function): The function convolved with the pixel values for continuous image.
            polrep (str): polarization representation, either 'stokes' or 'circ'
            pol_prim (str): The default image: I,Q,U or V for Stokes, RR,LL,LR,RL for Circular
            zero_pol (bool): If True, loads any missing polarizations as zeros

       Returns:
            (Image): loaded image object
    """

    return ehtim.io.load.load_im_txt(fname, pulse=pulse, polrep=polrep,
                                     pol_prim=pol_prim, zero_pol=True) 
開發者ID:achael,項目名稱:eht-imaging,代碼行數:18,代碼來源:image.py

示例10: dict2circuit

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def dict2circuit(datamap, handler=None, blockdict=None, putstart=None):
    '''
    parse a dict (probabily from a yaml file) to a circuit.

    Args:
        datamap (dict): the dictionary defining a circuit.
        handler (None|QuantumCircuit): the handler.
        blockdict (dict, default=datamap): the dictionary for block includes.
        putstart (bool, default=handler==None): put a start at the begining if True.
    '''
    if putstart is None: putstart = handler is None
    if handler is None: handler = QuantumCircuit(num_bit=datamap['nline'])
    if blockdict is None: blockdict = dict(datamap)
    if putstart:
        # text |0>s
        for i in range(datamap['nline']):
            plt.text(-0.4, -i, r'$\vert0\rangle$', va='center', ha='center', fontsize=setting['fontsize'])
        handler.x += 0.8

    if isinstance(datamap, str):
        vizcode(handler, datamap, blockdict=blockdict)
    else:
        for block in datamap['blocks']:
            dict2circuit(block, handler, blockdict, putstart=False) 
開發者ID:GiggleLiu,項目名稱:viznet,代碼行數:26,代碼來源:parsecircuit.py

示例11: test_edge

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def test_edge():
    edge_list = ['-', '..-', '->--', '<=>', '===->', '->-....-<-']
    clink_list = ['->', '<->', '>.>']
    offsets = [(), (-0.2, 0.2), (0.15, 0.3, -0.3)]
    with DynamicShow(figsize=(8, 6)) as ds:
        for i, style in enumerate(edge_list):
            edge = EdgeBrush(style, ds.ax)
            p1 = Pin((0, -i * 0.1))
            p2 = Pin((1, -i * 0.1))
            ei = edge >> (p1, p2)
            p1.text('"%s"'%style, 'left')
            if i == 0: ei.text('EdgeBrush', 'top')
        for j, (style, offset) in enumerate(zip(clink_list, offsets)):
            p1 = Pin((0, -i * 0.1 - (j+1)*0.3))
            p2 = Pin((1, -i * 0.1 - (j+1)*0.3))
            clink = CLinkBrush(style, color='r', roundness=0.05, offsets=offset)
            ei = clink >> (p1, p2)
            if j == 0: ei.text('CLinkBrush', 'top')
            p1.text('"%s", %s'%(style, str(offset)), 'left') 
開發者ID:GiggleLiu,項目名稱:viznet,代碼行數:21,代碼來源:test_brush.py

示例12: plot

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def plot(args):
    wc = pickle.load(open(os.path.join(args.data_dir, 'wc.dat'), 'rb'))
    words = sorted(wc, key=wc.get, reverse=True)[:args.top_k]
    if args.model == 'pca':
        model = PCA(n_components=2)
    elif args.model == 'tsne':
        model = TSNE(n_components=2, perplexity=30, init='pca', method='exact', n_iter=5000)
    word2idx = pickle.load(open('data/word2idx.dat', 'rb'))
    idx2vec = pickle.load(open('data/idx2vec.dat', 'rb'))
    X = [idx2vec[word2idx[word]] for word in words]
    X = model.fit_transform(X)
    plt.figure(figsize=(18, 18))
    for i in range(len(X)):
        plt.text(X[i, 0], X[i, 1], words[i], bbox=dict(facecolor='blue', alpha=0.1))
    plt.xlim((np.min(X[:, 0]), np.max(X[:, 0])))
    plt.ylim((np.min(X[:, 1]), np.max(X[:, 1])))
    if not os.path.isdir(args.result_dir):
        os.mkdir(args.result_dir)
    plt.savefig(os.path.join(args.result_dir, args.model) + '.png') 
開發者ID:theeluwin,項目名稱:pytorch-sgns,代碼行數:21,代碼來源:plot.py

示例13: cmPlot

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def cmPlot(confMatrix, classes, normalize=False, title='Confusion matrix', cmap=[]):
    if normalize:
        confMatrix = confMatrix.astype('float') / confMatrix.sum(axis=1)[:, np.newaxis]
        confMatrix = np.round(confMatrix * 100,1)
    if cmap == []:
        cmap = plt.cm.Blues

    #Actual plotting of the values
    thresh = confMatrix.max() / 2.
    for i, j in itertools.product(range(confMatrix.shape[0]), range(confMatrix.shape[1])):
        plt.text(j, i, confMatrix[i, j], horizontalalignment="center",
                 color="white" if confMatrix[i, j] > thresh else "black")

    avgAcc = np.mean([float(confMatrix[i, i]) / sum(confMatrix[:, i]) for i in range(confMatrix.shape[1])])
    plt.imshow(confMatrix, interpolation='nearest', cmap=cmap)
    plt.title(title + " (avgAcc={:2.2f}%)".format(100*avgAcc))
    plt.colorbar()
    plt.xticks(np.arange(len(classes)), classes, rotation=45)
    plt.yticks(np.arange(len(classes)), classes)
    plt.ylabel('True label')
    plt.xlabel('Predicted label') 
開發者ID:Azure-Samples,項目名稱:MachineLearningSamples-ImageClassificationUsingCntk,代碼行數:23,代碼來源:utilities_general_v2.py

示例14: show_graph

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def show_graph(g, vertex_color='typeof', size=15, vertex_label=None):
    """show_graph."""
    degrees = [len(g.neighbors(u)) for u in g.nodes()]

    print(('num nodes=%d' % len(g)))
    print(('num edges=%d' % len(g.edges())))
    print(('num non edges=%d' % len(list(nx.non_edges(g)))))
    print(('max degree=%d' % max(degrees)))
    print(('median degree=%d' % np.percentile(degrees, 50)))

    draw_graph(g, size=size,
               vertex_color=vertex_color, vertex_label=vertex_label,
               vertex_size=200, edge_label=None)

    # display degree distribution
    size = int((max(degrees) - min(degrees)) / 1.5)
    plt.figure(figsize=(size, 3))
    plt.title('Degree distribution')
    _bins = np.arange(min(degrees), max(degrees) + 2) - .5
    n, bins, patches = plt.hist(degrees, _bins,
                                alpha=0.3,
                                facecolor='navy', histtype='bar',
                                rwidth=0.8, edgecolor='k')
    labels = np.array([str(int(i)) for i in n])
    for xi, yi, label in zip(bins, n, labels):
        plt.text(xi + 0.5, yi, label, ha='center', va='bottom')

    plt.xticks(bins + 0.5)
    plt.xlim((min(degrees) - 1, max(degrees) + 1))
    plt.ylim((0, max(n) * 1.1))
    plt.xlabel('Node degree')
    plt.ylabel('Counts')
    plt.grid(linestyle=":")
    plt.show() 
開發者ID:fabriziocosta,項目名稱:EDeN,代碼行數:36,代碼來源:link_prediction_utils.py

示例15: plot_confusion_matrix

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import text [as 別名]
def plot_confusion_matrix(y_true, y_test, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    cm = confusion_matrix(y_true, y_test)
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label') 
開發者ID:EvilPsyCHo,項目名稱:TaskBot,代碼行數:34,代碼來源:plot.py


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