Python matplotlib.patches.Patch() Examples
The following are 30
code examples of matplotlib.patches.Patch().
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.patches
, or try the search function
.
Example #1
Source File: main.py From recaptcha-cracker with GNU General Public License v3.0 | 7 votes |
def graph_correct_captchas(captcha_queries, correct_captchas): queries_and_correct_scores = zip(captcha_queries, correct_captchas) queries_and_correct_scores = sorted(queries_and_correct_scores, key=lambda x:x[1], reverse=True) captcha_queries, correct_captchas = zip(*queries_and_correct_scores) captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries] bars = plt.bar(left=range(len(correct_captchas)), height=correct_captchas) patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))] plt.legend(handles=patches) plt.xticks([]) for i, bar in enumerate(bars): bar.set_color(colours[i]) plt.show() # graph_correct_captchas(captcha_queries, correct_captchas) # graph_query_amounts(captcha_queries, query_amounts)
Example #2
Source File: main.py From recaptcha-cracker with GNU General Public License v3.0 | 7 votes |
def graph_query_amounts(captcha_queries, query_amounts): queries_and_amounts = zip(captcha_queries, query_amounts) queries_and_amounts = sorted(queries_and_amounts, key=lambda x:x[1], reverse=True) captcha_queries, query_amounts = zip(*queries_and_amounts) # colours = cm.Dark2(np.linspace(0,1,len(captcha_queries))) # legend_info = zip(query_numbers, colours) # random.shuffle(colours) # captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries] bars = plt.bar(left=range(len(query_amounts)), height=query_amounts) plt.xlabel('CAPTCHA queries.') plt.ylabel('Query frequencies.') plt.xticks([]) # plt.xticks(range(len(captcha_queries)), captcha_queries, rotation='vertical') # colours = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', ] patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))] plt.legend(handles=patches) for i, bar in enumerate(bars): bar.set_color(colours[i]) plt.show()
Example #3
Source File: PDS_Compute_MTF.py From PDS_Compute_MTF with BSD 3-Clause "New" or "Revised" License | 6 votes |
def compute_lsf(self): diff_esf = abs(self.esf[1:] - self.esf[0:(self.esf.shape[0] - 1)]) diff_esf = np.append(0, diff_esf) lsf = diff_esf diff_esf_smooth = abs(self.esf_smooth[0:(self.esf.shape[0] - 1)] - self.esf_smooth[1:]) diff_esf_smooth = np.append(0, diff_esf_smooth) lsf_smooth = diff_esf_smooth self.lsf = lsf self.lsf_smooth = lsf_smooth plt.subplot(2, 2, 3) plt.title("LSF Curve") plt.xlabel("pixel") plt.ylabel("DN Value") plt.plot(self.xesf, lsf, 'y-', self.xesf, lsf_smooth) yellow_patch = mpatches.Patch(color='yellow', label='Raw LSF') blue_patch = mpatches.Patch(color='blue', label='Smooth LSF') plt.legend(handles=[yellow_patch, blue_patch]) self.compute_mtf()
Example #4
Source File: data_class.py From MIDI-VAE with MIT License | 6 votes |
def draw_pianoroll(pianoroll, name='Notes', show=False, save_path=''): cm = matplotlib.cm.get_cmap('Greys') notes_color = cm(1.0) notes_patch = mpatches.Patch(color=notes_color, label=name) plt.figure(figsize=(20.0, 10.0)) plt.title('Pianoroll Pitch-plot of ' + name, fontsize=10) plt.legend(handles=[notes_patch], loc='upper right', prop={'size': 8}) plt.pcolor(pianoroll, cmap='Greys', vmin=0, vmax=np.max(pianoroll)) if show: plt.show() if len(save_path) > 0: plt.savefig(save_path) tikz_save(save_path + ".tex", encoding='utf-8', show_info=False) plt.close()
Example #5
Source File: spines.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def set_color(self, c): """ Set the edgecolor. Parameters ---------- c : color Notes ----- This method does not modify the facecolor (which defaults to "none"), unlike the `Patch.set_color` method defined in the parent class. Use `Patch.set_facecolor` to set the facecolor. """ self.set_edgecolor(c) self.stale = True
Example #6
Source File: lenslayoutfigure.py From ray-optics with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot(self): try: self.ax.cla() except AttributeError: self.ax = self.add_subplot(1, 1, 1, aspect=1.0) for p in self.artists: if isinstance(p, Line2D): self.ax.add_line(p) elif isinstance(p, Patch): self.ax.add_patch(p) else: self.ax.add_artist(p) self.scale_bounds(self.oversize_factor) self.draw_frame(self.do_draw_frame) self.ax.set_facecolor(backgrnd_color) self.canvas.draw() return self
Example #7
Source File: PDS_Compute_MTF.py From PDS_Compute_MTF with BSD 3-Clause "New" or "Revised" License | 6 votes |
def compute_mtf(self): mtf = np.absolute(np.fft.fft(self.lsf, 2048)) mtf_smooth = np.absolute(np.fft.fft(self.lsf_smooth, 2048)) mtf_final = np.fft.fftshift(mtf) mtf_final_smooth = np.fft.fftshift(mtf_smooth) plt.subplot(2, 2, 4) x_mtf_final = np.arange(0,1,1./127) mtf_final = mtf_final[1024:1151]/np.amax(mtf_final[1024:1151]) mtf_final_smooth = mtf_final_smooth[1024:1151]/np.amax(mtf_final_smooth[1024:1151]) plt.plot(x_mtf_final, mtf_final, 'y-', x_mtf_final, mtf_final_smooth) plt.xlabel("cycles/pixel") plt.ylabel("Modulation Factor") plt.title("MTF Curve") yellow_patch = mpatches.Patch(color='yellow', label='Raw MTF') blue_patch = mpatches.Patch(color='blue', label='Smooth MTF') plt.legend(handles=[yellow_patch, blue_patch]) plt.show() return mtf
Example #8
Source File: crystallographic_map.py From pyxem with GNU General Public License v3.0 | 6 votes |
def plot_phase_map(self, library, **kwargs): phase_map = self.get_phase_map() phase_name_index = get_phase_name_and_index(library) plt.figure() image = plt.imshow(phase_map) colors = [image.cmap(image.norm(value)) for value in phase_name_index.values()] patches = [ mpatches.Patch( color=colors[i], label="{l}".format(l=list(library.keys())[i]) ) for i in range(len(phase_name_index.keys())) ] plt.legend(handles=patches, bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.0) plt.xlabel("x axis (nm)") plt.ylabel("y axis (nm)") plt.xticks([]) plt.yticks([]) plt.title("Phase map") plt.tight_layout() plt.show()
Example #9
Source File: plotting_tools.py From RoboND-DeepLearning-Project with MIT License | 6 votes |
def train_val_curve(train_loss, val_loss=None): train_line = plt.plot(train_loss, label='train_loss') train_patch = mpatches.Patch(color='blue',label='train_loss') handles = [train_patch] if val_loss: val_line = plt.plot(val_loss, label='val_loss') val_patch = mpatches.Patch(color='orange',label='val_loss') handles.append(val_patch) plt.legend(handles=handles, loc=2) plt.title('training curves') plt.ylabel('loss') plt.xlabel('epochs') plt.show() # modified from the BaseLogger in file linked below # https://github.com/fchollet/keras/blob/master/keras/callbacks.py
Example #10
Source File: parse_svg.py From pylustrator with GNU General Public License v3.0 | 6 votes |
def plt_patch(node: minidom.Element, trans_parent_trans: mtransforms.Transform, style: dict, constructor: callable, ids: dict, no_draw: bool = False) -> mpatches.Patch: """ add a node to the figure by calling the provided constructor """ trans_node = parseTransformation(node.getAttribute("transform")) style = get_inline_style(node, get_css_style(node, ids["css"], style)) patch = constructor(node, trans_node + trans_parent_trans + plt.gca().transData, style, ids) if not isinstance(patch, list): patch = [patch] for p in patch: if not getattr(p, "is_marker", False): style = apply_style(style, p) p.style = style #p.set_transform(p.get_transform() + plt.gca().transData) p.trans_parent = trans_parent_trans p.trans_node = parseTransformation(node.getAttribute("transform")) if not no_draw and not styleNoDisplay(style): plt.gca().add_patch(p) if node.getAttribute("id") != "": ids[node.getAttribute("id")] = patch return patch
Example #11
Source File: cat_mouse.py From Projects with MIT License | 6 votes |
def state(self): img = np.copy(self.world[self.sight_range:self.world.shape[0]-self.sight_range,self.sight_range:self.world.shape[0]-self.sight_range]) img[img==0] = 256 img[img==1] = 215 img[img==2] = 123 img[img==3] = 175 img[img==9] = 1 p = plt.imshow(img, interpolation='nearest', cmap='nipy_spectral') fig = plt.gcf() c1 = mpatches.Patch(color='red', label='cats') c2 = mpatches.Patch(color='green', label='mice') c3 = mpatches.Patch(color='yellow', label='cheese') plt.legend(handles=[c1,c2,c3],loc='center left',bbox_to_anchor=(1, 0.5)) #plt.savefig("cat_mouse%i.png" % self.gif, bbox_inches='tight') #self.gif += 1 plt.pause(0.1) # Run algorithm
Example #12
Source File: graphs.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 6 votes |
def add_legend_patch(self, legend_rows, fontsize=None): if matplotlib.__version__ == '3.0.2': self.logger.warning('skipping legend patch with matplotlib v3.0.2 for compatibility') return if self._legend is not None: self._legend.remove() self._legend = None fontsize = fontsize or self.fontsize_scale legend_bbox = self.figure.legend( tuple(patches.Patch(color=patch_color) for patch_color, _ in legend_rows), tuple(label for _, label in legend_rows), borderaxespad=1.25, fontsize=fontsize, frameon=True, handlelength=1.5, handletextpad=0.75, labelspacing=0.3, loc='lower right' ) legend_bbox.legendPatch.set_linewidth(0) self._legend = legend_bbox
Example #13
Source File: _pick_info.py From mplcursors with MIT License | 6 votes |
def _register_scatter(): """ Patch `PathCollection` and `scatter` to register their return values. This registration allows us to distinguish `PathCollection`s created by `Axes.scatter`, which should use point-like picking, from others, which should use path-like picking. The former is more common, so we store the latter instead; this also lets us guess the type better if this module is imported late. """ @functools.wraps(PathCollection.__init__) def __init__(self, *args, **kwargs): _nonscatter_pathcollections.add(self) return __init__.__wrapped__(self, *args, **kwargs) PathCollection.__init__ = __init__ @functools.wraps(Axes.scatter) def scatter(*args, **kwargs): paths = scatter.__wrapped__(*args, **kwargs) with suppress(KeyError): _nonscatter_pathcollections.remove(paths) return paths Axes.scatter = scatter
Example #14
Source File: generate_plots.py From hand_eye_calibration with BSD 3-Clause "New" or "Revised" License | 5 votes |
def generate_time_plot(methods, datasets, runtimes_per_method, colors): num_methods = len(methods) num_datasets = len(datasets) x_ticks = np.linspace(0., 1., num_methods) width = 0.6 / num_methods / num_datasets spacing = 0.4 / num_methods / num_datasets fig, ax1 = plt.subplots() ax1.set_ylabel('Time [s]', color='b') ax1.tick_params('y', colors='b') ax1.set_yscale('log') fig.suptitle("Hand-Eye Calibration Method Timings", fontsize='24') handles = [] for i, dataset in enumerate(datasets): runtimes = [runtimes_per_method[dataset][method] for method in methods] bp = ax1.boxplot( runtimes, 0, '', positions=(x_ticks + (i - num_datasets / 2. + 0.5) * spacing * 2), widths=width) plt.setp(bp['boxes'], color=colors[i], linewidth=line_width) plt.setp(bp['whiskers'], color=colors[i], linewidth=line_width) plt.setp(bp['fliers'], color=colors[i], marker='+', linewidth=line_width) plt.setp(bp['medians'], color=colors[i], marker='+', linewidth=line_width) plt.setp(bp['caps'], color=colors[i], linewidth=line_width) handles.append(mpatches.Patch(color=colors[i], label=dataset)) plt.legend(handles=handles, loc=2) plt.xticks(x_ticks, methods) plt.xlim(x_ticks[0] - 2.5 * spacing * num_datasets, x_ticks[-1] + 2.5 * spacing * num_datasets) plt.show()
Example #15
Source File: data_class.py From MIDI-VAE with MIT License | 5 votes |
def draw_difference_pianoroll(original, predicted, name_1='Original', name_2='Predicted', show=False, save_path=''): if original.shape!=predicted.shape: print("Shape mismatch. Not drawing a plot.") return draw_matrix = original + 2 * predicted cm = colors.ListedColormap(['white', 'blue', 'red', 'black']) bounds=[0,1,2,3,4] n = colors.BoundaryNorm(bounds, cm.N) original_color = cm(1/3) predicted_color = cm(2/3) both_color = cm(1.0) original_patch = mpatches.Patch(color=original_color, label=name_1) predicted_patch = mpatches.Patch(color=predicted_color, label=name_2) both_patch = mpatches.Patch(color=both_color, label='Notes in both songs') plt.figure(figsize=(20.0, 10.0)) plt.title('Difference-Pitch-plot of ' + name_1 + ' and ' + name_2, fontsize=10) plt.legend(handles=[original_patch, predicted_patch, both_patch], loc='upper right', prop={'size': 8}) plt.pcolor(draw_matrix, cmap=cm, vmin=0, vmax=3, norm=n) if show: plt.show() if len(save_path) > 0: plt.savefig(save_path) tikz_save(save_path + ".tex", encoding='utf-8', show_info=False) plt.close()
Example #16
Source File: legend.py From ImageFusion with MIT License | 5 votes |
def get_patches(self): 'return a list of patch instances in the legend' return silent_list('Patch', [h for h in self.legendHandles if isinstance(h, Patch)])
Example #17
Source File: reports.py From clusterman with Apache License 2.0 | 5 votes |
def _make_legend(fig, heatmap_range, has_errors, legend_formatter): cmap = get_cmap(COLORMAP) low, high = cmap(0.0), cmap(1.0) low_marker = _make_heatmap_legend_marker(low, 'min (p5): ' + legend_formatter(heatmap_range[0])) high_marker = _make_heatmap_legend_marker(high, 'max (p95): ' + legend_formatter(heatmap_range[1])) handles = [low_marker, high_marker] if has_errors: error_marker = _make_heatmap_legend_marker(ERROR_COLOR, 'exceeds threshold') handles.append(error_marker) fig.legend(handles=handles, loc='upper left', fontsize=6) trend_line = Line2D([0, 1], [0, 0], color=TREND_LINE_COLOR, label='average') bestfit_line = Line2D([0, 1], [0, 0], color='black', dashes=(1, 1), linewidth=0.75, label='best fit line') trend_patch = Patch(color=TREND_RANGE_COLOR, alpha=TREND_RANGE_ALPHA, label='interquartile range', linewidth=0) fig.legend(handles=[trend_line, bestfit_line, trend_patch], loc='upper right', fontsize=6)
Example #18
Source File: violin.py From scikit-criteria with BSD 3-Clause "New" or "Revised" License | 5 votes |
def violin_plot( mtx, criteria, weights, anames, cnames, show_legend=False, cmap=None, ax=None, subplots_kwargs=None, violin_kwargs=None): # create ax if necesary if ax is None: subplots_kwargs = subplots_kwargs or {} subplots_kwargs.setdefault("figsize", (9, 6)) ax = plt.subplots(**subplots_kwargs)[-1] # violinplot violin_kwargs = violin_kwargs or {} vp = ax.violinplot(mtx, **violin_kwargs) # colors in boxes colors = cmap(np.linspace(0, 1, mtx.shape[1])) legends_patchs = [] for violin, color, cname in zip(vp['bodies'], colors, cnames): violin.set_facecolor(color) legend_patch = patches.Patch(color=color, label=cname) legends_patchs.append(legend_patch) if show_legend: ax.legend(loc="best", handles=legends_patchs) # ticks ax.set_xticks(np.arange(1, len(cnames) + 1)) ax.set_xticklabels(cnames, rotation=10, size="small") ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) return ax
Example #19
Source File: box.py From scikit-criteria with BSD 3-Clause "New" or "Revised" License | 5 votes |
def box_plot( mtx, criteria, weights, anames, cnames, show_legend=False, cmap=None, ax=None, subplots_kwargs=None, box_kwargs=None): # create ax if necesary if ax is None: subplots_kwargs = subplots_kwargs or {} subplots_kwargs.setdefault("figsize", (9, 6)) ax = plt.subplots(**subplots_kwargs)[-1] # boxplot box_kwargs = box_kwargs or {} box_kwargs.setdefault("notch", False) box_kwargs.setdefault("vert", True) box_kwargs.setdefault("patch_artist", True) box_kwargs.setdefault("sym", "o") box_kwargs.setdefault("flierprops", {'linestyle': 'none', 'marker': 'o', 'markerfacecolor': 'red'}) bp = ax.boxplot(mtx, **box_kwargs) # colors in boxes colors = cmap(np.linspace(0, 1, mtx.shape[1])) legends_patchs = [] for box, color, cname in zip(bp['boxes'], colors, cnames): box.set_facecolor(color) legend_patch = patches.Patch(color=color, label=cname) legends_patchs.append(legend_patch) if show_legend: ax.legend(loc="best", handles=legends_patchs) # ticks ax.set_xticklabels(cnames, rotation=10, size="small") ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) return ax
Example #20
Source File: Results.py From MicroGrids with European Union Public License 1.1 | 5 votes |
def Energy_Participation(Energy_Flow): Energy_Participation = {'Energy PV':0, 'Energy Diesel':0, 'Discharge energy from the Battery':0, 'Lost Load':0} c = {'Energy Diesel':'Diesel Generator', 'Discharge energy from the Battery':'Battery', 'Energy PV':'From PV', 'Lost Load':'Lost Load'} labels=[] for v in Energy_Participation.keys(): if Energy_Flow[v]/Energy_Flow['Energy_Demand'] >= 0.001: Energy_Participation[v] = Energy_Flow[v]/Energy_Flow['Energy_Demand'] labels.append(c[v]) else: del Energy_Participation[v] Colors=['r','c','b','k'] plt.figure() plt.pie(Energy_Participation.values(), autopct='%1.1f%%', colors=Colors) Handles = [] for t in range(len(labels)): Handles.append(mpatches.Patch(color=Colors[t], alpha=1, label=labels[t])) plt.legend(handles=Handles, bbox_to_anchor=(1.4, 1)) plt.savefig('Results/Energy_Participation.png', bbox_inches='tight') plt.show() return Energy_Participation
Example #21
Source File: gd_algorithms_visualization.py From neupy with MIT License | 5 votes |
def draw_quiver(network_class, name, color='r'): """ Train algorithm and draw quiver for every epoch update for this algorithm. """ global weights global current_epoch bpn = network_class(create_network(), signals=save_epoch_weight) # We don't know in advance number of epochs that network # need to reach the goal. For this reason we use 1000 as # an upper limit for all network epochs, later we # need to fix weights = np.zeros((2, 1000)) weights[:, 0:1] = default_weight.copy() current_epoch = 0 while bpn.score(X_train, y_train) > 0.125: bpn.train(X_train, y_train, epochs=1) current_epoch += 1 weights = weights[:, :current_epoch + 1] weight_quiver(weights, color=color) label = "{name} ({n} steps)".format(name=name, n=current_epoch) return mpatches.Patch(color=color, label=label)
Example #22
Source File: legend.py From coffeegrindsize with MIT License | 5 votes |
def get_patches(self): 'Return a list of `~.patches.Patch` instances in the legend.' return silent_list('Patch', [h for h in self.legendHandles if isinstance(h, Patch)])
Example #23
Source File: cross_section.py From section-properties with MIT License | 5 votes |
def plot_mesh(self, nodes, elements, element_list, materials): """Watered down implementation of the CrossSection method to plot the finite element mesh, showing material properties.""" (fig, ax) = plt.subplots() post.setup_plot(ax, True) # plot the mesh ax.triplot(nodes[:, 0], nodes[:, 1], elements[:, 0:3], lw=0.5, color='black') color_array = [] legend_list = [] if materials is not None: # create an array of finite element colours for el in element_list: color_array.append(el.material.color) # create a list of unique material legend entries for (i, mat) in enumerate(materials): # if the material has not be entered yet if i == 0 or mat not in materials[0:i]: # add the material colour and name to the legend list legend_list.append(mpatches.Patch(color=mat.color, label=mat.name)) cmap = ListedColormap(color_array) # custom colormap c = np.arange(len(color_array)) # indicies of elements # plot the mesh colours ax.tripcolor(nodes[:, 0], nodes[:, 1], elements[:, 0:3], c, cmap=cmap) # display the legend ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), handles=legend_list) # finish the plot post.finish_plot(ax, True, title='Finite Element Mesh')
Example #24
Source File: plot_alpha_vectors.py From POMDPy with MIT License | 5 votes |
def plot_alpha_vectors(title, gamma, n_actions): """ Plot the current set of alpha vectors over the belief simplex :return: """ fig = plt.figure() plt.title(title) pts = 30 x = np.linspace(0., 1., num=pts) # y = np.linspace(0., 1., num=pts) # Z = np.zeros(shape=(pts, pts)) # X, Y = np.meshgrid(x, y) y = np.zeros(shape=pts) cmap = get_cmap(n_actions * 10) patches, patches_handles = [], [] for i in range(n_actions): patches.append(cmap(i * 10)) patches_handles.append(mpatches.Patch(color=patches[i], label='action {}'.format(i))) for av in gamma: for i in range(pts): # for j in range(pts): y[i] = np.dot(av.v, np.array([x[i], 1. - x[i]])) plt.plot(x, y, color=patches[av.action], linewidth=2) plt.xlabel('p1') plt.legend(handles=patches_handles) plt.show()
Example #25
Source File: legend.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_patches(self): 'Return a list of `~.patches.Patch` instances in the legend.' return silent_list('Patch', [h for h in self.legendHandles if isinstance(h, Patch)])
Example #26
Source File: interactivefigure.py From ray-optics with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot(self): """Draw the actual figure.""" try: self.ax.cla() except AttributeError: self.ax = self.add_subplot(1, 1, 1, aspect=self.aspect) for a in self.artists: a.set_picker(5) if isinstance(a, lines.Line2D): self.ax.add_line(a) elif isinstance(a, patches.Patch): self.ax.add_patch(a) else: self.ax.add_artist(a) if self.do_scale_bounds: self.view_bbox = util.scale_bounds(self.sys_bbox, self.oversize_factor) self.ax.set_aspect(self.aspect, adjustable='datalim') self.update_axis_limits(bbox=self.view_bbox) self.draw_frame(self.do_draw_frame) self.ax.set_facecolor(self._rgb['background1']) self.draw_axes(self.do_draw_axes) self.connect_events() self.canvas.draw_idle() return self
Example #27
Source File: legend.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def get_patches(self): 'Return a list of `~.patches.Patch` instances in the legend.' return silent_list('Patch', [h for h in self.legendHandles if isinstance(h, Patch)])
Example #28
Source File: visual_callbacks.py From keras-visuals with MIT License | 5 votes |
def on_epoch_end(self, epoch, logs={}): self.epoch_count += 1 self.val_acc.append(logs.get('val_acc')) self.acc.append(logs.get('acc')) self.loss.append(logs.get('loss')) self.val_loss.append(logs.get('val_loss')) epochs = [x for x in range(self.epoch_count)] count_subplots = 0 if 'acc' in self.graphs: count_subplots += 1 plt.subplot(self.num_subplots, 1, count_subplots) plt.title('Accuracy') #plt.axis([0,100,0,1]) plt.plot(epochs, self.val_acc, color='r') plt.plot(epochs, self.acc, color='b') plt.ylabel('accuracy') red_patch = mpatches.Patch(color='red', label='Test') blue_patch = mpatches.Patch(color='blue', label='Train') plt.legend(handles=[red_patch, blue_patch], loc=4) if 'loss' in self.graphs: count_subplots += 1 plt.subplot(self.num_subplots, 1, count_subplots) plt.title('Loss') #plt.axis([0,100,0,5]) plt.plot(epochs, self.val_loss, color='r') plt.plot(epochs, self.loss, color='b') plt.ylabel('loss') red_patch = mpatches.Patch(color='red', label='Test') blue_patch = mpatches.Patch(color='blue', label='Train') plt.legend(handles=[red_patch, blue_patch], loc=4) plt.draw() plt.pause(0.001)
Example #29
Source File: plot_results.py From nasbench-1shot1 with Apache License 2.0 | 5 votes |
def plot_correlation_between_epochs(metric_dict, title, xlabel, ylabel, foldername, x_log, y_log, smoothing=False, filename=None, max_iter=None, start=0): config_markerstyle = ['*', 'o', '-'] plt.figure(figsize=(6, 2)) for metric_idx, (config, values) in enumerate(metric_dict.items()): for epoch_idx, (epoch, val) in enumerate(values.items()): if epoch_idx == 0: label = config else: label = None plt.plot(np.arange(5, 50, 10), val, label=label, marker=config_markerstyle[metric_idx], color=plt.cm.magma(epoch_idx / len(values))) ax = plt.gca() plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Create legend for the optimizer # plt.legend(loc=1) # Create legend for the fidelity epoch_color_path_legend = [mpatches.Patch(color=plt.cm.magma(epoch_idx / len(values)), label=epoch) for epoch_idx, epoch in enumerate(['4 epochs', '12 epochs', '36 epochs', '108 epochs'])] # plt.legend(handles=epoch_color_path_legend, loc=2) plt.grid(True, which="both", ls="-", alpha=0.5) plt.tight_layout() folder_path = os.path.join(os.getcwd(), foldername) os.makedirs(folder_path, exist_ok=True) filepath = os.path.join(folder_path, '{}.pdf'.format(filename)), plt.savefig(filepath[0]) plt.close()
Example #30
Source File: embedding.py From agnez with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_legend(palette, labels): handles = [] for c, l in zip(palette, np.unique(labels)): patch = mpatches.Patch(color=c, label=l) handles.append(patch) return handles