我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pylab.savefig()。
def plot_rgb(image, name, label=None, label_color='w', label_size='large'): """ This will plot the r,g,b channels of an *image* of shape (N,M,3) or (N,M,4). *name* is the prefix of the file name, which will be supplemented with "_rgb.png." *label*, *label_color* and *label_size* may also be specified. """ import pylab Nvec = image.shape[0] image[np.isnan(image)] = 0.0 if image.shape[2] >= 4: image = image[:,:,:3] pylab.clf() pylab.gcf().set_dpi(100) pylab.gcf().set_size_inches((Nvec/100.0, Nvec/100.0)) pylab.gcf().subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0.0, hspace=0.0) pylab.imshow(image, interpolation='nearest') if label is not None: pylab.text(20, 20, label, color = label_color, size=label_size) pylab.savefig("%s_rgb.png" % name) pylab.clf()
def view_trigger_snippets_bis(trigger_snippets, elec_index, save=None): fig = pylab.figure() ax = fig.add_subplot(1, 1, 1) for n in xrange(0, trigger_snippets.shape[2]): y = trigger_snippets[:, elec_index, n] x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1) b = 0.5 + 0.5 * numpy.random.rand() ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid') ax.grid(True) ax.set_xlim([numpy.amin(x), numpy.amax(x)]) ax.set_xlabel("time") ax.set_ylabel("amplitude") if save is None: pylab.show() else: pylab.savefig(save) pylab.close(fig) return
def view_loss_curve(losss, title=None, save=None): '''Plot loss curve''' x_min = 1 x_max = len(losss) - 1 fig = pylab.figure() ax = fig.gca() ax.semilogy(range(x_min, x_max + 1), losss[1:], color='blue', linestyle='solid') ax.grid(True, which='both') if title is None: ax.set_title("Loss curve") else: ax.set_title(title) ax.set_xlabel("iteration") ax.set_ylabel("loss") ax.set_xlim([x_min - 1, x_max + 1]) if save is None: pylab.show() else: pylab.savefig(save) pylab.close(fig) return
def plot_labeled_images_random(image_list, label_list, categories, n, title_str, ypixels, xpixels, seed, filename): random.seed(seed) index_sample = random.sample(range(len(image_list)), n) plt.figure(figsize=(2*n, 2)) #plt.suptitle(title_str) for i, ind in enumerate(index_sample): ax = plt.subplot(1, n, i + 1) plt.imshow(image_list[ind].reshape(ypixels, xpixels)) plt.gray() ax.set_title(categories[label_list[ind]], fontsize=20) ax.get_xaxis().set_visible(False); ax.get_yaxis().set_visible(False) if 1: pylab.savefig(filename, bbox_inches='tight') else: plt.show() # plot_unlabeled_images_random: plots unlabeled images at random
def plot_unlabeled_images_random(image_list, n, title_str, ypixels, xpixels, seed, filename): random.seed(seed) index_sample = random.sample(range(len(image_list)), n) plt.figure(figsize=(2*n, 2)) plt.suptitle(title_str) for i, ind in enumerate(index_sample): ax = plt.subplot(1, n, i + 1) plt.imshow(image_list[ind].reshape(ypixels, xpixels)) plt.gray() ax.get_xaxis().set_visible(False); ax.get_yaxis().set_visible(False) if 1: pylab.savefig(filename, bbox_inches='tight') else: plt.show() # plot_compare: given test images and their reconstruction, we plot them for visual comparison
def plot_compare(x_test, decoded_imgs, filename): n = 10 plt.figure(figsize=(2*n, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, n, i + 1 + n) plt.imshow(decoded_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) if 1: pylab.savefig(filename, bbox_inches='tight') else: plt.show() # plot_img: plots greyscale image
def display_results_figure(results, METRIC): import pylab as pb color = iter(pb.cm.rainbow(np.linspace(0, 1, len(results)))) plots = [] for method in results.keys(): x = [] y = [] for train_perc in sorted(results[method].keys()): x.append(train_perc) y.append(results[method][train_perc][0]) c = next(color) (pi, ) = pb.plot(x, y, color=c) plots.append(pi) from matplotlib.font_manager import FontProperties fontP = FontProperties() fontP.set_size('small') pb.legend(plots, map(method_name_mapper, results.keys()), prop=fontP, bbox_to_anchor=(0.6, .65)) pb.xlabel('#Tweets from target rumour for training') pb.ylabel('Accuracy') pb.title(METRIC.__name__) pb.savefig('incrementing_training_size.png')
def display_data(word_vectors, words, target_words=None): target_matrix = word_vectors.copy() if target_words: target_words = [line.strip().lower() for line in open(target_words)][:2000] rows = [words.index(word) for word in target_words if word in words] target_matrix = target_matrix[rows,:] else: rows = np.random.choice(len(word_vectors), size=1000, replace=False) target_matrix = target_matrix[rows,:] reduced_matrix = tsne(target_matrix, 2); Plot.figure(figsize=(200, 200), dpi=100) max_x = np.amax(reduced_matrix, axis=0)[0] max_y = np.amax(reduced_matrix, axis=0)[1] Plot.xlim((-max_x,max_x)) Plot.ylim((-max_y,max_y)) Plot.scatter(reduced_matrix[:, 0], reduced_matrix[:, 1], 20); for row_id in range(0, len(rows)): target_word = words[rows[row_id]] x = reduced_matrix[row_id, 0] y = reduced_matrix[row_id, 1] Plot.annotate(target_word, (x,y)) Plot.savefig("word_vectors.png");
def on_epoch_end(self, epoch, logs={}): self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % epoch)) self.show_edit_distance(256) word_batch = next(self.text_img_gen)[0] res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words]) for i in range(self.num_display_words): pylab.subplot(self.num_display_words, 1, i + 1) if K.image_dim_ordering() == 'th': the_input = word_batch['the_input'][i, 0, :, :] else: the_input = word_batch['the_input'][i, :, :, 0] pylab.imshow(the_input, cmap='Greys_r') pylab.xlabel('Truth = \'%s\' Decoded = \'%s\'' % (word_batch['source_str'][i], res[i])) fig = pylab.gcf() fig.set_size_inches(10, 12) pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % epoch)) pylab.close() # Input Parameters
def plot_evaluation_episode_reward(): pylab.clf() sns.set_context("poster") pylab.plot(0, 0) episodes = [0] average_scores = [0] median_scores = [0] for n in xrange(len(csv_evaluation)): params = csv_evaluation[n] episodes.append(params[0]) average_scores.append(params[1]) median_scores.append(params[2]) pylab.plot(episodes, average_scores, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("average score") pylab.savefig("%s/evaluation_episode_average_reward.png" % args.plot_dir) pylab.clf() pylab.plot(0, 0) pylab.plot(episodes, median_scores, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("median score") pylab.savefig("%s/evaluation_episode_median_reward.png" % args.plot_dir)
def plot(self, filename): r"""Save an image file of the transfer function. This function loads up matplotlib, plots the transfer function and saves. Parameters ---------- filename : string The file to save out the plot as. Examples -------- >>> tf = TransferFunction( (-10.0, -5.0) ) >>> tf.add_gaussian(-9.0, 0.01, 1.0) >>> tf.plot("sample.png") """ import matplotlib matplotlib.use("Agg") import pylab pylab.clf() pylab.plot(self.x, self.y, 'xk-') pylab.xlim(*self.x_bounds) pylab.ylim(0.0, 1.0) pylab.savefig(filename)
def save(GUI): global txtResultPath if GUI: import pylab as pl import nest.raster_plot import nest.voltage_trace for key in spikedetectors: try: nest.raster_plot.from_device(spikedetectors[key], hist=True) pl.savefig(f_name_gen("", "spikes_" + key.lower()), dpi=dpi_n, format='png') pl.close() except Exception: print(" * * * from {0} is NOTHING".format(key)) txtResultPath = 'txt/' logger.debug("Saving TEXT into {0}".format(txtResultPath)) if not os.path.exists(txtResultPath): os.mkdir(txtResultPath) for key in spikedetectors: save_spikes(spikedetectors[key], name=key) with open(txtResultPath + 'timeSimulation.txt', 'w') as f: for item in times: f.write(item)
def on_epoch_end(self, epoch, logs={}): self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch))) self.show_edit_distance(256) word_batch = next(self.text_img_gen)[0] res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words]) if word_batch['the_input'][0].shape[0] < 256: cols = 2 else: cols = 1 for i in range(self.num_display_words): pylab.subplot(self.num_display_words // cols, cols, i + 1) if K.image_dim_ordering() == 'th': the_input = word_batch['the_input'][i, 0, :, :] else: the_input = word_batch['the_input'][i, :, :, 0] pylab.imshow(the_input.T, cmap='Greys_r') pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i])) fig = pylab.gcf() fig.set_size_inches(10, 13) pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch))) pylab.close()
def tile_images(image_batch, image_width=28, image_height=28, image_channel=1, dir=None, filename="images"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() pylab.gray() for m in range(100): pylab.subplot(10, 10, m + 1) pylab.imshow(image_batch[m].reshape((image_width, image_height)), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
def scatter_labeled_z(z_batch, label_batch, filename="labeled_z"): fig = pylab.gcf() fig.set_size_inches(20.0, 16.0) pylab.clf() colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"] for n in range(z_batch.shape[0]): result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none') classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] recs = [] for i in range(0, len(colors)): recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i])) ax = pylab.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5)) pylab.xticks(pylab.arange(-4, 5)) pylab.yticks(pylab.arange(-4, 5)) pylab.xlabel("z1") pylab.ylabel("z2") pylab.savefig(filename)
def visualize_bin_list(self, bin_list, path): """ Will create a histogram of all bin_list entries and save it to the specified path """ # TODO use savelogic here for jj, bin_entry in enumerate(bin_list): hist_x, hist_y = self._traceanalysis_logic.calculate_histogram(bin_entry, num_bins=50) pb.plot(hist_x[0:len(hist_y)], hist_y) fname = 'bin_' + str(jj) + '.png' savepath = os.path.join(path, fname) pb.savefig(savepath) pb.close() # ========================================================================= # Connecting to GUI # ========================================================================= # absolutely not working at the moment.
def stat_personal(self): if not os.path.exists(self.file_path + self.ip.ip): os.mkdir(self.file_path + self.ip.ip) print('make dir %s' % self.ip.ip) try: items = self.ip.info_set.count() except: return 0 my_info = Info.objects.filter(ip = self.ip).order_by('date') dates = list(range(len(my_info))) bmis = [info.get_bmi() for info in my_info] pl.figure('my', figsize = (5.2, 2.8), dpi = 100) pl.plot(dates, bmis, '*-', color = '#20b2aa', linewidth = 1.5) pl.ylabel(u'BMI?', fontproperties = zhfont) pl.ylim(0.0, 50.0) pl.savefig(self.file_path + self.ip.ip + '/my.jpg') pl.cla() return items
def show_results(self): pl.plot(self.t1, self.n_A1, 'b--', label='A1: Time Step = 0.05') pl.plot(self.t1, self.n_B1, 'b', label='B1: Time Step = 0.05') pl.plot(self.t2, self.n_A2, 'g--', label='A2: Time Step = 0.1') pl.plot(self.t2, self.n_B2, 'g', label='B2: Time Step = 0.1') pl.plot(self.t1, self.n_A1_true, 'r--', label='True A1: Time Step = 0.05') pl.plot(self.t1, self.n_B1_true, 'r', label='True B1: Time Step = 0.05') pl.plot(self.t2, self.n_A2_true, 'c--', label='True A2: Time Step = 0.1') pl.plot(self.t2, self.n_B2_true, 'c', label='True B2: Time Step = 0.1') pl.title('Double Decay Probelm-Approximation Compared with True in Defferent Time Steps') pl.xlim(0.0, 0.1) pl.ylim(0.0, 100.0) pl.xlabel('time ($s$)') pl.ylabel('Number of Nuclei') pl.legend(loc='best', shadow=True, fontsize='small') pl.grid(True) pl.savefig("computational_physics homework 4(improved-7).png")
def plotdata(obsmode,spectrum,val,odict,sdict, instr,fieldname,outdir,outname): isetting=P.isinteractive() P.ioff() P.clf() P.plot(obsmode,val,'.') P.ylabel('(pysyn-syn)/syn') P.xlabel('obsmode') P.title("%s: %s"%(instr,fieldname)) P.savefig(os.path.join(outdir,outname+'_obsmode.ps')) P.clf() P.plot(spectrum,val,'.') P.ylabel('(pysyn-syn)/syn') P.xlabel('spectrum') P.title("%s: %s"%(instr,fieldname)) P.savefig(os.path.join(outdir,outname+'_spectrum.ps')) matplotlib.interactive(isetting)
def visualize_reconstruction(xp, model, x, visualization_dir, epoch, gpu=False): x_variable = chainer.Variable(xp.asarray(x)) _x = model.decode(model.encode(x_variable), test=True) _x.to_cpu() _x = _x.data fig = pylab.gcf() fig.set_size_inches(8.0, 8.0) pylab.clf() pylab.gray() for m in range(50): i = m / 10 j = m % 10 pylab.subplot(10, 10, 20 * i + j + 1, xticks=[], yticks=[]) pylab.imshow(x[m].reshape((28, 28)), interpolation="none") pylab.subplot(10, 10, 20 * i + j + 10 + 1, xticks=[], yticks=[]) pylab.imshow(_x[m].reshape((28, 28)), interpolation="none") # pylab.imshow(np.clip((_x_batch.data[m] + 1.0) / 2.0, 0.0, 1.0).reshape( # (config.img_channel, config.img_width, config.img_width)), interpolation="none") pylab.axis("off") pylab.savefig("{}/reconstruction_{}.png".format(visualization_dir, epoch)) # pylab.show()
def plot_kde(data, dir=None, filename="kde", color="Greens"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() bg_color = sns.color_palette(color, n_colors=256)[0] ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2) ax.set_axis_bgcolor(bg_color) kde = ax.get_figure() pylab.xlim(-4, 4) pylab.ylim(-4, 4) kde.savefig("{}/{}.png".format(dir, filename))
def plot_kde(data, dir=None, filename="kde", color="Greens"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() bg_color = sns.color_palette(color, n_colors=256)[0] ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2) ax.set_axis_bgcolor(bg_color) kde = ax.get_figure() pylab.xlim(-4, 4) pylab.ylim(-4, 4) kde.savefig("{}/{}".format(dir, filename))
def tile_binary_images(x, dir=None, filename="x", row=10, col=10): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(col * 2, row * 2) pylab.clf() pylab.gray() for m in range(row * col): pylab.subplot(row, col, m + 1) pylab.imshow(np.clip(x[m], 0, 1), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
def main(): data = pd.read_table('../Real_Values.txt').get_values() x = [float(d) for d in data] test = np.array([669, 592, 664, 1005, 699, 401, 646, 472, 598, 681, 1126, 1260, 562, 491, 714, 530, 521, 687, 776, 802, 499, 536, 871, 801, 965, 768, 381, 497, 458, 699, 549, 427, 358, 219, 635, 756, 775, 969, 598, 630, 649, 722, 835, 812, 724, 966, 778, 584, 697, 737, 777, 1059, 1218, 848, 713, 884, 879, 1056, 1273, 1848, 780, 1206, 1404, 1444, 1412, 1493, 1576, 1178, 836, 1087, 1101, 1082, 775, 698, 620, 651, 731, 906, 958, 1039, 1105, 620, 576, 707, 888, 1052, 1072, 1357, 768, 986, 816, 889, 973, 983, 1351, 1266, 1053, 1879, 2085, 2419, 1880, 2045, 2212, 1491, 1378, 1524, 1231, 1577, 2459, 1848, 1506, 1589, 1386, 1111, 1180, 1075, 1595, 1309, 2092, 1846, 2321, 2036, 3587, 1637, 1416, 1432, 1110, 1135, 1233, 1439, 894, 628, 967, 1176, 1069, 1193, 1771, 1199, 888, 1155, 1254, 1403, 1502, 1692, 1187, 1110, 1382, 1808, 2039, 1810, 1819, 1408, 803, 1568, 1227, 1270, 1268, 1535, 873, 1006, 1328, 1733, 1352, 1906, 2029, 1734, 1314, 1810, 1540, 1958, 1420, 1530, 1126, 721, 771, 874, 997, 1186, 1415, 973, 1146, 1147, 1079, 3854, 3407, 2257, 1200, 734, 1051, 1030, 1370, 2422, 1531, 1062, 530, 1030, 1061, 1249, 2080, 2251, 1190, 756, 1161, 1053, 1063, 932, 1604, 1130, 744, 930, 948, 1107, 1161, 1194, 1366, 1155, 785, 602, 903, 1142, 1410, 1256, 742, 985, 1037, 1067, 1196, 1412, 1127, 779, 911, 989, 946, 888, 1349, 1124, 761, 994, 1068, 971, 1157, 1558, 1223, 782, 2790, 1835, 1444, 1098, 1399, 1255, 950, 1110, 1345, 1224, 1092, 1446, 1210, 1122, 1259, 1181, 1035, 1325, 1481, 1278, 769, 911, 876, 877, 950, 1383, 980, 705, 888, 877, 638, 1065, 1142, 1090, 1316, 1270, 1048, 1256, 1009, 1175, 1176, 870, 856, 860]) n_predict = 100 extrapolation = fourierExtrapolation(x, n_predict) pl.figure() pl.plot(np.arange(len(x), len(extrapolation) + len(x)), extrapolation, 'r', label = 'extrapolation') pl.plot(x, 'b', label = 'Given Data', linewidth = 3) pl.legend() pl.ylabel('BPM') pl.xlabel('Sample') pl.title('Fourier Extrapolation') pl.savefig('FourierExtrapolation.png') #pl.show() with open('Fourier_PredValues.txt', 'w') as out: out.write(str([e for e in extrapolation]).strip('[]'))
def tile_binary_images(x, dir=None, filename="x"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() pylab.gray() for m in range(100): pylab.subplot(10, 10, m + 1) pylab.imshow(np.clip(x[m], 0, 1), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
def plot_z(z, dir=None, filename="z", xticks_range=None, yticks_range=None): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() for n in xrange(z.shape[0]): result = pylab.scatter(z[n, 0], z[n, 1], s=40, marker="o", edgecolors='none') pylab.xlabel("z1") pylab.ylabel("z2") if xticks_range is not None: pylab.xticks(pylab.arange(-xticks_range, xticks_range + 1)) if yticks_range is not None: pylab.yticks(pylab.arange(-yticks_range, yticks_range + 1)) pylab.savefig("{}/{}.png".format(dir, filename))
def plot_signals(input_data, filename=None,downsamplefactor=1,n_columns=1): import pylab as pl n_rows = input_data.signal.n_channels() n_rows = int(n_rows/n_columns) print str(n_rows) + ' ' + str(n_columns) for row in range(n_rows): for col in range(n_columns): print (row)*n_columns+col+1 pl.subplot(n_rows, n_columns, row*n_columns+col+1) if downsamplefactor==1: pl.plot(input_data.timebase, input_data.signal.get_channel(row*n_columns+col)) pl.axis([-0.01,0.1,-5, 5]) else: plotdata=input_data.signal.get_channel(row*n_columns+col) timedata=input_data.timebase pl.plot(timedata[0:len(timedata):downsamplefactor], plotdata[0:len(timedata):downsamplefactor]) pl.axis([-0.01,0.1,-5,5]) if filename != None: pl.savefig(filename) else: pl.show()
def visualize_x(reconstructed_x_batch, image_width=28, image_height=28, image_channel=1, dir=None): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() if image_channel == 1: pylab.gray() for m in range(100): pylab.subplot(10, 10, m + 1) if image_channel == 1: pylab.imshow(reconstructed_x_batch[m].reshape((image_width, image_height)), interpolation="none") elif image_channel == 3: pylab.imshow(reconstructed_x_batch[m].reshape((image_channel, image_width, image_height)), interpolation="none") pylab.axis("off") pylab.savefig("%s/reconstructed_x.png" % dir)
def visualize_labeled_z(z_batch, label_batch, dir=None): fig = pylab.gcf() fig.set_size_inches(20.0, 16.0) pylab.clf() colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"] for n in xrange(z_batch.shape[0]): result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none') classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] recs = [] for i in range(0, len(colors)): recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i])) ax = pylab.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5)) pylab.xticks(pylab.arange(-4, 5)) pylab.yticks(pylab.arange(-4, 5)) pylab.xlabel("z1") pylab.ylabel("z2") pylab.savefig("%s/labeled_z.png" % dir)
def hist_weekday(self, tweet_weekday_user, tweet_weekday_bot, path): fig = plt.figure() ax = plt.subplot(111) opacity = 0.4 labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] bar_width = 0.3 x = range(len(tweet_weekday_user["prop"])) plt.xticks([0.3, 1.3, 2.3, 3.3, 4.3, 5.3, 6.3], labels) ax.bar(x, tweet_weekday_user["prop"],bar_width,color='b',alpha=opacity,label='Humans', yerr=tweet_weekday_user["std"]) ax.bar([0.3, 1.3, 2.3, 3.3, 4.3, 5.3, 6.3], tweet_weekday_bot["prop"],bar_width,color='g',alpha=opacity,label='Bots', yerr=tweet_weekday_bot["std"]) ax.set_xlabel('Week days') ax.set_ylabel('Tweets proportion per day (0 to 1)') sns.plt.title('Proportion of tweets for each week day') ax.legend() pl.savefig(path)
def _auto_plots(self,mode,filebasename,figdir,plotargs): """Generate standard plots and write png and and pdf. Chooses filename and plot title.""" import pylab try: os.makedirs(figdir) except OSError,err: if err.errno != errno.EEXIST: raise def figs(*args): return os.path.join(figdir,*args) modefilebasename = filebasename + self._suffix[mode] _plotargs = plotargs.copy() # need a copy because of changing 'title' if plotargs.get('title') is None: # None --> set automatic title _plotargs['title'] = self._title[mode]+' '+self.legend pylab.clf() self.plot(**_plotargs) pylab.savefig(figs(modefilebasename + '.png')) # png pylab.savefig(figs(modefilebasename + '.pdf')) # pdf print "--- Plotted %(modefilebasename)r (png,pdf)." % vars()
def plot_windows_together(db,figname=os.path.join(config.basedir,'figs','pmf','windows.pdf'),stride=10,**plotargs): """Plot windows in one plot; stride selects a subset of windows. Example: >>> PMF.angles.plot_windows_together(db,figname='figs/pmf/all_windows.png',stride=1,alpha=0.3,contour_alpha=0.2,cmap=cm.jet_r) """ import pylab pylab.clf() fn = db.filenames()[::stride] for n,f in enumerate(fn): fb = os.path.basename(f) print "-- %5.1f%% %3d/%3d %s" % (100*(n+1)/len(fn), n, len(fn), fb) # figname=os.path.join('figs','pmf',fb+'.pdf'), s = Selection(db,'filename="%s"' % f) s.plot(clf=False,**plotargs) pylab.title('Umbrella windows') pylab.savefig(str(figname)) print "- Created figure '%(figname)s'." % vars()
def removeIllumination2(self, size, title = ''): out = ndimage.filters.gaussian_filter(self.image, size) pylab.figure() pylab.subplot(2,2,1) pylab.axis('off') pylab.imshow(self.image) pylab.subplot(2,2,2) pylab.axis('off') pylab.imshow(out) pylab.subplot(2,2,3) pylab.axis('off') pylab.imshow(self.image - out) pylab.subplot(2,2,4) pylab.axis('off') pylab.imshow(self.smooth - out) if title != '': pylab.savefig(title) pylab.close() else: pylab.show() self.smooth -= out return self.image - out
def plot(self, outpath=''): pylab.figure(figsize = (17,10)) diff = self.f2-self.f3 pylab.subplot(2,1,1) pylab.plot(range(self.lengthSeq), self.f2, 'r-', label = "f2") pylab.plot(range(self.lengthSeq), self.f3, 'g-', label = "f3") pylab.xlim([0., self.lengthSeq]) pylab.tick_params(axis='both', which='major', labelsize=25) pylab.subplot(2,1,2) diff2 = diff/self.f3 diff2 /= np.max(diff2) pylab.plot(range(self.lengthSeq), diff2, 'b-', label = "Rescaled (by max) difference / f3") pylab.xlabel("Temps (en images)", fontsize = 25) pylab.tick_params(axis='both', which='major', labelsize=25) pylab.xlim([0., self.lengthSeq]) #pylab.legend(loc= 2, prop = {'size':15}) pylab.savefig(outpath) pylab.close()
def draw2D(self, title, image=[]): pylab.figure() if image == []: pylab.imshow(self.image, 'gray') else: pylab.imshow(image, 'gray') pylab.axis('off') pylab.autoscale(False) for i in xrange(self.nComponents): xeq = lambda t: self.params[6 * i + 3] * np.cos(t) * np.cos(self.params[6 * i + 5]) + self.params[ 6 * i + 4] * np.sin( t) * np.sin(self.params[6 * i + 5]) + self.params[6 * i + 1] yeq = lambda t: - self.params[6 * i + 3] * np.cos(t) * np.sin(self.params[6 * i + 5]) + self.params[ 6 * i + 4] * np.sin( t) * np.cos(self.params[6 * i + 5]) + self.params[6 * i + 2] t = np.linspace(0, 2 * np.pi, 100) x = xeq(t) y = yeq(t) pylab.scatter(self.params[6 * i + 2], self.params[6 * i + 1], color='k') pylab.plot(y.astype(int), x.astype(int), self.colors[i] + '-') pylab.savefig(title) pylab.close()
def bootstrap_extradata(self, nBoot, extradataA, nbins = 20): pops =[] meanpop = [[] for i in data.cat] pylab.figure(figsize = (14,14)) for i in xrange(min(4, len(extradataA))): #pylab.subplot(2,2,i+1) if i ==0: pylab.title("Bootstrap on means", fontsize = 20.) pop = extradataA[i]# & (self.GFP > 2000)]# for index in xrange(nBoot): newpop = np.random.choice(pop, size=len(pop), replace=True) #meanpop[i].append(np.mean(newpop)) pops.append(newpop) pylab.legend() #pylab.title(cat[i]) pylab.xlabel("Angle(degree)", fontsize = 15) pylab.xlim([0., 90.]) for i in xrange(len(extradataA)): for j in xrange(i+1, len(extradataA)): statT, pvalue = scipy.stats.ttest_ind(pops[i], pops[j], equal_var=False) print "cat{0} & cat{1} get {2} ({3})".format(i,j, pvalue,statT) pylab.savefig("/users/biocomp/frose/frose/Graphics/FINALRESULTS-diff-f3/mean_nBootstrap{0}_bins{1}_GFPsup{2}_FLO_{3}.png".format(nBoot, nbins, 'all', randint(0,999)))
def view_waveforms_clusters(data, halo, threshold, templates, amps_lim, n_curves=200, save=False): nb_templates = templates.shape[1] n_panels = numpy.ceil(numpy.sqrt(nb_templates)) mask = numpy.where(halo > -1)[0] clust_idx = numpy.unique(halo[mask]) fig = pylab.figure() square = True center = len(data[0] - 1)//2 for count, i in enumerate(xrange(nb_templates)): if square: pylab.subplot(n_panels, n_panels, count + 1) if (numpy.mod(count, n_panels) != 0): pylab.setp(pylab.gca(), yticks=[]) if (count < n_panels*(n_panels - 1)): pylab.setp(pylab.gca(), xticks=[]) subcurves = numpy.where(halo == clust_idx[count])[0] for k in numpy.random.permutation(subcurves)[:n_curves]: pylab.plot(data[k], '0.5') pylab.plot(templates[:, count], 'r') pylab.plot(amps_lim[count][0]*templates[:, count], 'b', alpha=0.5) pylab.plot(amps_lim[count][1]*templates[:, count], 'b', alpha=0.5) xmin, xmax = pylab.xlim() pylab.plot([xmin, xmax], [-threshold, -threshold], 'k--') pylab.plot([xmin, xmax], [threshold, threshold], 'k--') #pylab.ylim(-1.5*threshold, 1.5*threshold) ymin, ymax = pylab.ylim() pylab.plot([center, center], [ymin, ymax], 'k--') pylab.title('Cluster %d' %i) if nb_templates > 0: pylab.tight_layout() if save: pylab.savefig(os.path.join(save[0], 'waveforms_%s' %save[1])) pylab.close() else: pylab.show() del fig
def view_artefact(data, save=False): fig = pylab.figure() pylab.plot(data.T) if save: pylab.savefig(os.path.join(save[0], 'artefact_%s' %save[1])) pylab.close() else: pylab.show() del fig
def view_trigger_snippets(trigger_snippets, chans, save=None): # Create output directory if necessary. if os.path.exists(save): for f in os.listdir(save): p = os.path.join(save, f) os.remove(p) os.removedirs(save) os.makedirs(save) # Plot figures. fig = pylab.figure() for (c, chan) in enumerate(chans): ax = fig.add_subplot(1, 1, 1) for n in xrange(0, trigger_snippets.shape[2]): y = trigger_snippets[:, c, n] x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1) b = 0.5 + 0.5 * numpy.random.rand() ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid') y = numpy.mean(trigger_snippets[:, c, :], axis=1) x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1) ax.plot(x, y, color=(1.0, 0.0, 0.0), linestyle='solid') ax.grid(True) ax.set_xlim([numpy.amin(x), numpy.amax(x)]) ax.set_title("Channel %d" %chan) ax.set_xlabel("time") ax.set_ylabel("amplitude") if save is not None: # Save plot. filename = "channel-%d.png" %chan path = os.path.join(save, filename) pylab.savefig(path) fig.clf() if save is None: pylab.show() else: pylab.close(fig) return
def view_mahalanobis_distribution(data_1, data_2, save=None): '''Plot Mahalanobis distribution Before and After''' fig = pylab.figure() ax = fig.add_subplot(1,2,1) if len(data_1) == 3: d_gt, d_ngt, d_noi = data_1 elif len(data_1) == 2: d_gt, d_ngt = data_1 if len(data_1) == 3: ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise") ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT") ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT") ax.grid(True) ax.set_title("Before") ax.set_ylabel("") ax.set_xlabel('# Samples') ax.set_xlabel('Distances') if len(data_2) == 3: d_gt, d_ngt, d_noi = data_2 elif len(data_2) == 2: d_gt, d_ngt = data_2 ax = fig.add_subplot(1,2,2) if len(data_2) == 3: ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise") ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT") ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT") ax.grid(True) ax.set_title("After") ax.set_ylabel("") ax.set_xlabel('Distances') ax.legend() if save is None: pylab.show() else: pylab.savefig(save) pylab.close(fig) return
def plot_intensity_all(self, x, figure_path): sumI = np.array([self.sumIntensitiesAll(xi, self.node_vec, self.etimes, True)[1] for xi in x]) (f_mean, f_lower, f_upper) = (sumI, sumI, sumI) gpplot(x, f_mean, f_lower, f_upper) pb.xlabel('time') pb.ylabel('intensity lambda over all memes and users') pb.savefig(figure_path)
def main(argv=None): if argv is None: argv = sys.argv parser = ArgumentParser('Create plot of the Kp and Dst indices.', formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('pdf_fname', type=str, help='file to store plot') parser.add_argument('d1', type=dt_parser, help='start date/time') parser.add_argument('d2', type=dt_parser, help='end date/time') parser.add_argument('--style', '-s', type=str, choices=sorted(STYLE_MAP), default='display', help='plot style (display is more colorful and meant for screen display whereas document is high contrast and uses hatches for both color and black-white interpretation and meant for use in publication)') args = parser.parse_args(argv[1:]) plot_indices(args.d1, args.d2, style=args.style) PL.savefig(args.pdf_fname, bbox_inches='tight')
def main(): # Read the example RT structure and RT dose files # The testdata was downloaded from the dicompyler website as testdata.zip # Obtain the structures and DVHs from the DICOM data rtssfile = 'testdata/rtss.dcm' rtdosefile = 'testdata/rtdose.dcm' RTss = dicomparser.DicomParser(rtssfile) #RTdose = dicomparser.DicomParser("testdata/rtdose.dcm") RTstructures = RTss.GetStructures() # Generate the calculated DVHs calcdvhs = {} for key, structure in RTstructures.iteritems(): calcdvhs[key] = dvhcalc.get_dvh(rtssfile, rtdosefile, key) if (key in calcdvhs) and (len(calcdvhs[key].counts) and calcdvhs[key].counts[0]!=0): print ('DVH found for ' + structure['name']) pl.plot(calcdvhs[key].counts * 100/calcdvhs[key].counts[0], color=dvhcalc.np.array(structure['color'], dtype=float) / 255, label=structure['name'], linestyle='dashed') #else: # print("%d: no DVH"%key) pl.xlabel('Distance (cm)') pl.ylabel('Percentage Volume') pl.legend(loc=7, borderaxespad=-5) pl.setp(pl.gca().get_legend().get_texts(), fontsize='x-small') pl.savefig('testdata/dvh.png', dpi = 75)