def generate_wordcloud(text): # load custom stopword list stopwords = set([x.strip() for x in open('stopwords').read().split('\n')]) print stopwords # Generate a word cloud image wordcloud = WordCloud(stopwords=stopwords, max_font_size=50, max_words=2000, width=800, height=600, margin=0).generate(text) # Display the generated image: # the matplotlib way: import matplotlib.pyplot as plt plt.imshow(wordcloud) plt.axis("off") # display the image # plt.show() # save image on disk (+ get rid of the margin trick) plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) import matplotlib.ticker as ticker plt.gca().xaxis.set_major_locator(ticker.NullLocator()) plt.gca().yaxis.set_major_locator(ticker.NullLocator()) plt.savefig('results.png', bbox_inches='tight', pad_inches=0.0)
def process_image(self, datagen, suffix): # prepare iterator it = datagen.flow(self.samples, batch_size=1) name, extension = os.path.splitext(self.image_path) # print(name + suffix + extension) # generate samples and plot for i in range(9): # define subplot pyplot.subplot(330 + 1 + i) # generate batch of images batch = it.next() # if i%2 == 0: # continue # convert to unsigned integers for viewing image = batch[0].astype('uint8') new_name = name + suffix + str(i) + extension pyplot.imshow(image) pyplot.axis('off') pyplot.gca().xaxis.set_major_locator(ticker.NullLocator()) pyplot.gca().yaxis.set_major_locator(ticker.NullLocator()) pyplot.savefig(new_name, bbox_inches='tight', pad_inches=0, transparent="True") pyplot.close pyplot.imshow(image) pyplot.show()
def error_bitmap(sx, mu_axes, sigma_axes): """ Plot bitmaps of the mean relative error and standard deviation of the mean relative error. Arguments: sx -- the observation model. mu_axes -- the axis of the mean relative error bitmap. sigma_axes -- the axis of the mean relative error standard deviation bitmap. cmap -- the colour map of the bitmap. """ # Construct the mean and sigma matrices. mu_v, sigma_v = analysis.algorithm.feature_relative_error(sx) mu_m, sigma_m = square(mu_v), square(sigma_v) # Plot the mean relative error bitmap. mu_axes.get_xaxis().set_major_locator(ticker.NullLocator()) mu_axes.get_yaxis().set_major_locator(ticker.NullLocator()) mu_im = mu_axes.imshow(mu_m, vmin=0, vmax=1, cmap=ERROR_SCHEME) mu_im.set_interpolation(INTERPOLATION) # Plot the mean relative error standard deviation bitmap. sigma_axes.get_xaxis().set_major_locator(ticker.NullLocator()) sigma_axes.get_yaxis().set_major_locator(ticker.NullLocator()) sigma_im = sigma_axes.imshow(sigma_m, vmin=0, vmax=1, cmap=ERROR_SCHEME) sigma_im.set_interpolation(INTERPOLATION) # Return the mean and relative error images for colour bar plotting. return mu_im, sigma_im
def plotSimplex(points, fig=None, vertexlabels=['0', '1', '2'], **kwargs): """ Plot Nx3 points array on the 3-simplex (with optionally labeled vertices) kwargs will be passed along directly to matplotlib.pyplot.scatter Returns Figure, caller must .show() """ if (fig == None): fig = plt.figure() # Draw the triangle l1 = L.Line2D( [0, 0.5, 1.0, 0], # xcoords [0, np.sqrt(3) / 2, 0, 0], # ycoords color='k') fig.gca().add_line(l1) fig.gca().xaxis.set_major_locator(MT.NullLocator()) fig.gca().yaxis.set_major_locator(MT.NullLocator()) # Draw vertex labels fig.gca().text(-0.05, -0.05, vertexlabels[0]) fig.gca().text(1.05, -0.05, vertexlabels[1]) fig.gca().text(0.5, np.sqrt(3) / 2 + 0.05, vertexlabels[2]) # Project and draw the actual points projected = projectSimplex(points) plt.scatter(projected[:, 0], projected[:, 1], **kwargs) # Leave some buffer around the triangle for vertex labels fig.gca().set_xlim(-0.2, 1.2) fig.gca().set_ylim(-0.2, 1.2) return fig
def superimpose_meas_and_objs_on_image(store_to_image, image, meas, objs): #Consider first up-scaling the image. meas_names = ["Batt_Level", "Num_Poisons", "Num_Foods"] objs_names = ["Battery", "Poison", "Food"] fig, ax = plt.subplots() ax.imshow(image) y_pos = [25, 55, 85] #TODO Generalize objcounter = 0 for obj in objs_names: ax.barh(y_pos[objcounter], convert_plotted_values_x_axis(objs[objcounter]), bar_width, align='center', color=colors[objcounter], ecolor='black') objcounter += 1 ax.text(300, 390, str(meas[0]), fontsize=40, color='blue') ax.legend(objs_names, loc='upper right', fontsize=15) plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(tick.NullLocator()) plt.gca().yaxis.set_major_locator(tick.NullLocator()) plt.savefig(store_to_image, bbox_inches="tight", pad_inches=0) plt.close(fig)
def scaledimage(W, pixwidth=1, ax=None, grayscale=True): """Do intensity plot, similar to MATLAB imagesc().""" # W = intensity matrix to visualize # pixwidth = size of each W element # ax = matplotlib Axes to draw on # grayscale = use grayscale color map # Rely on caller to .show() # N = rows, M = column (N, M) = W.shape # Need to create a new Axes? if(ax is None): ax = plt.figure().gca() # extents = Left Right Bottom Top exts = (0, pixwidth * M, 0, pixwidth * N) if(grayscale): ax.imshow(W, interpolation='nearest', cmap=cm.gray, extent=exts) else: ax.imshow(W, interpolation='nearest', extent=exts) ax.xaxis.set_major_locator(mt.NullLocator()) ax.yaxis.set_major_locator(mt.NullLocator()) return ax
def extract_features(dataframe): for i, (file, emotion) in enumerate(dataframe.values): sample_rate, samples = wavfile.read(file) spectrum, freqs, t, im = plt.specgram(samples, Fs=sample_rate) plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(ticker.NullLocator()) plt.gca().yaxis.set_major_locator(ticker.NullLocator()) #plt.show() index = file.rfind('/') basename = file[(index + 1):-4] #plt.savefig(endpoint + '{}_spec.png'.format(basename), bbox_inches='tight', pad_inches=0) print(i) im = cv2.imread(endpoint + '{}_spec.png'.format(basename)) try: x = len(im) input.append(im) target.append(encode[emotion]) except: print("no data found at index" + str(i)) return input, target
def imagesc(W, pixwidth=1, ax=None, grayscale=True): ''' Do intensity plot, similar to MATLAB imagesc() W = intensity matrix to visualize pixwidth = size of each W element ax = matplotlib Axes to draw on grayscale = use grayscale color map Rely on caller to .show() Simple matrix intensity plot, similar to MATLAB imagesc() David Andrzejewski ([email protected]) From: https://gist.github.com/940072 ''' # import at last minute to allow user to change settings via previous matplotlib.use() from matplotlib import pyplot # N = rows, M = column (N, M) = W.shape # Need to create a new Axes? if (ax == None): ax = pyplot.figure().gca() # extents = Left Right Bottom Top exts = (0, pixwidth * M, 0, pixwidth * N) if (grayscale): ax.imshow(W, interpolation='nearest', cmap=CM.gray, extent=exts) else: ax.imshow(W, interpolation='nearest', extent=exts) ax.xaxis.set_major_locator(MT.NullLocator()) ax.yaxis.set_major_locator(MT.NullLocator()) return ax
def plot_activation(matrix, step, save_to=None): save_to = os.path.join(".", "activations") if save_to is None else save_to os.makedirs(save_to, exist_ok=True) if len(matrix.shape) != 2: raise ValueError('Input "matrix" should have 2 rank, but it is', str(len(matrix.shape))) num_label = matrix.shape[1] - 1 matrix = matrix[matrix[:, num_label].argsort()] fig, axes = plt.subplots(ncols=1, nrows=num_label, figsize=(15, 12)) fig.suptitle("The probability of entity presence (step %s)" % str(step), fontsize=20) fig.tight_layout() for i, ax in enumerate(axes.flatten()): idx = num_label - (i + 1) ax.spines['top'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_ylim(0, 1.05) ax.set_ylabel("Capsule " + str(idx)) ax.yaxis.set_major_locator(ticker.NullLocator()) if idx > 0: ax.xaxis.set_major_locator(ticker.NullLocator()) else: ax.xaxis.set_major_locator(ticker.IndexLocator(base=500, offset=0)) ax.set_xlabel("Sample index ") ax.plot(matrix[:, idx]) ax_prime = ax.twinx() ax_prime.spines['top'].set_color('none') ax_prime.spines['bottom'].set_color('none') plt.subplots_adjust(hspace=0.2, left=0.05, right=0.95, bottom=0.05, top=.95) plt.savefig(os.path.join(save_to, "activation_%s.png" % str(step))) plt.close()
def risk_bitmap(sx, sy, mu_axes, sigma_axes): """ Plot bitmaps of the mean attributable risk and standard deviation of the mean attributable risk. Arguments: sx -- the observation model of the exposed group. sy -- the observation model of the unexposed group. mu_axes -- the axes of the mean relative error bitmap. sigma_axes -- the axes of the standard deviation mean relative error bitmap. cmap -- the colour map of the bitmap. """ # Construct the mean and sigma matrices. mu_v, sigma_v = analysis.algorithm.feature_attributable_risk(sx, sy) mu_m, sigma_m = square(mu_v), square(sigma_v) # Plot the mean relative error bitmap. mu_axes.get_xaxis().set_major_locator(ticker.NullLocator()) mu_axes.get_yaxis().set_major_locator(ticker.NullLocator()) mu_im = mu_axes.imshow(mu_m, vmin=-1, vmax=1, cmap=RISK_MEAN_SCHEME) mu_im.set_interpolation(INTERPOLATION) # Plot the mean relative error standard deviation bitmap. sigma_axes.get_xaxis().set_major_locator(ticker.NullLocator()) sigma_axes.get_yaxis().set_major_locator(ticker.NullLocator()) sigma_im = sigma_axes.imshow(sigma_m, vmin=0, vmax=0.25, cmap=RISK_SE_SCHEME) sigma_im.set_interpolation(INTERPOLATION) # Return the mean and relative error images for colour bar plotting. return mu_im, sigma_im
def draw_simplex(pay_mat, save=False, savename='simplex'): patches = produce_patches(pay_mat) # print(patches) final_patches = list(map(s2.project_polygon, patches)) fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') ax.set_xlim(-0.18, 1.18) ax.set_ylim(-0.18, 1) ax.xaxis.set_major_locator(mt.NullLocator()) ax.yaxis.set_major_locator(mt.NullLocator()) ax.text(-0.06, -0.05, '0') ax.text(1.03, -0.05, '1') ax.text(0.49, np.sqrt(3) / 2 + 0.03, '2') fig.subplots_adjust(bottom = 0.1) fig.subplots_adjust(top = 0.9) fig.subplots_adjust(left = 0.1) fig.subplots_adjust(right = 1) p_0 = pts.Polygon(final_patches[0], ec='black', fc='sandybrown') p_1 = pts.Polygon(final_patches[1], ec='black', fc='indianred') p_2 = pts.Polygon(final_patches[2], ec='black', fc='lightseagreen') ax.add_patch(p_0) ax.add_patch(p_1) ax.add_patch(p_2) plt.legend([p_1, p_2, p_0], ['TR0', 'TR1', 'TR2']) if save: plt.savefig(savename + '.png') else: plt.show()
def neural_map(ax: plt.Axes, neurons: np.ndarray, axes: bool): l = neurons.shape[0] if axes: major_locator_n = tik.MultipleLocator(l // 2) major_formatter_n = tik.FormatStrFormatter('%d') minor_locator_n = tik.MultipleLocator(1) ax.yaxis.set_major_locator(major_locator_n) ax.yaxis.set_major_formatter(major_formatter_n) ax.yaxis.set_minor_locator(minor_locator_n) ax.xaxis.set_major_locator(major_locator_n) ax.xaxis.set_major_formatter(major_formatter_n) ax.xaxis.set_minor_locator(minor_locator_n) else: ax.xaxis.set_major_locator(tik.NullLocator()) ax.xaxis.set_minor_locator(tik.NullLocator()) ax.yaxis.set_major_locator(tik.NullLocator()) ax.yaxis.set_minor_locator(tik.NullLocator()) ax.imshow(neurons, cmap="hot", interpolation='none') ax.set_aspect('equal') ma = l - 0.5 mi = -0.5 ax.set_xlim(mi, ma) ax.set_ylim(mi, ma) for i in range(1, l): xy = i - 0.5 ax.plot((mi, ma), (xy, xy), 'red', linestyle='-') ax.plot((xy, xy), (mi, ma), 'red', linestyle='-')
def create_data(df_value): file, emotion = df_value sample_rate, sample = wavfile.read(file) segments = np.array_split(sample, 40) previous=[] segments_new=[] for s in segments: previous+=list(s) segments_new.append(previous) assert len(previous)==len(sample) , "size mismatch" utterance = [] for j,s in enumerate(segments_new): plt.clf() spectrum, freqs, t, im = plt.specgram(s, Fs=sample_rate) plt.gca().set_axis_off() plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0) plt.margins(0,0) plt.gca().xaxis.set_major_locator(ticker.NullLocator()) plt.gca().yaxis.set_major_locator(ticker.NullLocator()) index = file.rfind('/') basename = file[(index + 1):-4] plt.savefig(endpoint + '{}_spec_{}.png'.format(basename, j), dpi=10, bbox_inches='tight', pad_inches=0) im = cv2.imread(endpoint + '{}_spec_{}.png'.format(basename, j)) utterance.append(im) label = encode[emotion] return utterance, label
def save_tight(filepath): plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(ticker.NullLocator()) plt.gca().yaxis.set_major_locator(ticker.NullLocator()) plt.savefig(filepath, bbox_inches='tight', pad_inches=0)
def plotShapeletFunction(axes, func, x, y): z = numpy.zeros((y.size, x.size), dtype=float) ev = func.evaluate() for i, py in enumerate(y): for j, px in enumerate(x): z[i,j] = ev(float(px), float(py)) axes.imshow(z, interpolation='nearest', origin='lower') axes.yaxis.set_major_locator(ticker.NullLocator()) axes.xaxis.set_major_locator(ticker.NullLocator())
def wholeImgCLS(gt_info_cls,pred_info_cls, dirpath): # truth = np.loadtxt(filename, delimiter=',' ) fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') im = Image.open(os.path.join(dirpath, "image")).convert('L') ax.set_axis_off() print("here") fig.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) ax.margins(0, 0) ax.xaxis.set_major_locator(ticker.NullLocator()) ax.yaxis.set_major_locator(ticker.NullLocator()) ax.imshow(im, cmap='gray') recList = list() # color = { # 0: "red", # 1: "blue", # 2: "yellow" # } # Adding blue rectangle from gt p=patches.Rectangle( (gt_info_cls[1], gt_info_cls[2]), np.abs(gt_info_cls[3] - gt_info_cls[1]), np.abs(gt_info_cls[4] - gt_info_cls[2]), fill=False, edgecolor="blue", linewidth=2 ) recList.append(p) # Adding red rectangle from pred p=patches.Rectangle( (pred_info_cls[1], pred_info_cls[2]), np.abs(pred_info_cls[3] - pred_info_cls[1]), np.abs(pred_info_cls[4] - pred_info_cls[2]), fill=False, edgecolor="red", linewidth=2 ) recList.append(p) # plot the graph for recp in recList: ax.add_patch(recp) plt.plot() # plt.show() tmpName = "whole_Line" + str(pred_info_cls[0])+"-"+str(gt_info_cls[0])+".png" fig.savefig(os.path.join(dirpath, tmpName), dpi=dpi, bbox_inches='tight', pad_inches=0) return tmpName
def draw_graph(oriG, active_nodes=set(), title=None, last=False): global imgix draw_nodes = nx.draw_networkx_nodes draw_edges = nx.draw_networkx_edges draw_labels = nx.draw_networkx_labels draw_edge_labels = nx.draw_networkx_edge_labels pos = {i: oriG.node[i]['pos'] for i in oriG} fig, ax = plt.subplots(figsize=(12, 8)) if title is not None: ax.set_title(title) # draw nodes nonactive_nodes = set(oriG.nodes()) - set(active_nodes) draw_nodes(oriG, pos=pos, nodelist=nonactive_nodes, node_color='skyblue', ax=ax) draw_nodes(oriG, pos=pos, nodelist=[s], node_color='blue', ax=ax) draw_nodes(oriG, pos=pos, nodelist=[t], node_color='darkgreen', ax=ax) for active_node in active_nodes: excess_ratio = calc_excess_ratio(oriG, active_node) draw_nodes(oriG, pos=pos, nodelist=[active_node], node_color='red', alpha=excess_ratio, ax=ax) nls = {i: oriG.node[i]['d'] if 'd' in oriG.node[i] else i for i in oriG} draw_labels(oriG, pos=pos, labels=nls, ax=ax) # draw edges draw_edges(oriG, pos=pos, edgelist=oriG.edges(), alpha=0.2) for u, v in oriG.edges(): if 'preflow' in oriG[u][v]: width = oriG[u][v]['preflow'] else: width = 1 draw_edges(oriG, pos=pos, edgelist=[(u, v)], width=width, ax=ax) els = dict() for u, v in oriG.edges(): if 'preflow' in oriG[u][v]: preflow = oriG[u][v]['preflow'] else: preflow = 0 capacity = oriG[u][v]['capacity'] els[u, v] = '{}/{}'.format(preflow, capacity) draw_edge_labels(oriG, pos=pos, edge_labels=els, ax=ax) # erase locator ax.xaxis.set_major_locator(ticker.NullLocator()) ax.yaxis.set_major_locator(ticker.NullLocator()) if last: plt.savefig('figs/Last.png') else: plt.savefig('figs/Image{0:04d}.png'.format(imgix)); imgix = imgix + 1 plt.close()
def make_axes(fig): # 调整子图间的布局 fig.subplots_adjust(left=0.1, right=0.95, top=0.9, bottom=0.1, hspace=0.3, wspace=0.8) # 绘制左侧一列的绘图区(子图subplot) ax1 = plt.subplot2grid((3, 12), (0, 0), colspan=3, fc='greenyellow') ax2 = plt.subplot2grid((3, 12), (1, 0), colspan=3, fc='lightgreen') ax2.set_xlim(-1, 1) # 设置X轴坐标限制范围 ax2.set_ylim(-1, 1) # 设置X轴坐标限制范围 ax2.spines['right'].set_visible(False) # 设置右侧轴不可见 ax2.spines['top'].set_visible(False) # 设置上边轴不可见 ax2.spines['left'].set_position('center') # 将左侧轴设置到中间显示 ax2.spines['bottom'].set_position('center') # 将底部轴设置到中间显示 ax3 = plt.subplot2grid((3, 12), (2, 0), colspan=3, fc='springgreen') # 绘制中间一列的绘图区(子图subplot) ax4 = plt.subplot2grid((3, 12), (0, 3), rowspan=2, colspan=6, fc='None') # ax4.imshow(mapimg) ax5 = plt.subplot2grid((3, 12), (2, 3), colspan=2, fc='aqua', polar=True) ax6 = plt.subplot2grid((3, 12), (2, 5), colspan=2, fc='dodgerblue', polar=True) ax6.yaxis.set_major_locator(ticker.NullLocator()) ax7 = plt.subplot2grid((3, 12), (2, 7), colspan=2, fc='royalblue', polar=True) ax7.yaxis.set_major_locator(ticker.NullLocator()) # 绘制右侧一列的绘图区(子图subplot) ax8 = plt.subplot2grid((3, 12), (0, 9), colspan=3, fc='plum', polar=True) ax9 = plt.subplot2grid((3, 12), (1, 9), colspan=3, fc='mediumpurple') ax10 = plt.subplot2grid((3, 12), (2, 9), colspan=3, fc='purple', polar=True) return ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9, ax10
def __init__(self, axes, tile, **kwargs): super().__init__(**kwargs) self.tile = tile self.axes = axes self.axes.xaxis.set_major_locator(ticker.NullLocator()) self.axes.yaxis.set_major_locator(ticker.NullLocator()) self.artist = axes.imshow(np.zeros((0, 0)), origin="lower") self.rectangle = mp.patches.Rectangle((0, 0), 0, 0, ec='red', fc='None', zorder=5000) self.rectangle.set_alpha(0) self.axes.add_patch(self.rectangle) self.z_slice_max = self.tile.image.shape[2] - 1 self.z_slice = self.tile.image.shape[2] // 2 self.shift = self.tile.info["scaling"][0] * 5 tile.observe('extent', self.request_redraw)
def setup(ax): ax.cla() ax.spines['right'].set_color('none') ax.spines['left'].set_color('none') ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('none') # bottom ax.xaxis.set_major_locator(ticker.NullLocator()) ax.tick_params(which='major', width=1.00) ax.tick_params(which='major', length=5) ax.tick_params(which='minor', width=0.75) ax.tick_params(which='minor', length=2.5) ax.set_xlim(0, 5) ax.set_ylim(0, 1)
def plot(self, filename=None, show=False): self.plt.rcParams.update(self.params) labelLen = max(len(label) for label in self.labels) w, h = 800, 600 space = 0.01 if self.space_width == None else self.space_width border = self.border_width width = 1.0 - 2*border height = 1.0 - 2*border textLineHeight = min(max(h/len(self.labels), 4), self.plt.rcParams.get("font.size", 12)) maxTextLineWidthEstimate = textLineHeight*labelLen ## print maxTextLineWidthEstimate textAxisWidthRatio = 2.0*maxTextLineWidthEstimate/w ## print textAxisWidthRatio labelsAreaRatio = min(textAxisWidthRatio, 0.4) if self.label_width == None else self.label_width x, y = len(self.data.domain.attributes), len(self.data) heatmapAreaRatio = min(1.0*y/h*x/w, 0.3) if self.heatmap_width == None else self.heatmap_width dendrogramAreaRatio = 1.0 - labelsAreaRatio - heatmapAreaRatio - 2*space if self.dendrogram_width == None else self.dendrogram_width self.fig = self.plt.figure() self.labels_offset = self.root.height/20.0 dendrogramAxes = self.plt.axes([border, border, width*dendrogramAreaRatio, height]) dendrogramAxes.xaxis.grid(True) import matplotlib.ticker as ticker dendrogramAxes.yaxis.set_major_locator(ticker.NullLocator()) dendrogramAxes.yaxis.set_minor_locator(ticker.NullLocator()) dendrogramAxes.invert_xaxis() self.plotDendrogram() heatmapAxes = self.plt.axes([border + width*dendrogramAreaRatio + space, border, width*heatmapAreaRatio, height], sharey=dendrogramAxes) heatmapAxes.xaxis.set_major_locator(ticker.NullLocator()) heatmapAxes.xaxis.set_minor_locator(ticker.NullLocator()) heatmapAxes.yaxis.set_major_locator(ticker.NullLocator()) heatmapAxes.yaxis.set_minor_locator(ticker.NullLocator()) self.plotHeatMap() labelsAxes = self.plt.axes([border + width*(dendrogramAreaRatio + heatmapAreaRatio + 2*space), border, width*labelsAreaRatio, height], sharey=dendrogramAxes) self.plotLabels() labelsAxes.set_axis_off() labelsAxes.xaxis.set_major_locator(ticker.NullLocator()) labelsAxes.xaxis.set_minor_locator(ticker.NullLocator()) labelsAxes.yaxis.set_major_locator(ticker.NullLocator()) labelsAxes.yaxis.set_minor_locator(ticker.NullLocator()) if filename: canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(self.fig) canvas.print_figure(filename) if show: self.plt.show()
def plotcls(cls_list, dirPath): # truth = np.loadtxt(filename, delimiter=',' ) fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') im = np.array(Image.open(os.path.join(dirPath, "image")), dtype=np.uint8) ax.set_axis_off() print("here") fig.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) ax.margins(0, 0) ax.xaxis.set_major_locator(ticker.NullLocator()) ax.yaxis.set_major_locator(ticker.NullLocator()) ax.imshow(im.astype(np.uint8), cmap='gray') recList = list() # Adding blue rectangle from predict for element in cls_list: pred = element[0] gt = element[2] recList.append( patches.Rectangle( (pred[1], pred[2]), np.abs(pred[3] - pred[1]), np.abs(pred[4] - pred[2]), fill=False, edgecolor = 'red', linewidth=1 ) ) recList.append( patches.Rectangle( (gt[1], gt[2]), np.abs(gt[3] - gt[1]), np.abs(gt[4] - gt[2]), fill=False, edgecolor = 'blue', linewidth=1 ) ) # plot the graph for p in recList: ax.add_patch(p) plt.plot() # plt.show() fig.savefig(os.path.join(dirPath, "cls.png"), dpi=dpi, bbox_inches='tight', pad_inches=0)
def plot(self, W): dim = eval('(' + W.label + ')')[0] size = int(math.ceil(math.sqrt(dim[0]))) if len(dim) == 4: for i, channel in enumerate(W.data): ax = plt.subplot(size, size, i + 1) ax.xaxis.set_major_locator(ticker.NullLocator()) ax.yaxis.set_major_locator(ticker.NullLocator()) accum = channel[0] for ch in channel: accum += ch accum /= len(channel) ax.imshow(accum) else: plt.imshow(W.data)
def display_color(x, images, labels, save_file=None): """ Display color versions of the MNIST digits in a grid determined by the t-SNE projections. This code is translated and adapted from Andrej Karpathy's Matlab code: https://cs.stanford.edu/people/karpathy/cnnembed/ :param x: t-SNE projections of images :param images: Images to be displayed at each location :param labels: Image labels :param save_file: File path where the resultant image should be saved. If None, it displays to the screen. """ COL = MplColorHelper('nipy_spectral_r', 0, 10) N = len(images) S = 2000 # Size of final image G = np.ones((S, S, 3)) # Placeholder for RGB pixels in final image s = 50 # Size of every image thumbnail for i in range(N): a = np.ceil(x[i, 0] * (S - s) + 1) b = np.ceil(x[i, 1] * (S - s) + 1) a = a - ((a - 1) % s) b = b - ((b - 1) % s) a, b = int(a-1), int(b-1) if G[a, b, 0] != 1: # Check if the spot is already filled continue I = images[i].permute(1, 2, 0).numpy() I = resize(I, (s, s)) J = np.ones((s, s, 3)) if I.shape[2] == 1: eps = 0.0001 idx = np.where(I < eps) J[idx[0], idx[1], :] = [1, 1, 1] idx = np.where(I > eps) J[idx[0], idx[1], :] = COL.get_rgb(labels[i])[0:3] G[a:(a + s), b:(b + s)] = J fig = plt.figure() ax = plt.Axes(fig, [0., 0., 1.0, 1.0]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(G) plt.gca().xaxis.set_major_locator(ticker.NullLocator()) plt.gca().yaxis.set_major_locator(ticker.NullLocator()) if save_file is None: plt.show() else: plt.savefig(save_file, bbox_inches='tight', pad_inches=0)
def addEllipses(): alpha = 0.05 position = [0.16, 0.5, 0.3, 0.3] newax = plt.gcf().add_axes(position, zorder=+100) newax.patch.set_alpha(0) newax.yaxis.set_major_locator(plticker.NullLocator()) newax.xaxis.set_major_locator(plticker.NullLocator()) newax.axis('off') ellipse = Ellipse((0.3, 0.6), 0.3, 0.6, edgecolor='None', fc='green', alpha=alpha) newax.add_patch(ellipse) position = [0.16, 0.15, 0.3, 0.3] newax = plt.gcf().add_axes(position, zorder=+100) newax.patch.set_alpha(0) newax.yaxis.set_major_locator(plticker.NullLocator()) newax.xaxis.set_major_locator(plticker.NullLocator()) newax.axis('off') ellipse = Ellipse((0.3, 0.6), 0.3, 0.6, edgecolor='None', fc='blue', alpha=alpha) newax.add_patch(ellipse) position = [0.61, 0.28, 0.3, 0.3] newax = plt.gcf().add_axes(position, zorder=+100) newax.patch.set_alpha(0) newax.yaxis.set_major_locator(plticker.NullLocator()) newax.xaxis.set_major_locator(plticker.NullLocator()) newax.axis('off') ellipse = Ellipse((0.3, 0.6), 0.3, 0.45, edgecolor='None', fc='red', alpha=alpha, angle=45) newax.add_patch(ellipse) position = [0.78, 0.78, 0.1, 0.1] newax = plt.gcf().add_axes(position, zorder=+100) newax.patch.set_alpha(0) newax.yaxis.set_major_locator(plticker.NullLocator()) newax.xaxis.set_major_locator(plticker.NullLocator()) newax.axis('off') ellipse = Ellipse((0.5, 0.5), 0.3, 0.5, edgecolor='None', fc='brown', alpha=alpha) newax.add_patch(ellipse)
def plot_results_triple(stkFile, npFinal, file_to_save, picName, predicted_data, true_data, prediction_len): df2 = pd.read_csv(file_to_save) for i in npFinal: df2 = df2.append({'Close':i}, ignore_index=True) b1 = len(df2)-150 b2 = len(df2)-50 g1 = len(df2)-51 g2 = len(df2) blue = df2[(df2.index >= b1) & (df2.index < b2)] gold = df2[(df2.index >= g1) & (df2.index < g2)] fig = pyplot.figure(facecolor='white') ax = fig.add_subplot(111) pyplot.plot(gold.index, gold.Close, color='gold') ax.plot(blue.index, blue.Close, color='navy') dT1 = date.today() - timedelta(days = 150) dT2 = date.today() dT3 = date.today() + timedelta(days = 50) dTime1 = dt.datetime.strftime(dT1, '%Y-%m-%d') dTime2 = dt.datetime.strftime(dT2, '%Y-%m-%d') dTime3 = dt.datetime.strftime(dT3, '%Y-%m-%d') pyplot.text(b1, blue['Close'][b1], dTime1, weight='bold', va='bottom', fontsize=8, rotation=85) pyplot.text(b2, gold['Close'][g1], dTime2, weight='bold', va='bottom', fontsize=8, rotation=85) pyplot.text((g2-1), gold['Close'][g2-1], dTime3, weight='bold', va='bottom', fontsize=8, rotation=85) pyplot.xlabel('Trading Days') pyplot.ylabel('Price') ax1 = pyplot.axes() x_axis = ax1.axes.get_xaxis() x_axis.set_label_text('foo') x_axis.label.set_visible(False) x_axis.set_major_locator(ticker.NullLocator()) x_axis.set_minor_locator(ticker.NullLocator()) x_label = x_axis.get_label() x_label.set_visible(False) picPath = os.getcwd() + "/saved_pngs/" picName = picName + "2.png" os.chdir(picPath) pyplot.savefig(picName, dpi=400, bbox_inches='tight') os.chdir("../")
def test_locator_set_formatter(): """ Test if setting the locator only will update the AutoDateFormatter to use the new locator. """ plt.rcParams["date.autoformatter.minute"] = "%d %H:%M" t = [ datetime.datetime(2018, 9, 30, 8, 0), datetime.datetime(2018, 9, 30, 8, 59), datetime.datetime(2018, 9, 30, 10, 30) ] x = [2, 3, 1] fig, ax = plt.subplots() ax.plot(t, x) ax.xaxis.set_major_locator(mdates.MinuteLocator((0, 30))) fig.canvas.draw() ticklabels = [tl.get_text() for tl in ax.get_xticklabels()] expected = [ '30 08:00', '30 08:30', '30 09:00', '30 09:30', '30 10:00', '30 10:30' ] assert ticklabels == expected ax.xaxis.set_major_locator(mticker.NullLocator()) ax.xaxis.set_minor_locator(mdates.MinuteLocator((5, 55))) decoy_loc = mdates.MinuteLocator((12, 27)) ax.xaxis.set_minor_formatter(mdates.AutoDateFormatter(decoy_loc)) ax.xaxis.set_minor_locator(mdates.MinuteLocator((15, 45))) fig.canvas.draw() ticklabels = [tl.get_text() for tl in ax.get_xticklabels(which="minor")] expected = ['30 08:15', '30 08:45', '30 09:15', '30 09:45', '30 10:15'] assert ticklabels == expected
def set_legends(fig, ax, image_size, query, ysubtitle, title): #remove frame bottom_side = ax.spines["bottom"] bottom_side.set_visible(False) left_side = ax.spines["left"] left_side.set_visible(False) right_side = ax.spines["right"] right_side.set_visible(False) top_side = ax.spines["top"] top_side.set_visible(False) #display tickers ax.xaxis.set_major_locator(ticker.NullLocator()) numlabel = map(lambda x: image_size[0] / 2 + (x) * (image_size[0] + 1), range(len(query))) ax.yaxis.set_major_locator(ticker.FixedLocator(numlabel)) labels = map(lambda x: x, list(sorted(query))) ax.yaxis.set_major_formatter(ticker.FixedFormatter(labels)) #display legends plt.suptitle(title, fontsize=15) plt.title("Memory", loc='right', fontsize=13) if ysubtitle == "": plt.ylabel("Inputs", fontsize=15) #left_side.set_visible(True) else: plt.title("Inputs", loc='left', fontsize=13) plt.ylabel(ysubtitle, fontsize=15)
def dist_var_hist_box(series_var,filename): fig = plt.figure(figsize=(16, 10), dpi=80) # Creates one subplot within our figure and uses the classes fig and ax fig, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={"height_ratios": (.15, .85)}, dpi= 80, facecolor='w', edgecolor='k') sns.boxplot(series_var, ax=ax_box) sns.distplot(series_var, ax=ax_hist) #ax.set_ylim(0, 100) ax_hist.xaxis.set_major_locator(ticker.MultipleLocator(100000.00)) ax_hist.xaxis.set_minor_locator(ticker.MultipleLocator(50000)) ax_hist.xaxis.set_major_formatter(ticker.StrMethodFormatter('${x:,.0f}')) ax_hist.set_xlabel("House Price at Sale") ax_hist.yaxis.set_major_formatter(ticker.PercentFormatter()) ax_hist.yaxis.set_major_locator(ticker.NullLocator()) ax_box.set(xlabel='') fig.suptitle('Distribution of Housing Sales in Ames, Iowa', fontsize=26) file_name = filename path = './images/'+file_name+'.png' plt.savefig(path) plt.close(fig) pass
def plot_kde(df): row = dict(enumerate(range(3), 1)) column = dict(acute=0, chronic=1) with seaborn.axes_style('darkgrid'): fig, axes = pyplot.subplots(3, 2, sharex='col') for ((model, SAT), group) in df.groupby(['model', 'SAT']): i, j = row[SAT], column[model] ax = axes[i, j] for (b, g ) in group.groupby('birth_seasonal_coefficient_of_variation'): ser = g.time[g.observed] proportion_observed = len(ser) / len(g) if proportion_observed > 0: kde = statsmodels.nonparametric.api.KDEUnivariate(ser) kde.fit(cut=0) x = kde.support y = proportion_observed * kde.density else: x, y = [], [] label = b if i == j == 0 else '' ax.plot(x, y, label=label, alpha=0.7) ax.yaxis.set_major_locator(ticker.NullLocator()) if ax.is_first_row(): ax.set_title(f'{model.capitalize()} model', fontdict=dict(fontsize='medium')) if ax.is_last_row(): ax.set_xlim(left=0) ax.set_xlabel('extinction time (y)') if ax.is_first_col(): ylabel = '\ndensity' if i == 1 else '' ax.set_ylabel(f'SAT{SAT}{ylabel}') leg = fig.legend(loc='center left', bbox_to_anchor=(0.8, 0.5), title='Birth seasonal\ncoefficient of\nvariation') fig.tight_layout(rect=(0, 0, 0.82, 1))