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


Python pyplot.xlabel方法代碼示例

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


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

示例1: plot_confusion_matrix

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def plot_confusion_matrix(y_true, y_pred, size=None, normalize=False):
    """plot_confusion_matrix."""
    cm = confusion_matrix(y_true, y_pred)
    fmt = "%d"
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        fmt = "%.2f"
    xticklabels = list(sorted(set(y_pred)))
    yticklabels = list(sorted(set(y_true)))
    if size is not None:
        plt.figure(figsize=(size, size))
    heatmap(cm, xlabel='Predicted label', ylabel='True label',
            xticklabels=xticklabels, yticklabels=yticklabels,
            cmap=plt.cm.Blues, fmt=fmt)
    if normalize:
        plt.title("Confusion matrix (norm.)")
    else:
        plt.title("Confusion matrix")
    plt.gca().invert_yaxis() 
開發者ID:fabriziocosta,項目名稱:EDeN,代碼行數:21,代碼來源:__init__.py

示例2: plot_roc_curve

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def plot_roc_curve(y_true, y_score, size=None):
    """plot_roc_curve."""
    false_positive_rate, true_positive_rate, thresholds = roc_curve(
        y_true, y_score)
    if size is not None:
        plt.figure(figsize=(size, size))
        plt.axis('equal')
    plt.plot(false_positive_rate, true_positive_rate, lw=2, color='navy')
    plt.plot([0, 1], [0, 1], color='gray', lw=1, linestyle='--')
    plt.xlabel('False positive rate')
    plt.ylabel('True positive rate')
    plt.ylim([-0.05, 1.05])
    plt.xlim([-0.05, 1.05])
    plt.grid()
    plt.title('Receiver operating characteristic AUC={0:0.2f}'.format(
        roc_auc_score(y_true, y_score))) 
開發者ID:fabriziocosta,項目名稱:EDeN,代碼行數:18,代碼來源:__init__.py

示例3: update

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def update(self, xPhys, u, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu)
        # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu)
        self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress)))
        stress_rgba = self.myColorMap.to_rgba(stress)
        stress_rgba[:, :, 3] = xPhys.reshape(-1, 1)
        self.stress_im.set_array(np.swapaxes(
            stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1))
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        else:
            plt.xlabel("Max stress = {:.2f}".format(max(stress)[0]))
        plt.pause(0.01) 
開發者ID:zfergus,項目名稱:fenics-topopt,代碼行數:19,代碼來源:stress_gui.py

示例4: plot_num_recall

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def plot_num_recall(recalls, proposal_nums):
    """Plot Proposal_num-Recalls curve.

    Args:
        recalls(ndarray or list): shape (k,)
        proposal_nums(ndarray or list): same shape as `recalls`
    """
    if isinstance(proposal_nums, np.ndarray):
        _proposal_nums = proposal_nums.tolist()
    else:
        _proposal_nums = proposal_nums
    if isinstance(recalls, np.ndarray):
        _recalls = recalls.tolist()
    else:
        _recalls = recalls

    import matplotlib.pyplot as plt
    f = plt.figure()
    plt.plot([0] + _proposal_nums, [0] + _recalls)
    plt.xlabel('Proposal num')
    plt.ylabel('Recall')
    plt.axis([0, proposal_nums.max(), 0, 1])
    f.show() 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:25,代碼來源:recall.py

示例5: plot_iou_recall

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def plot_iou_recall(recalls, iou_thrs):
    """Plot IoU-Recalls curve.

    Args:
        recalls(ndarray or list): shape (k,)
        iou_thrs(ndarray or list): same shape as `recalls`
    """
    if isinstance(iou_thrs, np.ndarray):
        _iou_thrs = iou_thrs.tolist()
    else:
        _iou_thrs = iou_thrs
    if isinstance(recalls, np.ndarray):
        _recalls = recalls.tolist()
    else:
        _recalls = recalls

    import matplotlib.pyplot as plt
    f = plt.figure()
    plt.plot(_iou_thrs + [1.0], _recalls + [0.])
    plt.xlabel('IoU')
    plt.ylabel('Recall')
    plt.axis([iou_thrs.min(), 1, 0, 1])
    f.show() 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:25,代碼來源:recall.py

示例6: compute_roc

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def compute_roc(y_true, y_pred, plot=False):
    """
    TODO
    :param y_true: ground truth
    :param y_pred: predictions
    :param plot:
    :return:
    """
    fpr, tpr, _ = roc_curve(y_true, y_pred)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
開發者ID:StephanZheng,項目名稱:neural-fingerprinting,代碼行數:23,代碼來源:util.py

示例7: compute_roc_rfeinman

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def compute_roc_rfeinman(probs_neg, probs_pos, plot=False):
    """
    TODO
    :param probs_neg:
    :param probs_pos:
    :param plot:
    :return:
    """
    probs = np.concatenate((probs_neg, probs_pos))
    labels = np.concatenate((np.zeros_like(probs_neg), np.ones_like(probs_pos)))
    fpr, tpr, _ = roc_curve(labels, probs)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
開發者ID:StephanZheng,項目名稱:neural-fingerprinting,代碼行數:25,代碼來源:util.py

示例8: visualize_sampling

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def visualize_sampling(self,permutations):
        max_length = len(permutations[0])
        grid = np.zeros([max_length,max_length]) # initialize heatmap grid to 0
        transposed_permutations = np.transpose(permutations)
        for t, cities_t in enumerate(transposed_permutations): # step t, cities chosen at step t
            city_indices, counts = np.unique(cities_t,return_counts=True,axis=0)
            for u,v in zip(city_indices, counts):
                grid[t][u]+=v # update grid with counts from the batch of permutations
        # plot heatmap
        fig = plt.figure()
        rcParams.update({'font.size': 22})
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(grid, interpolation='nearest', cmap='gray')
        plt.colorbar()
        plt.title('Sampled permutations')
        plt.ylabel('Time t')
        plt.xlabel('City i')
        plt.show()

    # Heatmap of attention (x=cities; y=steps) 
開發者ID:MichelDeudon,項目名稱:neural-combinatorial-optimization-rl-tensorflow,代碼行數:23,代碼來源:dataset.py

示例9: visualize_sampling

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def visualize_sampling(self, permutations):
        max_length = len(permutations[0])
        grid = np.zeros([max_length,max_length]) # initialize heatmap grid to 0

        transposed_permutations = np.transpose(permutations)
        for t, cities_t in enumerate(transposed_permutations): # step t, cities chosen at step t
            city_indices, counts = np.unique(cities_t,return_counts=True,axis=0)
            for u,v in zip(city_indices, counts):
                grid[t][u]+=v # update grid with counts from the batch of permutations

        # plot heatmap
        fig = plt.figure()
        rcParams.update({'font.size': 22})
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(grid, interpolation='nearest', cmap='gray')
        plt.colorbar()
        plt.title('Sampled permutations')
        plt.ylabel('Time t')
        plt.xlabel('City i')
        plt.show() 
開發者ID:MichelDeudon,項目名稱:neural-combinatorial-optimization-rl-tensorflow,代碼行數:23,代碼來源:dataset.py

示例10: plot

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def plot(PDF, figName, imgpath, show=False, save=True):
    # plot
    output = PDF.get_constraint_value()
    plt.plot(PDF.experimentalDistances,PDF.experimentalPDF, 'ro', label="experimental", markersize=7.5, markevery=1 )
    plt.plot(PDF.shellsCenter, output["pdf"], 'k', linewidth=3.0,  markevery=25, label="total" )

    styleIndex = 0
    for key in output:
        val = output[key]
        if key in ("pdf_total", "pdf"):
            continue
        elif "inter" in key:
            plt.plot(PDF.shellsCenter, val, STYLE[styleIndex], markevery=5, label=key.split('rdf_inter_')[1] )
            styleIndex+=1
    plt.legend(frameon=False, ncol=1)
    # set labels
    plt.title("$\\chi^{2}=%.6f$"%PDF.squaredDeviations, size=20)
    plt.xlabel("$r (\AA)$", size=20)
    plt.ylabel("$g(r)$", size=20)
    # show plot
    if save: plt.savefig(figName)
    if show: plt.show()
    plt.close() 
開發者ID:bachiraoun,項目名稱:fullrmc,代碼行數:25,代碼來源:plotFigures.py

示例11: visualize_anomaly

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def visualize_anomaly(y_true, reconstruction_error, threshold):
    error_df = pd.DataFrame({'reconstruction_error': reconstruction_error,
                             'true_class': y_true})
    print(error_df.describe())

    groups = error_df.groupby('true_class')
    fig, ax = plt.subplots()

    for name, group in groups:
        ax.plot(group.index, group.reconstruction_error, marker='o', ms=3.5, linestyle='',
                label="Fraud" if name == 1 else "Normal")

    ax.hlines(threshold, ax.get_xlim()[0], ax.get_xlim()[1], colors="r", zorder=100, label='Threshold')
    ax.legend()
    plt.title("Reconstruction error for different classes")
    plt.ylabel("Reconstruction error")
    plt.xlabel("Data point index")
    plt.show() 
開發者ID:chen0040,項目名稱:keras-anomaly-detection,代碼行數:20,代碼來源:plot_utils.py

示例12: plot_wh_methods

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def plot_wh_methods():  # from utils.utils import *; plot_wh_methods()
    # Compares the two methods for width-height anchor multiplication
    # https://github.com/ultralytics/yolov3/issues/168
    x = np.arange(-4.0, 4.0, .1)
    ya = np.exp(x)
    yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2

    fig = plt.figure(figsize=(6, 3), dpi=150)
    plt.plot(x, ya, '.-', label='yolo method')
    plt.plot(x, yb ** 2, '.-', label='^2 power method')
    plt.plot(x, yb ** 2.5, '.-', label='^2.5 power method')
    plt.xlim(left=-4, right=4)
    plt.ylim(bottom=0, top=6)
    plt.xlabel('input')
    plt.ylabel('output')
    plt.legend()
    fig.tight_layout()
    fig.savefig('comparison.png', dpi=200) 
開發者ID:zbyuan,項目名稱:pruning_yolov3,代碼行數:20,代碼來源:utils.py

示例13: plot_12

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def plot_12(data):
    r1, r2, r3, r4 = data
    plt.figure()
    add_plot(r1, 'MeanReward100Episodes');
    add_plot(r1, 'BestMeanReward', 'vanilla DQN');
    add_plot(r2, 'MeanReward100Episodes');
    add_plot(r2, 'BestMeanReward', 'double DQN');
    plt.xlabel('Time step');
    plt.ylabel('Reward');
    plt.legend();
    plt.savefig(
        os.path.join('results', 'p12.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
開發者ID:xuwd11,項目名稱:cs294-112_hws,代碼行數:18,代碼來源:plot_part1.py

示例14: plot_3

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def plot_3(data):
    x = data.Iteration.unique()
    y_mean = data.groupby('Iteration').mean()
    y_std = data.groupby('Iteration').std()
    
    sns.set(style="darkgrid", font_scale=1.5)
    value = 'AverageReturn'
    plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_train');
    plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2);
    value = 'ValAverageReturn'
    plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_test');
    plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2);
    
    plt.xlabel('Iteration')
    plt.ylabel('AverageReturn')
    plt.legend(loc='best') 
開發者ID:xuwd11,項目名稱:cs294-112_hws,代碼行數:18,代碼來源:plot_3.py

示例15: plot_result_data

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import xlabel [as 別名]
def plot_result_data(acc_total, acc_val_total, loss_total, losss_val_total, cfg_path, epoch):
    import matplotlib.pyplot as plt
    y = range(epoch)
    plt.plot(y,acc_total,linestyle="-",  linewidth=1,label='acc_train')
    plt.plot(y,acc_val_total,linestyle="-", linewidth=1,label='acc_val')
    plt.legend(('acc_train', 'acc_val'), loc='upper right')
    plt.xlabel("Training Epoch")
    plt.ylabel("Acc on dataset")
    plt.savefig('{}/acc.png'.format(cfg_path))
    plt.cla()
    plt.plot(y,loss_total,linestyle="-", linewidth=1,label='loss_train')
    plt.plot(y,losss_val_total,linestyle="-", linewidth=1,label='loss_val')
    plt.legend(('loss_train', 'loss_val'), loc='upper right')
    plt.xlabel("Training Epoch")
    plt.ylabel("Loss on dataset")
    plt.savefig('{}/loss.png'.format(cfg_path)) 
開發者ID:HaiyangLiu1997,項目名稱:Pytorch-Networks,代碼行數:18,代碼來源:utils.py


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