Python matplotlib.pyplot.show() Examples
The following are 30 code examples for showing how to use matplotlib.pyplot.show(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
matplotlib.pyplot
, or try the search function
.
Example 1
Project: Sound-Recognition-Tutorial Author: JasonZhang156 File: data_augmentation.py License: Apache License 2.0 | 8 votes |
def demo_plot(): audio = './data/esc10/audio/Dog/1-30226-A.ogg' y, sr = librosa.load(audio, sr=44100) y_ps = librosa.effects.pitch_shift(y, sr, n_steps=6) # n_steps控制音调变化尺度 y_ts = librosa.effects.time_stretch(y, rate=1.2) # rate控制时间维度的变换尺度 plt.subplot(311) plt.plot(y) plt.title('Original waveform') plt.axis([0, 200000, -0.4, 0.4]) # plt.axis([88000, 94000, -0.4, 0.4]) plt.subplot(312) plt.plot(y_ts) plt.title('Time Stretch transformed waveform') plt.axis([0, 200000, -0.4, 0.4]) plt.subplot(313) plt.plot(y_ps) plt.title('Pitch Shift transformed waveform') plt.axis([0, 200000, -0.4, 0.4]) # plt.axis([88000, 94000, -0.4, 0.4]) plt.tight_layout() plt.show()
Example 2
Project: MomentumContrast.pytorch Author: peisuke File: test.py License: MIT License | 6 votes |
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()
Example 3
Project: pepper-robot-programming Author: maverickjoy File: asthama_search.py License: MIT License | 6 votes |
def _capture2dImage(self, cameraId): # Capture Image in RGB # WARNING : The same Name could be used only six time. strName = "capture2DImage_{}".format(random.randint(1,10000000000)) clientRGB = self.video_service.subscribeCamera(strName, cameraId, AL_kVGA, 11, 10) imageRGB = self.video_service.getImageRemote(clientRGB) imageWidth = imageRGB[0] imageHeight = imageRGB[1] array = imageRGB[6] image_string = str(bytearray(array)) # Create a PIL Image from our pixel array. im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string) # Save the image. image_name_2d = "images/img2d-" + str(self.imageNo2d) + ".png" im.save(image_name_2d, "PNG") # Stored in images folder in the pwd, if not present then create one self.imageNo2d += 1 im.show() return
Example 4
Project: pepper-robot-programming Author: maverickjoy File: asthama_search.py License: MIT License | 6 votes |
def _capture3dImage(self): # Depth Image in RGB # WARNING : The same Name could be used only six time. strName = "capture3dImage_{}".format(random.randint(1,10000000000)) clientRGB = self.video_service.subscribeCamera(strName, AL_kDepthCamera, AL_kQVGA, 11, 10) imageRGB = self.video_service.getImageRemote(clientRGB) imageWidth = imageRGB[0] imageHeight = imageRGB[1] array = imageRGB[6] image_string = str(bytearray(array)) # Create a PIL Image from our pixel array. im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string) # Save the image. image_name_3d = "images/img3d-" + str(self.imageNo3d) + ".png" im.save(image_name_3d, "PNG") # Stored in images folder in the pwd, if not present then create one self.imageNo3d += 1 im.show() return
Example 5
Project: Stock-Price-Prediction Author: dhingratul File: helper.py License: MIT License | 6 votes |
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()
Example 6
Project: dustmaps Author: gregreen File: test_bayestar.py License: GNU General Public License v2.0 | 6 votes |
def atest_plot_samples(self): dm = np.linspace(4., 19., 1001) samples = [] for dm_k in dm: d = 10.**(dm_k/5.-2.) samples.append(self._interp_ebv(self._test_data[0], d)) samples = np.array(samples).T # print samples import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1,1,1) for s in samples: ax.plot(dm, s, lw=2., alpha=0.5) plt.show()
Example 7
Project: mmdetection Author: open-mmlab File: inference.py License: Apache License 2.0 | 6 votes |
def show_result_pyplot(model, img, result, score_thr=0.3, fig_size=(15, 10)): """Visualize the detection results on the image. Args: model (nn.Module): The loaded detector. img (str or np.ndarray): Image filename or loaded image. result (tuple[list] or list): The detection result, can be either (bbox, segm) or just bbox. score_thr (float): The threshold to visualize the bboxes and masks. fig_size (tuple): Figure size of the pyplot figure. """ if hasattr(model, 'module'): model = model.module img = model.show_result(img, result, score_thr=score_thr, show=False) plt.figure(figsize=fig_size) plt.imshow(mmcv.bgr2rgb(img)) plt.show()
Example 8
Project: neural-fingerprinting Author: StephanZheng File: util.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example 9
Project: neural-fingerprinting Author: StephanZheng File: util.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example 10
Project: deep-learning-note Author: wdxtub File: 3_linear_regression_raw.py License: MIT License | 6 votes |
def generate_dataset(true_w, true_b): num_examples = 1000 features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float) # 真实 label labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b # 添加噪声 labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float) # 展示下分布 plt.scatter(features[:, 1].numpy(), labels.numpy(), 1) plt.show() return features, labels # batch 读取数据集
Example 11
Project: deep-learning-note Author: wdxtub File: simulate_sin.py License: MIT License | 6 votes |
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()
Example 12
Project: neural-combinatorial-optimization-rl-tensorflow Author: MichelDeudon File: dataset.py License: MIT License | 6 votes |
def visualize_2D_trip(self,trip,tw_open,tw_close): plt.figure(figsize=(30,30)) rcParams.update({'font.size': 22}) # Plot cities colors = ['red'] # Depot is first city for i in range(len(tw_open)-1): colors.append('blue') plt.scatter(trip[:,0], trip[:,1], color=colors, s=200) # Plot tour tour=np.array(list(range(len(trip))) + [0]) X = trip[tour, 0] Y = trip[tour, 1] plt.plot(X, Y,"--", markersize=100) # Annotate cities with TW tw_open = np.rint(tw_open) tw_close = np.rint(tw_close) time_window = np.concatenate((tw_open,tw_close),axis=1) for tw, (x, y) in zip(time_window,(zip(X,Y))): plt.annotate(tw,xy=(x, y)) plt.xlim(0,60) plt.ylim(0,60) plt.show() # Heatmap of permutations (x=cities; y=steps)
Example 13
Project: neural-combinatorial-optimization-rl-tensorflow Author: MichelDeudon File: dataset.py License: MIT License | 6 votes |
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)
Example 14
Project: neural-combinatorial-optimization-rl-tensorflow Author: MichelDeudon File: dataset.py License: MIT License | 6 votes |
def visualize_2D_trip(self, trip): plt.figure(figsize=(30,30)) rcParams.update({'font.size': 22}) # Plot cities plt.scatter(trip[:,0], trip[:,1], s=200) # Plot tour tour=np.array(list(range(len(trip))) + [0]) X = trip[tour, 0] Y = trip[tour, 1] plt.plot(X, Y,"--", markersize=100) # Annotate cities with order labels = range(len(trip)) for i, (x, y) in zip(labels,(zip(X,Y))): plt.annotate(i,xy=(x, y)) plt.xlim(0,100) plt.ylim(0,100) plt.show() # Heatmap of permutations (x=cities; y=steps)
Example 15
Project: neural-combinatorial-optimization-rl-tensorflow Author: MichelDeudon File: dataset.py License: MIT License | 6 votes |
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()
Example 16
Project: fullrmc Author: bachiraoun File: plotFigures.py License: GNU Affero General Public License v3.0 | 6 votes |
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()
Example 17
Project: keras-anomaly-detection Author: chen0040 File: h2o_ecg_pulse_detection.py License: MIT License | 6 votes |
def plot_bidimensional(model, test, recon_error, layer, title): bidimensional_data = model.deepfeatures(test, layer).cbind(recon_error).as_data_frame() cmap = cm.get_cmap('Spectral') fig, ax = plt.subplots() bidimensional_data.plot(kind='scatter', x='DF.L{}.C1'.format(layer + 1), y='DF.L{}.C2'.format(layer + 1), s=500, c='Reconstruction.MSE', title=title, ax=ax, colormap=cmap) layer_column = 'DF.L{}.C'.format(layer + 1) columns = [layer_column + '1', layer_column + '2'] for k, v in bidimensional_data[columns].iterrows(): ax.annotate(k, v, size=20, verticalalignment='bottom', horizontalalignment='left') fig.canvas.draw() plt.show()
Example 18
Project: keras-anomaly-detection Author: chen0040 File: plot_utils.py License: MIT License | 6 votes |
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()
Example 19
Project: indras_net Author: gcallah File: display_methods.py License: GNU General Public License v3.0 | 5 votes |
def draw_graph(graph, title, hierarchy=False, root=None): """ Drawing networkx graphs. graph is the graph to draw. hierarchy is whether we should draw it as a tree. """ # pos = None plt.title(title) # if hierarchy: # pos = hierarchy_pos(graph, root) # out for now: # nx.draw(graph, pos=pos, with_labels=True) plt.show()
Example 20
Project: indras_net Author: gcallah File: display_methods.py License: GNU General Public License v3.0 | 5 votes |
def show(self): """ Display the plot. """ if not self.headless: plt.show() else: file = io.BytesIO() plt.savefig(file, format="png") return file
Example 21
Project: indras_net Author: gcallah File: display_methods.py License: GNU General Public License v3.0 | 5 votes |
def update_plot(self, i): """ This is our animation function. For line graphs, redraw the whole thing. """ plt.clf() (data_points, varieties) = self.data_func() self.draw_graph(data_points, varieties) self.show()
Example 22
Project: indras_net Author: gcallah File: display_methods.py License: GNU General Public License v3.0 | 5 votes |
def show(self): """ Display the plot. """ if not self.headless: plt.show() else: file = io.BytesIO() plt.savefig(file, format="png") return file
Example 23
Project: indras_net Author: gcallah File: display_methods.py License: GNU General Public License v3.0 | 5 votes |
def draw_graph(graph, title, hierarchy=False, root=None): """ Drawing networkx graphs. graph is the graph to draw. hierarchy is whether we should draw it as a tree. """ pos = None plt.title(title) if hierarchy: pos = hierarchy_pos(graph, root) nx.draw(graph, pos=pos, with_labels=True) plt.show()
Example 24
Project: indras_net Author: gcallah File: display_methods.py License: GNU General Public License v3.0 | 5 votes |
def update_plot(self, i): """ This is our animation function. For line graphs, redraw the whole thing. """ plt.clf() (data_points, varieties) = self.data_func() self.draw_graph(data_points, varieties) self.show()
Example 25
Project: indras_net Author: gcallah File: display_methods.py License: GNU General Public License v3.0 | 5 votes |
def __init__(self, title, varieties, width, height, anim=True, data_func=None, is_headless=False, legend_pos=4): """ Setup a scatter plot. varieties contains the different types of entities to show in the plot, which will get assigned different colors """ global anim_func self.scats = None self.anim = anim self.data_func = data_func self.s = ceil(4096 / width) self.headless = is_headless fig, ax = plt.subplots() ax.set_xlim(0, width) ax.set_ylim(0, height) self.create_scats(varieties) ax.legend(loc = legend_pos) ax.set_title(title) plt.grid(True) if anim and not self.headless: anim_func = animation.FuncAnimation(fig, self.update_plot, frames=1000, interval=500, blit=False)
Example 26
Project: indras_net Author: gcallah File: display_methods.py License: GNU General Public License v3.0 | 5 votes |
def show(self): """ Display the plot. """ if not self.headless: plt.show() else: file = io.BytesIO() plt.savefig(file, format="png") return file
Example 27
Project: simulated-annealing-tsp Author: chncyhn File: anneal.py License: MIT License | 5 votes |
def plot_learning(self): """ Plot the fitness through iterations. """ plt.plot([i for i in range(len(self.fitness_list))], self.fitness_list) plt.ylabel("Fitness") plt.xlabel("Iteration") plt.show()
Example 28
Project: vergeml Author: mme File: pr.py License: MIT License | 5 votes |
def __call__(self, args, env): import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import average_precision_score from sklearn.metrics import precision_recall_curve from vergeml.plots import load_labels, load_predictions try: labels = load_labels(env) except FileNotFoundError: raise VergeMLError("Can't plot PR curve - not supported by model.") nclasses = len(labels) if args['class'] not in labels: raise VergeMLError("Unknown class: " + args['class']) try: y_test, y_score = load_predictions(env, nclasses) except FileNotFoundError: raise VergeMLError("Can't plot PR curve - not supported by model.") # From: # https://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html#sphx-glr-auto-examples-model-selection-plot-precision-recall-py ix = labels.index(args['class']) y_test = y_test[:,ix].astype(np.int) y_score = y_score[:,ix] precision, recall, _ = precision_recall_curve(y_test, y_score) average_precision = average_precision_score(y_test, y_score) plt.step(recall, precision, color='b', alpha=0.2, where='post') plt.fill_between(recall, precision, alpha=0.2, color='b', step='post') plt.xlabel('Recall ({})'.format(args['class'])) plt.ylabel('Precision ({})'.format(args['class'])) plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Precision-Recall curve for @{0}: AP={1:0.2f}'.format(args['@AI'], average_precision)) plt.show()
Example 29
Project: pepper-robot-programming Author: maverickjoy File: asthama_search.py License: MIT License | 5 votes |
def run(self): self._printLogs("Waiting for the robot to be in wake up position", "OKBLUE") self.motion_service.wakeUp() self.posture_service.goToPosture("StandInit", 0.1) self.create_callbacks() # self.startDLServer() self._addTopic() # graphplots self._initialisePlot() ani = animation.FuncAnimation(self.fig, self._animate, blit=False, interval=500 ,repeat=False) # loop on, wait for events until manual interruption try: # while True: # time.sleep(1) # starting graph plot plt.show() # blocking call hence no need for while(True) except KeyboardInterrupt: self._printLogs("Interrupted by user, shutting down", "FAIL") self._cleanUp() self._printLogs("Waiting for the robot to be in rest position", "FAIL") # self.motion_service.rest() sys.exit(0) return
Example 30
Project: pedestrian-haar-based-detector Author: felipecorrea File: detect.py License: GNU General Public License v2.0 | 5 votes |
def generate_histogram(img): hist,bins = np.histogram(img.flatten(),256,[0,256]) #cumulative distribution function calculation cdf = hist.cumsum() plt.plot(cdf_normalized, color = 'b') plt.hist(img.flatten(),256,[0,256], color = 'r') plt.xlim([0,256]) plt.legend(('cdf','histogram'), loc = 'upper left') plt.show() return hist