本文整理汇总了Python中matplotlib.pyplot.legend方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.legend方法的具体用法?Python pyplot.legend怎么用?Python pyplot.legend使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.legend方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: show
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [as 别名]
def show(mnist, targets, ret):
target_ids = range(len(set(targets)))
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'violet', 'orange', 'purple']
plt.figure(figsize=(12, 10))
ax = plt.subplot(aspect='equal')
for label in set(targets):
idx = np.where(np.array(targets) == label)[0]
plt.scatter(ret[idx, 0], ret[idx, 1], c=colors[label], label=label)
for i in range(0, len(targets), 250):
img = (mnist[i][0] * 0.3081 + 0.1307).numpy()[0]
img = OffsetImage(img, cmap=plt.cm.gray_r, zoom=0.5)
ax.add_artist(AnnotationBbox(img, ret[i]))
plt.legend()
plt.show()
示例2: run_eval
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [as 别名]
def run_eval(sess, test_X, test_y):
ds = tf.data.Dataset.from_tensor_slices((test_X, test_y))
ds = ds.batch(1)
X, y = ds.make_one_shot_iterator().get_next()
with tf.variable_scope("model", reuse=True):
prediction, _, _ = lstm_model(X, [0.0], False)
predictions = []
labels = []
for i in range(TESTING_EXAMPLES):
p, l = sess.run([prediction, y])
predictions.append(p)
labels.append(l)
predictions = np.array(predictions).squeeze()
labels = np.array(labels).squeeze()
rmse = np.sqrt(((predictions-labels) ** 2).mean(axis=0))
print("Mean Square Error is: %f" % rmse)
plt.figure()
plt.plot(predictions, label='predictions')
plt.plot(labels, label='real_sin')
plt.legend()
plt.show()
示例3: plot_mul
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [as 别名]
def plot_mul(Y_hat, Y, pred_len):
"""
PLots the predicted data versus true data
Input: Predicted data, True Data, Length of prediction
Output: return plot
Note: Run from timeSeriesPredict.py
"""
fig = plt.figure(facecolor='white')
ax = fig.add_subplot(111)
ax.plot(Y, label='Y')
# Print the predictions in its respective series-length
for i, j in enumerate(Y_hat):
shift = [None for p in range(i * pred_len)]
plt.plot(shift + j, label='Y_hat')
plt.legend()
plt.show()
示例4: compute_roc
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [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
示例5: compute_roc_rfeinman
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [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
示例6: plot_learning_curve
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [as 别名]
def plot_learning_curve(X, y, Xval, yval, l=0):
training_cost, cv_cost = [], []
m = X.shape[0]
for i in range(1, m + 1):
# regularization applies here for fitting parameters
res = linear_regression_np(X[:i, :], y[:i], l=l)
# remember, when you compute the cost here, you are computing
# non-regularized cost. Regularization is used to fit parameters only
tc = cost(res.x, X[:i, :], y[:i])
cv = cost(res.x, Xval, yval)
training_cost.append(tc)
cv_cost.append(cv)
plt.plot(np.arange(1, m + 1), training_cost, label='training cost')
plt.plot(np.arange(1, m + 1), cv_cost, label='cv cost')
plt.legend(loc=1)
示例7: plot
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [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()
示例8: visualize_anomaly
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [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()
示例9: plot_wh_methods
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [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)
示例10: plot_results
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [as 别名]
def plot_results(start=0, stop=0): # from utils.utils import *; plot_results()
# Plot training results files 'results*.txt'
fig, ax = plt.subplots(2, 5, figsize=(14, 7))
ax = ax.ravel()
s = ['GIoU', 'Objectness', 'Classification', 'Precision', 'Recall',
'val GIoU', 'val Objectness', 'val Classification', 'mAP', 'F1']
for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
n = results.shape[1] # number of rows
x = range(start, min(stop, n) if stop else n)
for i in range(10):
y = results[i, x]
if i in [0, 1, 2, 5, 6, 7]:
y[y == 0] = np.nan # dont show zero loss values
ax[i].plot(x, y, marker='.', label=f.replace('.txt', ''))
ax[i].set_title(s[i])
if i in [5, 6, 7]: # share train and val loss y axes
ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
fig.tight_layout()
ax[1].legend()
fig.savefig('results.png', dpi=200)
示例11: plot_results_overlay
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [as 别名]
def plot_results_overlay(start=0, stop=0): # from utils.utils import *; plot_results_overlay()
# Plot training results files 'results*.txt', overlaying train and val losses
s = ['train', 'train', 'train', 'Precision', 'mAP', 'val', 'val', 'val', 'Recall', 'F1'] # legends
t = ['GIoU', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
n = results.shape[1] # number of rows
x = range(start, min(stop, n) if stop else n)
fig, ax = plt.subplots(1, 5, figsize=(14, 3.5))
ax = ax.ravel()
for i in range(5):
for j in [i, i + 5]:
y = results[j, x]
if i in [0, 1, 2]:
y[y == 0] = np.nan # dont show zero loss values
ax[i].plot(x, y, marker='.', label=s[j])
ax[i].set_title(t[i])
ax[i].legend()
ax[i].set_ylabel(f) if i == 0 else None # add filename
fig.tight_layout()
fig.savefig(f.replace('.txt', '.png'), dpi=200)
示例12: plot_12
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [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
)
示例13: plot_13
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [as 别名]
def plot_13(data):
r1, r2, r3, r4 = data
plt.figure()
add_plot(r3, 'MeanReward100Episodes');
add_plot(r3, 'BestMeanReward', 'gamma = 0.9');
add_plot(r2, 'MeanReward100Episodes');
add_plot(r2, 'BestMeanReward', 'gamma = 0.99');
add_plot(r4, 'MeanReward100Episodes');
add_plot(r4, 'BestMeanReward', 'gamma = 0.999');
plt.legend();
plt.xlabel('Time step');
plt.ylabel('Reward');
plt.savefig(
os.path.join('results', 'p13.png'),
bbox_inches='tight',
transparent=True,
pad_inches=0.1
)
示例14: plot_3
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [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')
示例15: plot_result_data
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import legend [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))