我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用matplotlib.patches.Patch()。
def plot_build_time_composition_graph(parseTimes, hashTimes, compileTimes, diffToBuildTime): # times in s fig, ax = plt.subplots() ax.stackplot(np.arange(1, len(parseTimes)+1), # x axis # [parseTimes, hashTimes, compileTimes, diffToBuildTime], [[i/60 for i in parseTimes], [i/60 for i in hashTimes], [i/60 for i in compileTimes], [i/60 for i in diffToBuildTime]], colors=[parseColor,hashColor,compileColor,remainColor], edgecolor='none') plt.xlim(1,len(parseTimes)) plt.xlabel('commits') plt.ylabel('time [min]') lgd = ax.legend([mpatches.Patch(color=remainColor), mpatches.Patch(color=compileColor), mpatches.Patch(color=hashColor), mpatches.Patch(color=parseColor)], ['remaining build time','compile time', 'hash time', 'parse time'], loc='center left', bbox_to_anchor=(1, 0.5)) fig.savefig(abs_path(BUILD_TIME_COMPOSITION_FILENAME), bbox_extra_artists=(lgd,), bbox_inches='tight') print_avg(parseTimes, 'parse') print_avg(hashTimes, 'hash') print_avg(compileTimes, 'compile') print_avg(diffToBuildTime, 'remainder')
def plot_build_time_composition_graph(parse_times, hash_times, compile_times, diff_to_build_time): # times in ns fig, ax = plt.subplots() #[i/1e6 for i in parse_times], ax.stackplot(np.arange(1, len(parse_times)+1), # x axis [[i/1e6 for i in parse_times], [i/1e6 for i in hash_times],[i/1e6 for i in compile_times], # ns to ms #diff_to_build_time ], colors=[parse_color,hash_color,compile_color, # remain_color ], edgecolor='none') plt.xlim(1,len(parse_times)) plt.xlabel('commits') plt.ylabel('time [ms]') ax.set_yscale('log') lgd = ax.legend([#mpatches.Patch(color=remain_color), mpatches.Patch(color=compile_color), mpatches.Patch(color=hash_color), mpatches.Patch(color=parse_color)], [#'remaining build time', 'compile time', 'hash time', 'parse time'], loc='center left', bbox_to_anchor=(1, 0.5)) fig.savefig(abs_path(BUILD_TIME_FILENAME), bbox_extra_artists=(lgd,), bbox_inches='tight') ################################################################################
def plot(self, ylim=None): import matplotlib.patches as mpatches import matplotlib.pyplot as plt from pylab import subplot number_of_subplots=len(self.scores.keys()) colors = ['blue', 'green', 'orange'] patches = [] for plot_idx, metric in enumerate(self.scores): for i, set_name in enumerate(self.scores[metric].keys()): data = self.scores[metric][set_name][0] time = self.scores[metric][set_name][1] patches.append(mpatches.Patch(color=colors[i], label='{0} {1}'.format(set_name, metric))) ax1 = subplot(number_of_subplots,1,plot_idx+1) ax1.plot(time,data, label='{0}'.format(metric), color=colors[i]) if ylim != None: plt.ylim(ymin=ylim[0]) plt.ylim(ymax=ylim[1]) plt.xlabel('iter') plt.ylabel('{0} {1}'.format(set_name, metric)) ax1.legend(handles=patches) plt.show()
def plot_feature_importances(forest, patch_name_nfeatures, layer_name): importances = forest.feature_importances_ n_features = len(importances) plt.figure() plt.title("Feature importances (layer %s)" % str(layer_name)) bar_list = plt.bar(range(n_features), importances, color="r", align="center") if n_features < 50: plt.xticks(range(n_features), range(n_features)) plt.xlim([-1, n_features]) PATCH_COLORS = ["orangered", "orange", "green", "purple", "cyan", "blue", "red", "yellow"] bar_id = 0 patches = list() for i, (patch_name, n_bars) in enumerate(patch_name_nfeatures): patches.append(mpatches.Patch(color=PATCH_COLORS[i], label=patch_name)) for b in range(n_bars): bar_list[bar_id].set_color(PATCH_COLORS[i]) bar_id += 1 plt.legend(handles = patches)
def plot_glcf_labelmap(labels, ax=None): import pylab as pl if ax is None: ax = pl.subplot(111) vimg = glcf_to_rgb(labels) vimg[labels.mask] = (0, 0, 0) ax.imshow(vimg, interpolation='nearest') lgd_patches = [] for glcf_type in sorted(np.unique(labels)): if glcf_type is ma.masked: continue lgd_patches.append( mpatches.Patch( color=np.array(CMAP[glcf_type]) / 255., label=CLASSES_NAMES[glcf_type] ) ) ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), handles=lgd_patches)
def draw_matplot_graph(unit_supplies, replay): units = sorted(list(unit_supplies.keys())) y = NP.row_stack([ unit_supplies[i] for i in units ]) # this call to 'cumsum' (cumulative sum), passing in your y data, # is necessary to avoid having to manually order the datasets x = times y_stack = NP.cumsum(y, axis=0) # a 3x10 array fig = PLT.figure() ax1 = fig.add_subplot(111) patches = [] ax1.fill_between(x, 0, y_stack[0,:], facecolor="#CC6666", alpha=.7) patches.append(mpatches.Patch(color="#CC6666", label=units[0], alpha=.7)) for index, key in enumerate(units[1:]): color = "#" + hashlib.sha224(bytes(key, 'utf-8')).hexdigest()[:6] patches.append(mpatches.Patch(color=color, label=key, alpha=.7)) ax1.fill_between(x, y_stack[index,:], y_stack[index+1,:], facecolor=color, alpha=.7) PLT.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0., handles=patches) PLT.show()
def plot_masks(cropped_image_path, prediction_map, output_image_path): fig = plt.figure("segments") ax = fig.add_subplot(1, 1, 1) image_draw = io.imread(cropped_image_path) segparams = SegParams() feature_mapping = segparams.feature_palette() classes = segparams.feature_classes() legend_patches = [] for i in feature_mapping.keys(): if i in prediction_map: temp_inds = np.where(prediction_map != i) temp_map = prediction_map.copy() temp_map[temp_inds] = 0 image_draw = mark_boundaries( image_draw, temp_map, mode='inner', color=feature_mapping[i]) # outline_color=feature_mapping[i]) legend_patches.append(mpatches.Patch( color=(feature_mapping[i][0], feature_mapping[i][1], feature_mapping[i][2], 1), label=classes[i])) ax.imshow(image_draw) lgd = ax.legend(handles=legend_patches, loc="upper left", bbox_to_anchor=(1, 1)) plt.axis("off") plt.savefig(output_image_path.strip('.jpg') + '_segmented.png', bbox_extra_artists=( lgd,), bbox_inches='tight') plt.show()
def initAxes(optimizers): interval = functionClass.interval fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = np.arange(interval[0][0], interval[0][1], 0.05) y = np.arange(interval[1][0], interval[1][1], 0.05) X, Y = np.meshgrid(x, y) Z = functionClass.getZMeshGrid(X, Y) ax.plot_surface(X, Y, Z, cmap=cm.coolwarm) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') ax.view_init(elev=functionClass.camera[0], azim=functionClass.camera[1]) plt.legend( handles=[mpatches.Patch(color=optimizersColorLookup[optimizer.name], label=optimizer.name) for optimizer in optimizers]) return fig, ax # may be list or array
def plot_positions(df, img_path, frame, cam): color_dict = {'car': '#fc8d59', 'bus': '#ffffbf', 'person': '#91cf60'} frame_pos = df[(df['frame'] == frame) & (df['cam'] == cam)] fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') im = plt.imread(img_path) ax.imshow(im) for i, f in frame_pos.iterrows(): add_rect(ax, f['x'], f['y'], f['w'], f['h'], color=color_dict[f['class_name']], name=f['id']) legend_handles = [] for k, v in color_dict.iteritems(): handle = patches.Patch(color=v, label=k) legend_handles.append(handle) plt.legend(loc=0, handles=legend_handles) plt.xlim((0, 360)) plt.ylim((0, 288)) plt.ylim(plt.ylim()[::-1]) plt.tight_layout() plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off') plt.show()
def scatter(x, y, color, **kwargs): plt.scatter(x, y, color = color, s=5) plt.title(kwargs['title']) legends = [] col_dict = get_color_list() for x in col_dict: legends.append(mpatches.Patch(color=col_dict[x],label=x)) plt.legend(handles=legends) plt.show()
def save_test1_fig(name): with open("test1/{}.pkl".format(name), "rb") as f: results = pickle.load(f) fps, acc, var = [], [], [] for r in results: fps.append(r["fps"]) acc.append(r["accuracy"]) var.append(r["config"][name]) plt.hold(True) plt.plot(var, fps, color="blue") plt.plot(var, acc, color="red") plt.legend(handles=[ ptc.Patch(color='blue', label='FPS'), ptc.Patch(color='red', label='Accuracy') ]) plt.xlabel(name) plt.savefig("test1/{}.png".format(name)) plt.hold(False) plt.close()
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()
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)
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
def display_optimization(): pred_datas, real_datas = load_dataset_all('2016_2_8.xls') weights, biases = load_model('opt_model_paras') weights1 = np.matrix(weights[0]) weights2 = np.matrix(weights[1]) weights3 = np.matrix(weights[2]) biases1 = np.matrix(biases[0]) biases2 = np.matrix(biases[1]) biases3 = np.matrix(biases[2]) layer1 = sigmoid(pred_datas * weights1 + biases1) layer2 = sigmoid(layer1 * weights2 + biases2) result = layer2 * weights3 + biases3 plt.title('Improved Temperature in 2016') plt.xlabel('date') plt.ylabel('temperature') plt.plot(result, 'g', linewidth=1.5) plt.plot(real_datas, 'r', linewidth=1.5) red_patch = mpatches.Patch(color='red', label='real') green_patch = mpatches.Patch(color='green', label='pred') plt.legend(handles=[red_patch, green_patch]) plt.show()
def create_legend(self): voltage_sort = [] permittivity_sort = [] for voltage, color in zip(self.voltages, self.conductor_patch_colors): if voltage not in voltage_sort: legend_artist = patches.Patch(color=color, label=voltage) self.conductor_legend_handles.append(legend_artist) voltage_sort.append(voltage) for permittivity, color in zip(self.permittivities, self.dielectric_patch_colors): if permittivity not in permittivity_sort: legend_artist = patches.Patch(color=color, label=permittivity, hatch='//') self.dielectric_legend_handles.append(legend_artist) permittivity_sort.append(permittivity) self.conductor_legend_handles = [j for (i, j) in sorted(zip(voltage_sort, self.conductor_legend_handles))] self.dielectric_legend_handles = [j for (i, j) in sorted(zip(permittivity_sort, self.dielectric_legend_handles))]
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
def main(): print("Start sim") parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('settings', help='Location of the settings yaml file for the desired simulation') args = parser.parse_args() with open(args.settings, 'r') as stream: settings = yaml.load(stream) n_bandits = settings['n_bandits'] n_runs = settings['n_runs'] n_plays_per_run = settings['n_plays_per_run'] patches = [] for experiment in settings['experiments']: print(experiment) simulation = Sim(n_runs, n_plays_per_run, lambda _: eval(experiment['env_class'])(n_bandits, options=experiment['env_options']), lambda actions: eval(experiment['agent_class'])(actions, options=experiment['options'])) simulation.run() simulation.plot(experiment['color'], experiment['label']) patches.append(mpatches.Patch(color=experiment['color'], label=experiment['label'])) plt.axis([0,n_plays_per_run,0,1.05]) plt.title("NBandits Reinforcement") plt.plot([0,n_plays_per_run],[0.9, 0.9], '--', color='g') plt.plot([0,n_plays_per_run],[0.95, 0.95], '--', color='b') plt.legend(handles=patches) plt.savefig('images/n_bandits_solutions.png') # plt.show()
def plot_ppvs(train_ppvs, validation_ppvs, filepath): plt.plot(train_ppvs, color="blue") plt.plot(validation_ppvs, color="tomato") patches = list() patches.append(mpatches.Patch(color="blue", label="Training PPV")) patches.append(mpatches.Patch(color="tomato", label="Validation PPV")) plt.legend(handles=patches) plt.ylim([0, 1])
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)
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()
def draw_legend(self): handls = [] labls = [] pos = "lower right" for i, plotdata_file in enumerate(self.plotdata_files): handls.append(mpatches.Patch(color=self.COLORS_ACTIVE[i])) labls.append("%d: %s" % (i, plotdata_file)) self.figure.legend( handls, labls, pos, fontsize="xx-small" )
def plot_legend_with_list_of_dicts_with_name_and_df(self,dicts): legend_handles = [] for i in range(len(dicts)): name = dicts[i]['name'] patch = mpatches.Patch(color=self.colors[i], label=name) legend_handles.append(patch) plt.legend(handles=legend_handles)
def apply_overlay(image, overlay, path, label=''): """ Overlay overlay onto image and add label as text and save to path (full path with extension!) """ fig = plt.figure(frameon=False) plt.imshow(image, interpolation='none') plt.imshow(overlay, cmap='plasma', alpha=0.7, interpolation='none') if label != '': red_patch = mpatches.Patch(color='yellow', label=label) plt.legend(handles=[red_patch]) fig.savefig(path) plt.close(fig)
def build_map_nmf(df_map, m, coords, info, title, CrimePatterns): # plt.clf() fig = plt.figure() ax = fig.add_subplot(111, axisbg='w', frame_on=True) # draw wards with grey outlines norm = Normalize() for i in xrange(5): color = colormaps[i] cmap = plt.get_cmap(color) pc = PatchCollection(df_map[df_map['class'] == i+1]['patches'], match_original=True, alpha=0.8) pc.set_facecolor(cmap(norm(df_map.loc[(df_map['class'] == i+1), i].values))) ax.add_collection(pc) pc = PatchCollection(df_map[df_map['class'] == 0]['patches'], match_original=True, alpha=0.2) pc.set_facecolor('grey') ax.add_collection(pc) x, y = m(coords[0] + 0.02, coords[1] + 1.0) details = plt.annotate(info, xy=(x, y), size=24, color='#555555') # Draw a map scale m.drawmapscale( coords[0] + 0.2, coords[1] + 0.95, coords[0], coords[1], 20., fontsize=8, barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', units='mi', zorder=5) legend_patches = [] for i in range(6): legend_patches.append(mpatches.Patch(color=colors[i], label=CrimePatterns[i])) plt.legend(handles=legend_patches, loc='lower right') x1, y1 = m(coords[0] + 0.05, 33.62) colorinfo = 'Color represent each cluster of community;\nBrightness represent the severities of crime in each community' plt.annotate(colorinfo, xy=(x1, y1), size=16, color='#555555') plt.tight_layout() fig.set_size_inches(12, 13) plt.savefig(title, dpi=300, alpha=True)
def draw_flows(self): minimal_timestamp = float(self.memory.get_minimal_timestamp()) ytick_labels = [] yticks = [] fig = plt.figure() fig.suptitle( self.client_ip + " on " + self.pcap_path[self.pcap_path.rfind("\\\\") + 2:]) ax = fig.add_subplot(111) for i, (four_tuple, flow) in enumerate(self.memory.items()): ax.plot(np.array([float(t) - minimal_timestamp for t in (flow.start_time, flow.end_time)]), np.array([i * 3] * 2), 'k') ax.plot(np.array([float(pkt.sniff_timestamp) - minimal_timestamp for pkt in flow]), np.array([i * 3] * len(flow)), 'bo', color=self.get_color(flow.client.port), picker=True)[ 0].set_gid( flow) ytick_labels.append(str(flow.server)) yticks.append(i * 3) ax.set_yticks(yticks) ax.set_yticklabels(ytick_labels) ax.set_xlabel("Seconds since beginning of capture") ax.set_ylabel("External IP:Port") plt.legend(title='Internal Port', handles=[mpatches.Patch(color=color, label=src_port) for src_port, color in self.colors.items()]) def onpick(event): print(event.artist.get_gid()) fig.canvas.mpl_connect("pick_event", onpick) plt.show()
def _update_colors(self, color_spec): """ Takes a sequence of 4 color tuples, builds the color maps, if the plot data isn't none will modify the plot colors """ self._colors = color_spec self._color_maps = [visualizer_colors.PMIColormap("PMIFriend", color_spec[0]), visualizer_colors.PMIColormap("PMITryst", color_spec[1]), visualizer_colors.PMIColormap("PMIHeadToHead", color_spec[2]), visualizer_colors.PMIColormap("PMIArmsRace", color_spec[3])] self.color_mappers = [cm.ScalarMappable(norm=self._normalizer, cmap=self._color_maps[0]), cm.ScalarMappable(norm=self._normalizer, cmap=self._color_maps[1]), cm.ScalarMappable(norm=self._normalizer, cmap=self._color_maps[2]), cm.ScalarMappable(norm=self._normalizer, cmap=self._color_maps[3])] self.color_samples = dict() self._legend_proxies = [] for mapper, name in zip(self.color_mappers, self.data.relation_types): rgba = mapper.to_rgba(0.7, bytes=True) self.color_samples[name] = rgba self._legend_proxies.append(mpatches.Patch(color=[i/255 for i in rgba], label=name)) self._on_color_changed() self._mpl.redraw()
def __plotFrame(self, data): values = np.unique(data.ravel()) im = plt.imshow(data, interpolation='none') colors = [im.cmap(im.norm(value)) for value in values] patches = [mpatches.Patch(color=colors[i], label="Level {l}".format(l=values[i])) for i in range(len(values))] plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0. ) plt.show()
def __plotFrame(self, data, legend=False): values = np.unique(data.ravel()) im = plt.imshow(data, interpolation='none') colors = [im.cmap(im.norm(value)) for value in values] patches = [mpatches.Patch(color=colors[i], label="Level {l}".format(l=values[i])) for i in range(len(values))] if legend: plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0. ) plt.show() if self.setLivePlot: plt.pause(0.1)
def display_all(): datas = load_dataset_incol('2016_2_8.xls') plt.title('Temperature in 2016') plt.xlabel('date') plt.ylabel('temperature') plt.plot(datas[0], 'b') plt.plot(datas[2], 'm') plt.plot(datas[6], 'g') plt.plot(datas[7], 'r') blue_patch = mpatches.Patch(color='blue', label='pred2') yellow_patch = mpatches.Patch(color='magenta', label='pred4') green_patch = mpatches.Patch(color='green', label='pred8') red_patch = mpatches.Patch(color='red', label='real') plt.legend(handles=[blue_patch, yellow_patch, green_patch, red_patch]) plt.show()
def display_detail(): datas = load_dataset_incol('2016_2_8.xls') # plt.title('Temperature') plt.subplot(4, 1, 1) # plt.xlabel('2 days') plt.ylabel('temperature') plt.plot(datas[7][247:250], color='r', linewidth=2) plt.scatter(2, datas[0][249], s=60, color='b') blue_patch = mpatches.Patch(color='blue', label='2-day pred') red_patch = mpatches.Patch(color='red', label='real') plt.legend(handles=[blue_patch, red_patch], loc=2) plt.subplot(4, 1, 2) # plt.xlabel('4 days') plt.ylabel('temperature') plt.plot(datas[7][245:250], color='r', linewidth=2) plt.scatter(4, datas[2][249], s=60, color='m') magenta_patch = mpatches.Patch(color='magenta', label='4-day pred') red_patch = mpatches.Patch(color='red', label='real') plt.legend(handles=[magenta_patch, red_patch], loc=2) plt.subplot(4, 1, 3) # plt.xlabel('6 days') plt.ylabel('temperature') plt.plot(datas[7][243:250], color='r', linewidth=2) plt.scatter(6, datas[4][249], s=60, color='y') yellow_patch = mpatches.Patch(color='yellow', label='6-day pred') red_patch = mpatches.Patch(color='red', label='real') plt.legend(handles=[yellow_patch, red_patch], loc=2) plt.subplot(4, 1, 4) # plt.xlabel('8 days') plt.ylabel('temperature') plt.plot(datas[7][241:250], color='r', linewidth=2) plt.scatter(8, datas[6][249], s=60, color='g') green_patch = mpatches.Patch(color='green', label='8-day pred') red_patch = mpatches.Patch(color='red', label='real') plt.legend(handles=[green_patch, red_patch], loc=3) plt.show()
def _tsne_plot_embedding(self, x, y, inputs, path_result_image, title=""): x_min, x_max = np.min(x, 0), np.max(x, 0) x_normalized = (x - x_min) / (x_max - x_min) tableau20 = style.generate_tableau20_colors() figure = plt.figure() figure.set_size_inches(18.5, 10.5) ax = figure.add_subplot(111) ax.axis('off') for i in xrange(x.shape[0]): plt.text(x_normalized[i, 0], x_normalized[i, 1], str(y[i]), color=tableau20[y[i]], fontdict={'weight': 'bold', 'size': 12}) labels = [mpatches.Patch(color=tableau20[output_descriptor.value], label="[{0}] {1}".format(output_descriptor.value, output_descriptor.name)) for output_descriptor in list(self.output_descriptor_enum)] legend = ax.legend(handles=labels, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., frameon=False) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) for i in xrange(len(x_normalized)): distance_between_points = np.sum((x_normalized[i] - shown_images) ** 2, 1) if np.min(distance_between_points) < self.MIN_DISTANCE_BETWEEN_IMAGES: continue shown_images = np.r_[shown_images, [x_normalized[i]]] rendered_image = offsetbox.OffsetImage(self._state_into_grid_of_screenshots(inputs[i]), cmap=plt.get_cmap('gray')) image_position = x_normalized[i] annotation_box_relative_position = (-70, 250) if x_normalized[i][1] > 0.5 else (-70, -250) imagebox = offsetbox.AnnotationBbox(rendered_image, image_position, xybox=annotation_box_relative_position, xycoords='data', boxcoords="offset points", arrowprops=dict(arrowstyle="->")) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title) plt.savefig(path_result_image, bbox_extra_artists=(legend,), bbox_inches='tight', pad_inches=4) print("Visualization written to {0}".format(path_result_image))
def correlation_circle(self, axes, column_correlations, supplementary_column_correlations, explained_inertia, show_labels): fig, ax = plt.subplots() ax.grid('on') ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.axhline(y=0, linestyle='--', linewidth=1.2, color=GRAYS['dark'], alpha=0.6) ax.axvline(x=0, linestyle='--', linewidth=1.2, color=GRAYS['dark'], alpha=0.6) # Plot the arrows and add text for _, row in column_correlations.iterrows(): ax.annotate( row.name if show_labels else '', xy=(0, 0), xytext=(row[axes[0]], row[axes[1]]), arrowprops=dict(arrowstyle='<-', edgecolor='black') ) if not supplementary_column_correlations.empty: for _, row in supplementary_column_correlations.iterrows(): ax.annotate( row.name if show_labels else '', xy=(0, 0), xytext=(row[axes[0]], row[axes[1]]), arrowprops=dict(arrowstyle='<-', edgecolor='red') ) # Add legend to distinguish active and supplementary columns active_legend = mpatches.Patch(color='black', label='Active columns') supp_legend = mpatches.Patch(color='red', label='Supplementary columns') plt.legend(handles=[active_legend, supp_legend]) circle = plt.Circle((0, 0), radius=1, color=GRAYS['dark'], fill=False, lw=1.4) ax.add_patch(circle) ax.margins(0.01) ax.axis('equal') ax.set_title('Correlation circle') ax.set_xlabel('Component {} ({}%)'.format(axes[0], 100 * round(explained_inertia[axes[0]], 2))) ax.set_ylabel('Component {} ({}%)'.format(axes[1], 100 * round(explained_inertia[axes[1]], 2))) return fig, ax
def draw_timeline(self, tobesaved=False, fname=None, y_max=20, freq='1M'): ''' Prints a user's timeline of interaction with ems, jail,and mental health from 2010 Jan to 2016 June :params DataFrame user: A DataFrame of user with personid/hash_ssn, event, begin_date and end_date. :params str fname: The file name to be saved with. :params bool tobesaved: The flag of whether to save the figure. :params int y_max: The maximum of y-axis of the figure. :return: None :rtype: None ''' user_resample = self.get_series(freq) user_m = [t.count('M') for t in user_resample] user_e = [t.count('E') for t in user_resample] user_j = [t.count('J') for t in user_resample] user_df = pd.DataFrame({'count_of_m':user_m, 'count_of_j':user_j, 'count_of_e':user_e},index=list(user_resample.index.to_period(freq))) columns = list(user_resample.index.to_period(freq)) x_max = len(columns) heat_df = pd.DataFrame(np.array([[0]*x_max]*y_max), index=range(y_max), columns=columns) for i in range(len(user_df)): temp = [] temp_df = user_df.iloc[[i]] if int(temp_df['count_of_e']) > 0: temp.extend([1]*int(temp_df['count_of_e'])) if int(temp_df['count_of_j']) > 0: temp.extend([2]*int(temp_df['count_of_j'])) if int(temp_df['count_of_m']) > 0: temp.extend([3]*int(temp_df['count_of_m'])) temp = temp + [0]*(y_max-len(temp)) heat_df[columns[i]] = temp fig = plt.figure(figsize=(30,10)) #plt.title("{}'s timeline".format(user['personid'][0])) cmap = ListedColormap(['white',(0.99,0.58,0.59),(0.59,0.59,1),(0.6,0.8,0.59)]) ax = sns.heatmap(heat_df, cmap=cmap,vmin=0,vmax=3,edgecolor='w', linewidth=1.5,cbar=False, annot=False, square=True) ax.invert_yaxis() ax.set_xticklabels(columns,rotation=90,ha='center',va='top') ax.set_yticklabels(range(y_max,0,-1), rotation=0,va='baseline') ems_patch = mpatches.Patch(color=(0.99,0.58,0.59), label='EMS') jail_patch = mpatches.Patch(color=(0.59,0.59,1), label='Jail') mh_patch = mpatches.Patch(color = (0.6,0.8,0.59), label='Mental Health') plt.legend(handles=[ems_patch,jail_patch,mh_patch], handler_map={jail_patch: HandlerSquare(), ems_patch: HandlerSquare(), mh_patch: HandlerSquare()}, bbox_to_anchor=(0.5, 1.05), loc=9, ncol=3, borderaxespad=0.3,prop={'size':25}) if tobesaved == True: if fname == None: fname = "id{}_timeline.png".format(user['personid'][0]) plt.savefig(fname) plt.show()
def plot_path_2d(quad_path, planned_path=None, waypoints=None, h_axis='x', v_axis='y'): """ Generates and saves a 2D plot of the quad's path. Use this function to generate individual 2D plots of the quads path, and the planned path Use h_axis and v_axis to specify which two dimension to compare. Args: quad_path (numpy.ndarray): A 2D numpy.ndarray of x,y,z quad positions planned_path (numpy.ndarray): A 2D numpy.ndarray of x,y,z target positions waypoints (numpy.ndarray): A 2D numpy.ndarray of x,y,z positions out_fname (str): string path and file name to save the output to h_axis (str): One of 'x', 'y', or 'z. The 3d axis to use as horizontal in the 2d plot. v_axis (str): One of 'x', 'y', or 'z. The 3d axis to use as vertical in the 2d plot. Returns: None """ plt.style.use('ggplot') fig = plt.figure(figsize=(16, 10)) axes = fig.add_subplot(111) fig.suptitle('Quadrotor Path', weight='bold', fontsize=14) # generate the plot for this axes axes = path_2d(quad_path, axes, planned_path, waypoints, h_axis, v_axis) quad_patch = patches.Patch(color='k') handles = [quad_patch] labels = ['quadrotor path'] if planned_path is not None: planned_patch = patches.Patch(color='r') labels.append('planned_path') handles.append(planned_patch) if waypoints is not None: waypoints_patch = patches.Patch(color='b') labels.append('waypoints') handles.append(waypoints_patch) fig.legend(handles=handles, labels=labels, loc='upper right', fontsize=11, frameon=False) rospack = rospkg.rospack.RosPack() base_path = rospack.get_path('quad_controller') out_path = os.path.join(base_path, 'output_data', 'one_plot_' + str(time.time()) + '.png') fig.savefig(out_path, dpi='figure')
def plot_path_3d(quad_path, planned_path=None, waypoints=None, out_fname='/home/d/Desktop/tmp_3d.png', azimuth=210.0, elevation=45.0): """ Generates, displays, and saves a 3d plot of the quads path, Use this function to generate 3d plots of the path the quad took and path it was trying to follow. Use the parameters azimuth, and elevation to specify the initial viewing angle if saving plots to .png. Args: quad_path (numpy.ndarray): A 2D numpy.ndarray of x,y,z quad positions planned_path (numpy.ndarray): A 2D numpy.ndarray of x,y,z target positions waypoints (numpy.ndarray): A 2D numpy.ndarray of x,y,z positions out_fname (str): string path and file name to save the output to azimuth (float): The initial azimuth angle of the viewpoint for the matplotlib 3d plot elevation (float): the initial elevation of the viewpoint Returns: None """ plt.style.use('ggplot') fig = plt.figure(figsize=(16, 10)) fig.suptitle('Quadrotor Path', weight='bold', fontsize=14) ax3d = fig.add_subplot(111, projection='3d') ax3d = path_3d(quad_path, ax3d, planned_path, waypoints) ax3d.view_init(elevation, azimuth) quad_patch = patches.Patch(color='k') handles = [quad_patch] labels = ['quadrotor path'] if planned_path is not None: planned_patch = patches.Patch(color='r') labels.append('planned_path') handles.append(planned_patch) if waypoints is not None: waypoints_patch = patches.Patch(color='b') labels.append('waypoints') handles.append(waypoints_patch) fig.legend(handles=handles, labels=labels, loc='upper right', fontsize=11, frameon=False) rospack = rospkg.rospack.RosPack() base_path = rospack.get_path('quad_controller') out_path = os.path.join(base_path, 'output_data', 'isometric_plot_' + str(time.time()) + '.png') fig.savefig(out_path, dpi='figure')
def speedPlot(ifile=DEFAULT_FNM, timefl=1): """ Produce a plot from the output produced by the internal Python dd implementation of diskTest. The CRC throughput is shown in RED. The pure I/O in BLUE and the total throughput (CRC+I/O) in GREEN. INPUT: ifile: string, file name of the pickle file as produced by diskTest (default: bspeed.pkl) timefl: [0|1]: flag, if set the plot will use time on the x-axis else it will use block numbers. """ import pylab # This requires pylab for the plotting... import matplotlib.patches as mpatches f = open(ifile) p=pickle.Unpickler(f) (bspeed,cspeed,tspeed) = p.load() f.close() bspeed = pylab.array(bspeed) cspeed = pylab.array(cspeed) tspeed = pylab.array(tspeed) tzero = tspeed[0,1] if timefl: pylab.plot(bspeed[:,1] - tzero, bspeed[:,0],'b+') pylab.xlabel('Time since start [s]') pylab.ylabel('Throughput[MB/s]') plt = pylab.plot(tspeed[:,1] - tzero, tspeed[:,0], 'bx', mfc='none') if cspeed[0:,0].max() != -1: # plot only if not dummy plt = pylab.plot(cspeed[:,1] - tzero, cspeed[:,0],'r+') red_patch = mpatches.Patch(color='red', label='CRC performance') else: pylab.plot(bspeed[:,0],'b+') pylab.xlabel('Block #') pylab.ylabel('Throughput[MB/s]') plt = pylab.plot(tspeed[:,0], 'bx', mfc='none') if cspeed[0:,0].max() != -1: # plot only if not dummy plt = pylab.plot(cspeed[:,0],'r+') red_patch = mpatches.Patch(color='red', label='CRC performance') totalSize = (tspeed[:,0] * tspeed[:,2]).sum() totalTime = tspeed[-1][1]-tspeed[0][1] pylab.plot([0,totalTime],[totalSize/totalTime,totalSize/totalTime], 'g') blue_patch = mpatches.Patch(color='blue', label='Block I/O') green_patch = mpatches.Patch(color='green', label='Total I/O') if cspeed[0:,0].max() != -1: # plot only if not dummy pylab.legend(handles=[red_patch, blue_patch, green_patch]) else: pylab.legend(handles=[blue_patch, green_patch]) pylab.title(os.path.basename(ifile)) ymax = plt[0].axes.get_ylim()[1] # get current maximum plt[0].axes.set_ylim([0,ymax]) return
def cluster_visual(X, y_pred, y_true=None): import matplotlib.pyplot as plt import numpy as np from sklearn.decomposition import PCA import matplotlib.patches as mpatches pca = PCA(n_components=2) X = pca.fit(X).transform(X) pred_labels = np.unique(y_pred) if y_true is not None: true_labels = np.unique(y_true) fig, axes = plt.subplots(2, 1, figsize=(7, 10)) ax1, ax2 = axes else: fig, ax1 = plt.subplots(1, 1, figsize=(7, 5)) axes = (ax1,) # predicted labels for label, i in enumerate(pred_labels): if label == -1: temp_x = X[y_pred == label] ax1.scatter(temp_x[:, 0], temp_x[:, 1], c='black') else: temp_x = X[y_pred == label] ax1.scatter(temp_x[:, 0], temp_x[:, 1], c=plt.cm.Paired(int(i))) ax1.set_title('Predicted labels', size='x-large') patch = mpatches.Patch(color='black', label='Unlabeled points') ax1.legend(handles=[patch]) if y_true is not None: # true labels for label, i in enumerate(true_labels): temp_x = X[y_true == label] ax2.scatter(temp_x[:, 0], temp_x[:, 1], c=plt.cm.Paired(int(i))) ax2.set_title('True labels', size='x-large') for axis in axes: axis.grid(False, which='both') empty_x_labels = [''] * len(axis.get_xticklabels()) empty_y_labels = [''] * len(axis.get_yticklabels()) axis.set_xticklabels(empty_x_labels) axis.set_yticklabels(empty_y_labels) plt.show()
def plot_spike_sources(filePath, fileName, nrInputNeurons, nrVR, observationTime, totalSimulationTime, classLabels, odourNames): '''Plot the Poisson spike source matrix Input: -path of the spike times file -name of the spike times file -number of input neurons (= number of sensors) -number of virtual receptors -length of the Poisson spike train for each sample -maximum simulation time for each recording (number of samples for each recording) x (length of Poisson spike train for each sample) -class labels -names of the odours used ''' bckndNames =[[]]*len(odourNames) spikeTimes = utils.readSpikeSourceDataFile(os.path.join(filePath, fileName))['spike_times'] plt.figure(figsize=(20,20)) for idx, line in enumerate(spikeTimes): for x in line: plt.plot(x, idx, 'ko', markersize = 2) for j in range(idx, nrVR): plt.plot(0, j, 'k,') for j, classLabel in enumerate(classLabels): plt.axvspan(j*observationTime, j*observationTime+observationTime, facecolor=colors[int(classLabel)], alpha=0.3) for idxO, odour in enumerate(odourNames): bckndNames[idxO] = mpatches.Patch(color=colors[idxO], label=odour) plt.legend(handles=bckndNames, loc ='best', prop={'size':20}) plt.xlabel('Simulation time[ms]', fontsize=20) plt.ylabel('%i Virtual receptors per sensor'%(nrVR/nrInputNeurons), fontsize=20) plt.tick_params(labelsize=20) plt.title('VR spike times for classes %s'%str(classLabels), fontsize=20) plt.savefig(fileName+'.pdf') plt.close() #-----------------------------------------------------------------------------
def oscillator2(data): float_close = Data.toFloatArray(df['Close']) float_high = Data.toFloatArray(df['High']) float_low = Data.toFloatArray(df['Low']) float_open = Data.toFloatArray(df['Open']) adx_values = tl.ADX(np.array(float_high),np.array(float_low),np.array(float_close), timeperiod = 14) dmi = tl.DX(np.array(float_high),np.array(float_low),np.array(float_close), timeperiod = 14) mdmi = tl.MINUS_DI(np.array(float_high),np.array(float_low),np.array(float_close), timeperiod = 14) rsi = tl.RSI(np.array(float_close),timeperiod = 4 ) signals = [] flag = 0 for i in xrange(40 , len(adx_values) - 2): if flag ==0: if adx_values[i]>20 and dmi[i]>mdmi[i] and df.loc[i+1, 'Open']> (df.loc[i, 'Close']+1.8) and rsi[i]<50: signal = ['HSI', df.loc[i+1, 'Date'], 'Long', df.loc[i+1, 'Close']] flag =1 signals.append(signal) if adx_values[i]>20 and dmi[i]<mdmi[i] and df.loc[i+1, 'Open']< (df.loc[i, 'Close']-1.8) and rsi[i]<50: signal = ['HSI', df.loc[i+1, 'Date'], 'Short', df.loc[i+1, 'Close']] flag =2 signals.append(signal) elif flag ==1: if df.loc[i, 'Close']>= signal[3]*1.01 or df.loc[i, 'Close']<= signal[3]*0.90 or (df.loc[i, 'Date']-signal[1])>timedelta(days=5): signal = ['HSI', df.loc[i, 'Date'], 'Short', df.loc[i+1, 'Open']] flag = 0 signals.append(signal) elif flag ==2: if df.loc[i, 'Close']<= signal[3]*0.99 or df.loc[i, 'Close']>= signal[3]*1.10 or (df.loc[i, 'Date']-signal[1])>timedelta(days=5): signal = ['HSI', df.loc[i+1, 'Date'], 'Long', df.loc[i+1, 'Close']] flag = 0 signals.append(signal) sig = pd.DataFrame(signals, columns=['Code', 'Time', 'Action', 'Price']) print sig['Time'][10]-sig['Time'][0] profits = [] print sig for k in range(0,len(signals)/2): if sig['Action'][k*2] == "Long": profit = sig['Price'][k*2+1] - sig['Price'][k*2] else: profit = sig['Price'][k*2]- sig['Price'][k*2+1] profits.append(profit) print np.sum(profits) print(profits) ###### PLOT ####### longSignals = sig[sig['Action'] == 'Long'] shortSignals = sig[sig['Action'] == 'Short'] plt.plot(df['Date'], df['Close'], longSignals['Time'], longSignals['Price'], 'r^', shortSignals['Time'], shortSignals['Price'], 'gv', markersize=10) red_patch = mpatches.Patch(color='red', label='Long') green_patch = mpatches.Patch(color='green', label='Short') plt.legend(handles=[red_patch, green_patch]) plt.grid() plt.show() ###### PLOT #######
def create_graphic(path, array_date, array_dateb, array_datec, array_data, label): title = _('Monitoring') + ' ' + label fig = Figure() ax = fig.add_subplot(111) bx = fig.add_subplot(111) cx = fig.add_subplot(111) x = [] y = [] yb = [] yc = [] xb = [] xc = [] for i in range(len(array_data)): x.append(array_data[i]) y.append(array_date[i]) xb.append(array_data[i]) xc.append(array_data[i]) yb.append(array_dateb[i]) yc.append(array_datec[i]) ax.plot_date(x, y, '-') bx.plot_date(xb, yb, '-') cx.plot_date(xc, yc, '-') patch1 = mpatches.Patch(color='blue', label=_('Phase 1')) patch2 = mpatches.Patch(color='green', label=_('Phase 2')) patch3 = mpatches.Patch(color='red', label=_('Phase 3')) z = [patch1, patch2, patch3] cx.legend(handles=z, loc=1) ax.set_title(title) ax.set_xlabel(_('Date')) ax.set_ylabel(label) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas = FigureCanvas(fig) fig.savefig(path) return path
def plot_pr(precision, recall, title='', r=[0.67, 1.01], legend_labels=None, save_path=None, nbins=5, colorVals=None, xlabel='Recall', ylabel='Precision', l_pos="lower left", legend=True, r_x=[0.67, 1.01], ls=22): from matplotlib import pyplot as plt fig, ax = plt.subplots() fig.patch.set_facecolor('white') ax.tick_params(axis='x', which='major', labelsize=ls, direction='out', length=4, width=3, right="off", top="off", pad=10) ax.tick_params(axis='y', which='major', labelsize=ls, direction='out', length=4, width=3, right="off", top="off", pad=10) ax.tick_params(axis='x', which='minor', labelsize=ls, direction='out', length=4, width=3, right="off", top="off", pad=10) ax.tick_params(axis='y', which='minor', labelsize=ls, direction='out', length=4, width=3, right="off", top="off", pad=10) ax.spines['left'].set_linewidth(3) ax.spines['bottom'].set_linewidth(3) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) plt.locator_params(axis='x', nbins=nbins) plt.locator_params(axis='y', nbins=nbins) plt.title(title) if not -1 in r: plt.xlim(r_x) plt.ylim(r) plt.xlabel(xlabel, fontsize=ls) plt.ylabel(ylabel, fontsize=ls) plt.tight_layout() if isinstance(recall, list): if colorVals is None: colorVals = [[0.171, 0.485, 0.731, 1.], [0.175, 0.585, 0.301, 1.], [0.841, 0.138, 0.133, 1.]] if len(colorVals) < len(recall): colorVals += ["0.35"] * (len(recall) - len(colorVals)) if len(colorVals) > len(recall): colorVals = ["0.35", "0.7"] if legend_labels is None: legend_labels = ["Mitochondria", "Vesicle Clouds", "Synaptic Junctions"] handles = [] for ii in range(len(recall)): handles.append(patches.Patch(color=colorVals[ii], label=legend_labels[ii])) plt.plot(recall[ii], precision[ii], lw=4, c=colorVals[ii]) if legend: plt.legend(handles=handles, loc=l_pos, frameon=False, prop={'size': ls}) else: plt.plot(recall, precision, lw=4, c="0.35") if save_path is None: plt.show(block=False) else: plt.savefig(save_path, dpi=300)
def draw_histogram(l, dataname): import matplotlib.patches as mpatches import matplotlib.pyplot as plt from scipy import stats fig = plt.figure(1) fig.set_figheight(12) fig.set_figwidth(9) fr = fig.patch fr.set_facecolor('white') data = np.array([int(i * 100) for i in l]) lnspc = np.linspace(min(data), max(data), len(data)) d = np.diff(np.unique(data)).min() left_of_first_bin = data.min() - float(d) / 2 right_of_last_bin = data.max() + float(d) / 2 plt.hist(data, np.arange(left_of_first_bin, right_of_last_bin + d, (d / 2)), normed=True, align='left', facecolor='g', alpha=0.6) w = 2. k = float(d) * 5. m, s = stats.norm.fit(data) print("mean: %f sigma: %f" % (m, s)) pdf_g = stats.norm.pdf(lnspc, m, s) * k plt.plot(lnspc, pdf_g, 'r--', label='Norm', linewidth=w) ag, bg, cg = stats.gamma.fit(data) pdf_gamma = stats.gamma.pdf(lnspc, ag, bg, cg) * k plt.plot(lnspc, pdf_gamma, 'b--', label="Gamma", linewidth=w) ab, bb, cb, db = stats.beta.fit(data) pdf_beta = stats.beta.pdf(lnspc, ab, bb, cb, db) * k plt.plot(lnspc, pdf_beta, 'k--', label="Beta", linewidth=w) normal = mpatches.Patch(color='red', label='Normal') gamma = mpatches.Patch(color='blue', label='Gamma') beta = mpatches.Patch(color='black', label='Beta') plt.legend(loc=2, handles=[normal, gamma, beta]) plt.xlim(70, 102) plt.subplots_adjust(left=0.15) plt.grid(True) plt.xlabel("accuracy") plt.ylabel("probability") plt.title(r'{0} dataset $ \ \mu={1}, \ \sigma={2}$'.format(dataname, np.round(m, decimals=1), np.round(s, decimals=1))) plt.show() # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # DIGITS Dataset # # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
def plot_map(m, coords, df_map, info, savefig=False): plt.clf() fig = plt.figure() ax = fig.add_subplot(111, axisbg='w', frame_on=True) # draw wards with grey outlines norm = Normalize() for i in xrange(5): color = colormaps[i] cmap = plt.get_cmap(color) cond = (df_map['class'] == (i+1)) inx = df_map[cond].index if cond.sum() > 0: pc = PatchCollection(df_map[cond]['patches'], match_original=True, alpha=0.75) pc.set_facecolor(cmap(norm(df_map.loc[inx, 'cls_%d'%(i+1)].values))) ax.add_collection(pc) if (df_map['class'] == 0).sum() > 0: pc = PatchCollection(df_map[df_map['class'] == 0]['patches'], match_original=True, alpha=0.1 ) pc.set_facecolor('grey') ax.add_collection(pc) x, y = m(coords[0], coords[3]+0.006) details = ax.annotate(info, xy=(x, y), size=20, color='k') # Draw a map scale m.drawmapscale( coords[0]+0.02, coords[1]-0.004, coords[0], coords[1], 2, barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', units='mi', zorder=5) legend_patches = [] for i in range(5): legend_patches.append(mpatches.Patch(color='C%d' % i, label=classes[i])) ax.legend(handles=legend_patches, loc='upper right') fig.set_size_inches(12, 12) plt.tight_layout() if savefig: plt.savefig(savefig, dpi=200, alpha=True)
def plot_yield_by_quality(): # Close any previous plots plt.close('all') # Read in seqlength and time from ALL_READS dataframe new_yield_data = ALL_READS[['time', "seq_length", "av_qual"]] # Bin qualities qual_bins = [0] + QUALITY_BINS + [new_yield_data["av_qual"].max()] # Cut yield data into quality bins new_yield_data["descriptive_quality"] = pd.cut(new_yield_data["av_qual"], qual_bins, labels=[description for description in reversed(QUALITY_DESCRIPTIONS)]) # Time as index and drop av_qual column new_yield_data.set_index(pd.DatetimeIndex(new_yield_data['time']), inplace=True) new_yield_data.drop('av_qual', axis=1, inplace=True) # Obtain cumulative sum by quality bin in each minute. yield_data_grouped = new_yield_data.groupby("descriptive_quality").apply(lambda d: d.resample("1T").sum().fillna(0))['seq_length'] # Create a dict of dataframes based on groups. yield_data_by_quality = {description: yield_data_grouped[description].to_frame().reset_index() for description in QUALITY_DESCRIPTIONS} for description, yield_df in yield_data_by_quality.items(): yield_df.reset_index(inplace=True) yield_df.set_index("time", inplace=True) yield_df = yield_df.reindex(index=YIELD_DATA.time, fill_value=0) yield_df.reset_index(inplace=True) # Generate a cumulative sum of sequence data yield_df['cumsum_bp'] = yield_df['seq_length'].cumsum() # Convert time to timedelta format and then to float format, in hours. yield_df['duration_tdelta'] = yield_df['time'].apply(lambda t: t - yield_df['time'].min()) yield_df['duration_float'] = yield_df['duration_tdelta'].apply(lambda t: t.total_seconds() / 3600) yield_data_by_quality[description] = yield_df # Set subplots. fig, ax = plt.subplots(1) # Create ticks using numpy linspace. Ideally will create 6 points between 0 and 48 hours. num_points = 7 # Need to include zero point x_ticks = np.linspace(YIELD_DATA['duration_float'].min(), YIELD_DATA['duration_float'].max(), num_points) ax.set_xticks(x_ticks) # Define axis formatters ax.yaxis.set_major_formatter(FuncFormatter(y_yield_to_human_readable)) ax.xaxis.set_major_formatter(FuncFormatter(x_yield_to_human_readable)) # Set x and y labels and title. ax.set_xlabel("Duration (HH:MM)") ax.set_ylabel("Yield") ax.set_title(f"Yield for {SAMPLE_NAME} over time by quality") ax.stackplot(YIELD_DATA['duration_float'], [yield_data_by_quality[description]['cumsum_bp'] for description in QUALITY_DESCRIPTIONS], colors=QUALITY_COLOURS) # Limits must be set after the plot is created ax.set_xlim(YIELD_DATA['duration_float'].min(), YIELD_DATA['duration_float'].max()) ax.set_ylim(ymin=0) # Add legend to plot. ax.legend([mpatches.Patch(color=colour) for colour in QUALITY_COLOURS], QUALITY_DESCRIPTIONS, loc=2) # Ensure labels are not missed. fig.tight_layout() savefig(os.path.join(PLOTS_DIR, f"{SAMPLE_NAME.replace(' ', '_')}_yield_plot_by_quality.png"))