Python matplotlib.pyplot.text() Examples

The following are 30 code examples of matplotlib.pyplot.text(). 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: feature_vis.py    From transferlearning with MIT License 8 votes vote down vote up
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() 
Example #2
Source File: draw_plot.py    From TaobaoAnalysis with MIT License 6 votes vote down vote up
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)) 
Example #3
Source File: plot.py    From pytorch-sgns with MIT License 6 votes vote down vote up
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') 
Example #4
Source File: plot.py    From TaskBot with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #5
Source File: utilities_general_v2.py    From MachineLearningSamples-ImageClassificationUsingCntk with MIT License 6 votes vote down vote up
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') 
Example #6
Source File: plot.py    From ML_CIA with MIT License 6 votes vote down vote up
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') 
Example #7
Source File: parsecircuit.py    From viznet with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: test_brush.py    From viznet with MIT License 6 votes vote down vote up
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') 
Example #9
Source File: image.py    From eht-imaging with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #10
Source File: yolo_image.py    From ai-platform with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: main.py    From WxConn with MIT License 6 votes vote down vote up
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)  # 固定窗口位置 
Example #12
Source File: feature_show.py    From person-reid-lib with MIT License 6 votes vote down vote up
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 
Example #13
Source File: visual_callbacks.py    From squeezenet-keras with MIT License 6 votes vote down vote up
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() 
Example #14
Source File: main.py    From WxConn with MIT License 5 votes vote down vote up
def update_to_pre_login_success(self):
        self.lable_tip.config(text='登录成功,请稍等')
        self.lable_tip.update() 
Example #15
Source File: test_brush.py    From viznet with MIT License 5 votes vote down vote up
def test_ghz():
    num_bit = 4
    handler = QuantumCircuit(num_bit=4)
    basic = NodeBrush('qc.basic')
    C = NodeBrush('qc.C')
    NOT = NodeBrush('qc.NOT', size='small')
    END = NodeBrush('qc.end')
    M = NodeBrush('qc.measure')
    BOX = NodeBrush('qc.box')
    with DynamicShow() as ds:
        handler.x += 0.5
        handler.gate(basic, 0, 'X')
        for i in range(1, num_bit):
            handler.gate(basic, i, 'H')
        handler.x += 1
        handler.gate((C, NOT), (1, 0))
        handler.gate((C, NOT), (3, 2))
        handler.x += 0.7
        handler.gate((C, NOT), (2, 0))
        handler.x += 0.7
        handler.gate((C, NOT), (3, 2))
        handler.x += 1
        for i in range(num_bit):
            handler.gate(basic, i, 'H')
        handler.x += 1
        handler.gate(BOX, (0, 1, 2, 3), '$e^{-iHt}$')
        handler.x += 1
        for i in range(num_bit):
            handler.gate(M, i)
        handler.edge.ls = '='
        handler.x += 0.8
        for i in range(num_bit):
            handler.gate(END, i)

        # text |0>s
        for i in range(num_bit):
            plt.text(-0.4, -i, r'$\vert0\rangle_{Q_%d}$' %
                     i, va='center', ha='center', fontsize=18) 
Example #16
Source File: main.py    From WxConn with MIT License 5 votes vote down vote up
def update_progress(self, value):
        text = '正在统计连接数...{value}%'
        self.lable_progress.config(text=text.format(value=value))
        self.lable_progress.update()
        self.progress.config(value=value)
        self.progress.update() 
Example #17
Source File: main.py    From WxConn with MIT License 5 votes vote down vote up
def update_generating(self):
        text = '生成结果中,请稍后'
        self.lable_progress.config(text=text)
        self.lable_progress.update() 
Example #18
Source File: phaseest.py    From viznet with MIT License 5 votes vote down vote up
def qft():
    num_bit = 5
    num_bit2 = 3
    with DynamicShow((7, 5), '_phaseest.png') as ds:
        handler = QuantumCircuit(num_bit=num_bit+num_bit2, y0=2., locs=-np.append(0.8*np.arange(num_bit), 0.9*num_bit+0.3*np.arange(num_bit2)))
        handler.x += 0.7
        with handler.block(slice(0, num_bit-1), pad_x=0.2, pad_y=0.2) as boxes:
            [handler.gate(_.GATE, i, 'H') for i in range(num_bit)]
        boxes[0].text("A", 'top')
        handler.x +=1.2
        _.BOX.size = (0.4, 0.3)
        with handler.block(slice(0, num_bit+num_bit2-1),pad_x=0.2, pad_y=0.2) as boxes:
            for i in range(num_bit):
                handler.gate((_.C, _.BOX), (i, slice(num_bit,num_bit+num_bit2-1)), ['', r'$U^{%d}$'%(2**i)])
                if i!=num_bit-1:
                    handler.x +=1.0
        boxes[0].text("B", 'top')
        handler.x +=0.7
        for i in range(num_bit2):
            handler.gate(viznet.NodeBrush('pin'), num_bit+i)
        handler.x +=0.7

        _.BOX.size = (0.6, 0.3)
        handler.gate(_.BOX, slice(0, num_bit-1), r'QFT${}^\dagger$')
        handler.x +=1.0
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit+num_bit2):
            plt.text(*handler.get_position(i, x=-0.5), r'$\left\vert %s\right\rangle_{Q_%d}$' %
                     (0 if i<num_bit else '?', i+1), va='center', ha='center', fontsize=16)
        plt.text(3.5, -6, "Quantum Circuit for Phase Estimation", ha='center') 
Example #19
Source File: ghz.py    From viznet with MIT License 5 votes vote down vote up
def ghz4():
    '''4 bit GHZ circuit, applicable on ibmqx4 circuit.'''
    num_bit = 4
    with DynamicShow((5, 3), '_exact_ghz4_circuit.png') as ds:
        handler = QuantumCircuit(num_bit=4, y0=2.)
        handler.x += 0.5
        handler.gate(_.GATE, 0, 'X')
        for i in range(1, num_bit):
            handler.gate(_.GATE, i, 'H')
        handler.x += 1
        handler.gate((_.C, _.NOT), (1, 0))
        handler.gate((_.C, _.NOT), (3, 2))
        handler.x += 0.7
        handler.gate((_.C, _.NOT), (2, 0))
        handler.x += 0.7
        handler.gate((_.C, _.NOT), (3, 2))
        handler.x += 1
        for i in range(num_bit):
            handler.gate(_.GATE, i, 'H')
        handler.x += 1
        for i in range(num_bit):
            handler.gate(_.MEASURE, i)
        handler.edge.style = '='
        handler.x += 0.8
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit):
            plt.text(*handler.get_position(i, x=-0.5), r'$\left\vert0\right\rangle_{Q_%d}$' %
                     i, va='center', ha='center', fontsize=18) 
Example #20
Source File: differentiable.py    From viznet with MIT License 5 votes vote down vote up
def diffcircuit():
    '''illustration of block-focus scheme.'''
    num_bit = 4
    depth = 3
    with DynamicShow((10, 4), '_differentiable.png') as ds:
        plt.text(5, -4, "Differentiable Circuit of Size 4, depth 2")
        handler = QuantumCircuit(num_bit=num_bit)
        handler.x += 1.0
        with handler.block(slice(0, num_bit-1), pad_x=0.2, pad_y=0.1) as b:
            rot_gate(handler, 1, mask=[0,1,1])
        b[0].text('Rotation', 'top')
        handler.x += 1.0
        # entangler block
        with handler.block(slice(0, num_bit-1), pad_x=0, pad_y = 0.1) as b:
            entangle_gate(handler)
        b[0].text('Entangler', 'top')

        for i in range(depth-2):
            handler.x += 1.0
            rot_gate(handler, 2, mask=[1,1,1])
            handler.x += 1.0
            entangle_gate(handler)
        handler.x += 1.0
        rot_gate(handler, 3, mask=[1,1,0])

        handler.x += 1.0
        for i in range(num_bit):
            handler.gate(_.MEASURE, i)
        handler.edge.style = '='
        handler.x += 0.8
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit):
            plt.text(-0.5, -i, r'$\left\vert0\right\rangle$'
                     , va='center', ha='center', fontsize=16) 
Example #21
Source File: qft.py    From viznet with MIT License 5 votes vote down vote up
def qft():
    num_bit = 5
    with DynamicShow((10, 3.5), '_qft.png') as ds:
        handler = QuantumCircuit(num_bit=num_bit, y0=2.)
        handler.x += 0.7
        for i in range(num_bit):
            if i ==1:
                context = handler.block(slice(i, num_bit-1), pad_y=0.1, pad_x=0.2)
                boxes = context.__enter__()
            for k in range(i, num_bit):
                if i==k:
                    handler.gate(_.GATE, i, 'H')
                else:
                    if i ==0 and k==1+2:
                        context = handler.block(slice(i, k), pad_y=0.1, pad_x = 0.15)
                        boxes = context.__enter__()
                    handler.gate((_.C, _.WIDE), (k, i), ['',r'R${}_%d$'%(k-i+1)])
                    if i ==0 and k==1+2:
                        context.__exit__(None, None, None)
                        boxes[0].text("A", "top")
                if i==1 and k==num_bit-1:
                    context.__exit__(None, None, None)
                    boxes[0].text("B", "top")
                handler.x+=1.0
            handler.x+=0.2
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit):
            plt.text(*handler.get_position(i, x=-0.5), r'$\left\vert ?\right\rangle_{Q_%d}$' %
                     (i+1), va='center', ha='center', fontsize=16)
        plt.text(8.5, -3, "Quantum Fourier Transformation circuit of size 5", ha='center') 
Example #22
Source File: main.py    From WxConn with MIT License 5 votes vote down vote up
def update_qrcode(self):
        self.lable_tip.config(text='微信扫一扫开始统计')
        self.lable_tip.update()

        self.qrcode_pic = self._resize_ads_qrcode(ALS.user_qrcode_path, size=(200, 200))
        self.qrcode.create_image(0, 0, anchor='nw', image=self.qrcode_pic) 
Example #23
Source File: main.py    From WxConn with MIT License 5 votes vote down vote up
def _anim_button_emoji(self):
        """
        动态改变button中emoji
        """
        if self.anim_button_running:
            button_text = HAPPY_EMOJI[random.randint(0, len(HAPPY_EMOJI) - 1)]
            self.btn_enter.config(text=button_text)
            self.btn_enter.update()
            self.master.after(1000, self._anim_button_emoji) 
Example #24
Source File: main.py    From WxConn with MIT License 5 votes vote down vote up
def generate_city_pic(self, city_data):
        """
        生成城市数据图片
        因为plt在子线程中执行会出现自动弹出弹框并阻塞主线程的行为,plt行为均放在主线程中
        :param data:
        :return:
        """
        font = {'family': ['xkcd', 'Humor Sans', 'Comic Sans MS'],
                'weight': 'bold',
                'size': 12}
        matplotlib.rc('font', **font)
        cities = city_data['cities']
        city_people = city_data['city_people']

        # 绘制「性别分布」柱状图
        plt.barh(range(len(cities)), width=city_people, align='center', color=self.bar_color, alpha=0.8)
        # 添加轴标签
        plt.xlabel(u'Number of People')
        # 添加标题
        plt.title(u'Top %d Cities of your friends distributed' % len(cities), fontsize=self.title_font_size)
        # 添加刻度标签
        plt.yticks(range(len(cities)), cities)
        # 设置X轴的刻度范围
        plt.xlim([0, city_people[0] * 1.1])

        # 为每个条形图添加数值标签
        for x, y in enumerate(city_people):
            plt.text(y + len(str(y)), x, y, ha='center')

        # 显示图形
        plt.savefig(ALS.result_path + '/4.png')
        # todo 如果调用此处的关闭,就会导致应用本身也被关闭
        # plt.close()
        # plt.show() 
Example #25
Source File: main.py    From WxConn with MIT License 5 votes vote down vote up
def generate_sex_pic(self, sex_data):
        """
        生成性别数据图片
        因为plt在子线程中执行会出现自动弹出弹框并阻塞主线程的行为,plt行为均放在主线程中
        :param sex_data:
        :return:
        """
        # 绘制「性别分布」柱状图
        # 'steelblue'
        bar_figure = plt.bar(range(3), sex_data, align='center', color=self.bar_color, alpha=0.8)
        # 添加轴标签
        plt.ylabel(u'Number')
        # 添加标题
        plt.title(u'Male/Female in your Wechat', fontsize=self.title_font_size)
        # 添加刻度标签
        plt.xticks(range(3), [u'Male', u'Female', u'UnKnown'])
        # 设置Y轴的刻度范围
        # 0, male; 1, female; 2, unknown
        max_num = max(sex_data[0], max(sex_data[1], sex_data[2]))
        plt.ylim([0, max_num * 1.1])

        # 为每个条形图添加数值标签
        for x, y in enumerate(sex_data):
            plt.text(x, y + len(str(y)), y, ha='center')

        # 保存图片
        plt.savefig(ALS.result_path + '/2.png')
        # todo 如果不调用此处的关闭,就会导致生成最后一个图像出现折叠、缩小的混乱
        #bar_figure.remove()
        plt.clf()
        plt.delaxes()
        #plt.close()

        # 显示图形
        # plt.show() 
Example #26
Source File: plot_cm.py    From Deep-Learning-with-TensorFlow-Second-Edition with MIT License 5 votes vote down vote up
def plot_confusion_matrix(cm, 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`.
    """
    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)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

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

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

# Compute confusion matrix 
Example #27
Source File: classification_demo.py    From Deep-Learning-with-TensorFlow-Second-Edition with MIT License 5 votes vote down vote up
def print_and_plot_confusion_matrix(cm, 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`.
    """
    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)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

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

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    return cm

# Plot non-normalized confusion matrix 
Example #28
Source File: utils.py    From MCF-3D-CNN with MIT License 5 votes vote down vote up
def plot_confusion_matrix(cm, classes,
                          save_tag = '',
                          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`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=0)
    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')
    plt.savefig('experiments/img/'+ save_tag + '_cfm.png')
    plt.close('all') # 关闭图 
Example #29
Source File: link_prediction_utils.py    From EDeN with MIT License 5 votes vote down vote up
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() 
Example #30
Source File: main.py    From WxConn with MIT License 5 votes vote down vote up
def done(self):
        text = '统计成功\n请在微信"文件传输助手"查看'
        self.lable_progress.config(text=text)
        self.lable_progress.update()