我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.subplots_adjust()。
def save_ims(filename, ims, dpi=100, scale=0.5): n, c, h, w = ims.shape rows = int(math.ceil(math.sqrt(n))) cols = int(round(math.sqrt(n))) fig, axes = plt.subplots(rows, cols, figsize=(w*cols/dpi*scale, h*rows/dpi*scale), dpi=dpi) for i, ax in enumerate(axes.flat): if i < n: ax.imshow(ims[i].transpose((1, 2, 0))) ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0.1, hspace=0.1) plt.savefig(filename, dpi=dpi, bbox_inces='tight', transparent=True) plt.clf() plt.close()
def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'): words = [(i, vocab[i]) for i in s] model = TSNE(n_components=2, random_state=0) #Note that the following line might use a good chunk of RAM tsne_embedding = model.fit_transform(word_embedding_matrix) words_vectors = tsne_embedding[np.array([item[1] for item in words])] plt.subplots_adjust(bottom = 0.1) plt.scatter( words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral')) for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]): plt.annotate( label, xy=(x, y), xytext=(-20, 20), textcoords='offset points', ha='right', va='bottom', fontsize=20, # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0') ) plt.show() # plt.savefig(save_file)
def draw_images(img, undistorted, title, cmap): f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9)) f.tight_layout() ax1.imshow(img) ax1.set_title('Original Image', fontsize=50) if cmap is not None: ax2.imshow(undistorted, cmap=cmap) else: ax2.imshow(undistorted) ax2.set_title(title, fontsize=50) plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.) plt.show() # TODO: Write a function that takes an image, object points, and image points # performs the camera calibration, image distortion correction and # returns the undistorted image
def init_plot(self): # Interactive mode plt.ion() # Chart size and margins plt.figure(figsize = (20, 10)) plt.subplots_adjust(hspace = 0.05, top = 0.95, bottom = 0.1, left = 0.05, right = 0.95) # Setup axis labels and ranges plt.title('Pico Technology TC-08') plt.xlabel('Time [s]') plt.ylabel('Temperature [' + self.unit_text + ']') plt.xlim(0, self.duration) self.plotrangemin = 19 self.plotrangemax = 21 plt.ylim(self.plotrangemin, self.plotrangemax) # Enable a chart line for each channel self.lines = [] for i in CHANNEL_CONFIG: if CHANNEL_CONFIG.get(i) != ' ': self.lines.append(line(plt, CHANNEL_NAME.get(i))) else: self.lines.append(line(plt, 'Channel {:d} OFF'.format(i))) # Plot the legend plt.legend(loc = 'best', fancybox = True, framealpha = 0.5) plt.draw()
def create_plot(json_data, output): all_data = pd.DataFrame(json_data) df = all_data[all_data['ProductDescription'] == 'Linux/UNIX'] df = df.drop_duplicates(subset=['DateTime', 'AvailabilityZone', 'InstanceType']) x_min = df['DateTime'].min() x_max = df['DateTime'].max() border_pad = (x_max - x_min) * 5 / 100 g = sns.FacetGrid( df, col='InstanceType', hue='AvailabilityZone', xlim=(x_min - border_pad, x_max + border_pad), legend_out=True, size=10, palette="Set1" ) g.map(plt.scatter, 'DateTime', 'SpotPrice', s=4).add_legend() plt.subplots_adjust(top=.9) g.fig.suptitle('AWS Spot Prices between {start} and {end}'.format(start=x_min, end=x_max)) g.savefig(output, format='png')
def visualize_weights(W, outfile): # ????????? W = (W - np.min(W)) / (np.max(W) - np.min(W)) W *= 255.0 W = W.astype(np.int) pos = 1 for i in range(100): plt.subplot(10, 10, pos) plt.subplots_adjust(wspace=0, hspace=0) plt.imshow(W[i].reshape(28, 28)) plt.gray() plt.axis('off') pos += 1 plt.show() plt.savefig(outfile)
def create_chart(self, top, others): plt.clf() sizes = [x[1] for x in top] labels = ["{} {:g}%".format(x[0], x[1]) for x in top] if len(top) >= 10: sizes = sizes + [others] labels = labels + ["Others {:g}%".format(others)] title = plt.title('User activity in the last 5000 messages') title.set_va("top") title.set_ha("left") plt.gca().axis("equal") colors = ['r', 'darkorange', 'gold', 'y', 'olivedrab', 'green', 'darkcyan', 'mediumblue', 'darkblue', 'blueviolet', 'indigo'] pie = plt.pie(sizes, colors=colors, startangle=0) plt.legend(pie[0], labels, bbox_to_anchor=(0.7, 0.5), loc="center", fontsize=10, bbox_transform=plt.gcf().transFigure) plt.subplots_adjust(left=0.0, bottom=0.1, right=0.45) image_object = BytesIO() plt.savefig(image_object, format='PNG') image_object.seek(0) return image_object
def scatter_regresion_Plot(X, Y, testName): plt.scatter(X, Y, c = 'b', label = '_nolegend_', s = 1) X = X.reshape(-1, 1) Y = Y.reshape(-1, 1) R2 = r2_score(X, Y) regr = linear_model.LinearRegression() regr.fit(X, Y) plt.plot(X, regr.predict(X), "--", label = 'Regression', color = 'r') plt.title(testName + ' ($R^2$: ' + "{0:.3f}".format(R2) + ")", fontsize = 14) plt.xlabel('True Values', fontsize = 12, weight = 'bold') plt.ylabel('Predicted Values', fontsize = 12, weight = 'bold') plt.legend(loc = 'upper left', bbox_to_anchor = (0, 1.0), fancybox = True, shadow = True, fontsize = 10) plt.subplots_adjust(left = 0.2, right = 0.9, bottom = 0.05, top = 0.97, wspace = 0.15, hspace = 0.3)
def visualize(generated_images, epoch): col, row = 8, 8 fig, axes = plt.subplots(row, col, sharex=True, sharey=True) #images = np.squeeze(generated_images, axis=(-1,))*127.5 images = generated_images*127.5 + 127.5 #images = generated_images*255.0 for i, array in enumerate(images): image = Image.fromarray(array.astype(np.uint8)) ax = axes[int(i/col), int(i%col)] ax.axis("off") ax.imshow(image) plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0.2) #plt.pause(.01) #plt.show() plt.savefig("image_{}.png".format(epoch)) # ==================== # Data Loader # ====================
def visualize(generated_images, epoch): col, row = 8, 8 fig, axes = plt.subplots(row, col, sharex=True, sharey=True) images = np.squeeze(generated_images, axis=(-1,))*255.5 for i, array in enumerate(images): image = Image.fromarray(array) ax = axes[int(i/col), int(i%col)] ax.axis("off") ax.imshow(image) plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0.2) #plt.pause(.01) #plt.show() plt.savefig("image_{}.png".format(epoch)) # Generator
def plot_MNIST_results(): matplotlib.rcParams.update({'font.size': 10}) fig = plt.figure(figsize=(6,4), dpi=100) ll_1hl = [-92.17,-90.69,-89.86,-89.16,-88.61,-88.25,-87.95,-87.71] ll_2hl = [-89.17, -87.96, -87.10, -86.41, -85.96, -85.60, -85.28, -85.10] x = np.arange(len(ll_1hl)) plt.axhline(y=-84.55, color="black", linestyle="--", label="2hl-DBN") plt.axhline(y=-86.34, color="black", linestyle="-.", label="RBM") plt.axhline(y=-88.33, color="black", linestyle=":", label="NADE (fixed order)") plt.plot(ll_1hl, "r^-", label="1hl-NADE") plt.plot(ll_2hl, "go-", label="2hl-NADE") plt.xticks(x, 2**x) plt.xlabel("Models averaged") plt.ylabel("Test loglikelihood (nats)") plt.legend(loc=4, prop = {"size":10}) plt.subplots_adjust(left=0.12, right=0.95, top=0.97, bottom=0.10) plt.savefig(os.path.join(DESTINATION_PATH, "likelihoodvsorderings.pdf"))
def plot_examples(nade, dataset, shape, name, rows=5, cols=10): #Show some samples images = list() for row in xrange(rows): for i in xrange(cols): nade.setup_n_orderings(n=1) sample = dataset.sample_data(1)[0].T dens = nade.logdensity(sample) images.append((sample, dens)) images.sort(key=lambda x: -x[1]) plt.figure(figsize=(0.5*cols,0.5*rows), dpi=100) plt.gray() for row in xrange(rows): for col in xrange(cols): i = row*cols+col sample, dens = images[i] plt.subplot(rows, cols, i+1) plot_sample(np.resize(sample, np.prod(shape)).reshape(shape), shape, origin="upper") plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01, hspace=0.04, wspace=0.04) type_1_font() plt.savefig(os.path.join(DESTINATION_PATH, name))
def plot_samples(nade, shape, name, rows=5, cols=10): #Show some samples images = list() for row in xrange(rows): for i in xrange(cols): nade.setup_n_orderings(n=1) sample = nade.sample(1)[:,0] dens = nade.logdensity(sample[:, np.newaxis]) images.append((sample, dens)) images.sort(key=lambda x: -x[1]) plt.figure(figsize=(0.5*cols,0.5*rows), dpi=100) plt.gray() for row in xrange(rows): for col in xrange(cols): i = row*cols+col sample, dens = images[i] plt.subplot(rows, cols, i+1) plot_sample(np.resize(sample, np.prod(shape)).reshape(shape), shape, origin="upper") plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01, hspace=0.04, wspace=0.04) type_1_font() plt.savefig(os.path.join(DESTINATION_PATH, name)) #plt.show()
def inpaint_digits_(dataset, shape, model, n_examples = 5, delete_shape = (10,10), n_samples = 5, name = "inpaint_digits"): #Load a few digits from the test dataset (as rows) data = dataset.sample_data(1000)[0] #data = data[[1,12,17,81,88,102],:] data = data[range(20,40),:] n_examples = data.shape[0] #Plot it all matplotlib.rcParams.update({'font.size': 8}) plt.figure(figsize=(5,5), dpi=100) plt.gray() cols = 2 + n_samples for row in xrange(n_examples): # Original plt.subplot(n_examples, cols, row*cols+1) plot_sample(data[row,:], shape, origin="upper") plt.subplots_adjust(left=0.01, right=0.99, top=0.95, bottom=0.01, hspace=0.40, wspace=0.04) plt.savefig(os.path.join(DESTINATION_PATH, "kk.pdf"))
def draw_dual_line_graph(title, x_label, y_label, y_axis_1, y_axis_2, line_1_label, line_2_label, output_path): x_axis = np.arange(0, len(y_axis_1)) fig = plt.figure() fig.suptitle(title, fontsize=14, fontweight='bold') ax = fig.add_subplot(111) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.plot(x_axis, y_axis_1, 'b') ax.plot(x_axis, y_axis_2, 'g', alpha=0.7) ax.legend([line_1_label, line_2_label], loc='center', bbox_to_anchor=(0.5, -0.18), ncol=2) ax.axis([0, np.amax(x_axis), 0, np.log(2) + .001]) plt.margins(0.2) plt.tick_params(labelsize=10) fig.subplots_adjust(bottom=0.2) plt.savefig(output_path + '.eps', format='eps') plt.savefig(output_path) plt.close(fig)
def draw_dist_graph(clique_name, **kwargs): if not os.path.exists(kwargs['output_dir'] + clique_name + '.png'): try: doc_vector = kwargs['doc_vecs'][clique_name] except KeyError: return print('Drawing probability distribution graph for ' + clique_name) x_axis = [topic_id + 1 for topic_id, dist in enumerate(doc_vector)] y_axis = [dist for topic_id, dist in enumerate(doc_vector)] plt.bar(x_axis, y_axis, width=1, align='center', color='r') plt.xlabel('Topics') plt.ylabel('Probability') plt.title('Topic Distribution for clique') plt.xticks(np.arange(2, len(x_axis), 2), rotation='vertical', fontsize=7) plt.subplots_adjust(bottom=0.2) plt.ylim([0, np.max(y_axis) + .01]) plt.xlim([0, len(x_axis) + 1]) plt.savefig(kwargs['output_dir'] + clique_name) plt.close()
def draw_user_to_clique_graphs(distance_dir, dist_file): if not os.path.exists(distance_dir + dist_file + '.png'): print('Drawing community members distance from clique for: ' + dist_file) df = pd.read_csv(distance_dir + dist_file, sep='\t', header=None, names=['user', 'clique', 'distance']) x_axis = [str(row['user']) for idx, row in df.iterrows()] y_axis = [float(row['distance']) for idx, row in df.iterrows()] plt.figure(figsize=(20, 10)) plt.bar(np.arange(1, len(x_axis) + 1, 1), y_axis, width=1, align='center', color='r') plt.xlabel('Community Users') plt.ylabel('Divergence from Clique') plt.title('Distances from ' + dist_file + ' to the clique where grown from', fontsize=14, fontweight='bold') plt.xticks(np.arange(0, len(x_axis) + 1, 2), np.arange(0, len(x_axis) + 1, 2), rotation='vertical', fontsize=8) plt.subplots_adjust(bottom=0.2) plt.ylim([0, np.log(2) + .01]) plt.xlim([0, len(x_axis) + 1]) plt.savefig(distance_dir + dist_file) plt.close()
def matploit(data): plt.figure(figsize=(8,5), dpi=80) plt.subplot(1,1,1) plt.grid() plt.subplots_adjust(top=0.9) X = [i for i in range(len(data))] plt.scatter(X,data,color="r") plt.xlim(0.0,len(data)) #plt.xticks(np.linspace(1.0,4.0,7,endpoint=True)) plt.ylim(0,max(data)+1) #plt.yticks(np.linspace(0.0,18,7,endpoint=True)) plt.xlabel("Link number") plt.ylabel("Similarity") plt.show()
def save_ims(filename, ims, dpi=100): n, c, w, h = ims.shape x_plots = math.ceil(math.sqrt(n)) y_plots = x_plots if n % x_plots == 0 else x_plots - 1 plt.figure(figsize=(w*x_plots/dpi, h*y_plots/dpi), dpi=dpi) for i, im in enumerate(ims): plt.subplot(y_plots, x_plots, i+1) if c == 1: plt.imshow(im[0]) else: plt.imshow(im.transpose((1, 2, 0))) plt.axis('off') plt.gca().set_xticks([]) plt.gca().set_yticks([]) plt.gray() plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) plt.savefig(filename, dpi=dpi*2, facecolor='black') plt.clf() plt.close()
def plot_bad_images(images): """This takes a list of images misclassified by a pretty good neural network --- one achieving over 93 percent accuracy --- and turns them into a figure.""" bad_image_indices = [8, 18, 33, 92, 119, 124, 149, 151, 193, 233, 241, 247, 259, 300, 313, 321, 324, 341, 349, 352, 359, 362, 381, 412, 435, 445, 449, 478, 479, 495, 502, 511, 528, 531, 547, 571, 578, 582, 597, 610, 619, 628, 629, 659, 667, 691, 707, 717, 726, 740, 791, 810, 844, 846, 898, 938, 939, 947, 956, 959, 965, 982, 1014, 1033, 1039, 1044, 1050, 1055, 1107, 1112, 1124, 1147, 1181, 1191, 1192, 1198, 1202, 1204, 1206, 1224, 1226, 1232, 1242, 1243, 1247, 1256, 1260, 1263, 1283, 1289, 1299, 1310, 1319, 1326, 1328, 1357, 1378, 1393, 1413, 1422, 1435, 1467, 1469, 1494, 1500, 1522, 1523, 1525, 1527, 1530, 1549, 1553, 1609, 1611, 1634, 1641, 1676, 1678, 1681, 1709, 1717, 1722, 1730, 1732, 1737, 1741, 1754, 1759, 1772, 1773, 1790, 1808, 1813, 1823, 1843, 1850, 1857, 1868, 1878, 1880, 1883, 1901, 1913, 1930, 1938, 1940, 1952, 1969, 1970, 1984, 2001, 2009, 2016, 2018, 2035, 2040, 2043, 2044, 2053, 2063, 2098, 2105, 2109, 2118, 2129, 2130, 2135, 2148, 2161, 2168, 2174, 2182, 2185, 2186, 2189, 2224, 2229, 2237, 2266, 2272, 2293, 2299, 2319, 2325, 2326, 2334, 2369, 2371, 2380, 2381, 2387, 2393, 2395, 2406, 2408, 2414, 2422, 2433, 2450, 2488, 2514, 2526, 2548, 2574, 2589, 2598, 2607, 2610, 2631, 2648, 2654, 2695, 2713, 2720, 2721, 2730, 2770, 2771, 2780, 2863, 2866, 2896, 2907, 2925, 2927, 2939, 2995, 3005, 3023, 3030, 3060, 3073, 3102, 3108, 3110, 3114, 3115, 3117, 3130, 3132, 3157, 3160, 3167, 3183, 3189, 3206, 3240, 3254, 3260, 3280, 3329, 3330, 3333, 3383, 3384, 3475, 3490, 3503, 3520, 3525, 3559, 3567, 3573, 3597, 3598, 3604, 3629, 3664, 3702, 3716, 3718, 3725, 3726, 3727, 3751, 3752, 3757, 3763, 3766, 3767, 3769, 3776, 3780, 3798, 3806, 3808, 3811, 3817, 3821, 3838, 3848, 3853, 3855, 3869, 3876, 3902, 3906, 3926, 3941, 3943, 3951, 3954, 3962, 3976, 3985, 3995, 4000, 4002, 4007, 4017, 4018, 4065, 4075, 4078, 4093, 4102, 4139, 4140, 4152, 4154, 4163, 4165, 4176, 4199, 4201, 4205, 4207, 4212, 4224, 4238, 4248, 4256, 4284, 4289, 4297, 4300, 4306, 4344, 4355, 4356, 4359, 4360, 4369, 4405, 4425, 4433, 4435, 4449, 4487, 4497, 4498, 4500, 4521, 4536, 4548, 4563, 4571, 4575, 4601, 4615, 4620, 4633, 4639, 4662, 4690, 4722, 4731, 4735, 4737, 4739, 4740, 4761, 4798, 4807, 4814, 4823, 4833, 4837, 4874, 4876, 4879, 4880, 4886, 4890, 4910, 4950, 4951, 4952, 4956, 4963, 4966, 4968, 4978, 4990, 5001, 5020, 5054, 5067, 5068, 5078, 5135, 5140, 5143, 5176, 5183, 5201, 5210, 5331, 5409, 5457, 5495, 5600, 5601, 5617, 5623, 5634, 5642, 5677, 5678, 5718, 5734, 5735, 5749, 5752, 5771, 5787, 5835, 5842, 5845, 5858, 5887, 5888, 5891, 5906, 5913, 5936, 5937, 5945, 5955, 5957, 5972, 5973, 5985, 5987, 5997, 6035, 6042, 6043, 6045, 6053, 6059, 6065, 6071, 6081, 6091, 6112, 6124, 6157, 6166, 6168, 6172, 6173, 6347, 6370, 6386, 6390, 6391, 6392, 6421, 6426, 6428, 6505, 6542, 6555, 6556, 6560, 6564, 6568, 6571, 6572, 6597, 6598, 6603, 6608, 6625, 6651, 6694, 6706, 6721, 6725, 6740, 6746, 6768, 6783, 6785, 6796, 6817, 6827, 6847, 6870, 6872, 6926, 6945, 7002, 7035, 7043, 7089, 7121, 7130, 7198, 7216, 7233, 7248, 7265, 7426, 7432, 7434, 7494, 7498, 7691, 7777, 7779, 7797, 7800, 7809, 7812, 7821, 7849, 7876, 7886, 7897, 7902, 7905, 7917, 7921, 7945, 7999, 8020, 8059, 8081, 8094, 8095, 8115, 8246, 8256, 8262, 8272, 8273, 8278, 8279, 8293, 8322, 8339, 8353, 8408, 8453, 8456, 8502, 8520, 8522, 8607, 9009, 9010, 9013, 9015, 9019, 9022, 9024, 9026, 9036, 9045, 9046, 9128, 9214, 9280, 9316, 9342, 9382, 9433, 9446, 9506, 9540, 9544, 9587, 9614, 9634, 9642, 9645, 9700, 9716, 9719, 9729, 9732, 9738, 9740, 9741, 9742, 9744, 9745, 9749, 9752, 9768, 9770, 9777, 9779, 9792, 9808, 9831, 9839, 9856, 9858, 9867, 9879, 9883, 9888, 9890, 9893, 9905, 9944, 9970, 9982] n = len(bad_image_indices) bad_images = [images[j] for j in bad_image_indices] fig = plt.figure(figsize=(10, 15)) for j in xrange(1, n+1): ax = fig.add_subplot(25, 125, j) ax.matshow(bad_images[j-1], cmap = matplotlib.cm.binary) ax.set_title(str(bad_image_indices[j-1])) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.subplots_adjust(hspace = 1.2) plt.show()
def setMargins(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None): """ Tune the subplot layout via the meanings (and suggested defaults) are:: left = 0.125 # the left side of the subplots of the figure right = 0.9 # the right side of the subplots of the figure bottom = 0.1 # the bottom of the subplots of the figure top = 0.9 # the top of the subplots of the figure wspace = 0.2 # the amount of width reserved for blank space between subplots hspace = 0.2 # the amount of height reserved for white space between subplots The actual defaults are controlled by the rc file """ plt.subplots_adjust(left, bottom, right, top, wspace, hspace) plt.draw_if_interactive()
def plot_route_network_thumbnail(g, map_style=None): width = 512 # pixels height = 300 # pixels scale = 24 dpi = mpl.rcParams["figure.dpi"] width_m = width * scale height_m = height * scale median_lat, median_lon = get_median_lat_lon_of_stops(g) dlat = util.wgs84_height(height_m) dlon = util.wgs84_width(width_m, median_lat) spatial_bounds = { "lon_min": median_lon - dlon, "lon_max": median_lon + dlon, "lat_min": median_lat - dlat, "lat_max": median_lat + dlat } fig = plt.figure(figsize=(width/dpi, height/dpi)) ax = fig.add_subplot(111) plt.subplots_adjust(bottom=0.0, left=0.0, right=1.0, top=1.0) return plot_route_network_from_gtfs(g, ax, spatial_bounds, map_alpha=1.0, scalebar=False, legend=False, map_style=map_style)
def plot_coefficients(classifier, feature_names=hallmark_queries, top_features=11): coef = classifier.coef_.ravel() top_positive_coefficients = np.argsort(coef)[-top_features:] top_negative_coefficients = np.argsort(coef)[:top_features] top_coefficients = np.hstack([top_negative_coefficients, top_positive_coefficients]) # create plot plt.figure(figsize=(15, 5)) colors = ['red' if c < 0 else 'blue' for c in coef[top_coefficients]] plt.bar(np.arange(2 * top_features), coef[top_coefficients], color=colors, align='center') feature_names = np.array(feature_names) plt.xticks(np.arange(0, 2 * top_features), feature_names[top_coefficients], rotation=60, ha='right', fontsize=10, fontweight='bold') plt.ylabel('Relative Coefficient Importance Score', fontsize=10) plt.xlabel('Feature (Keyword) Name', fontsize=15) plt.title('Relative Feature Importance of HoC Dict #1 During SVM Relevance Classification', fontsize=15) plt.subplots_adjust(bottom=0.3) plt.show()
def graphRawFX(): date, bid, ask = np.loadtxt('data/GBPUSD1d.txt', unpack=True, delimiter=',', converters={0: mdates.strpdate2num('%Y%m%d%H%M%S')} ) fig = plt.figure(figsize=(10,7)) ax1 = plt.subplot2grid((40, 40), (0, 0), rowspan=40, colspan=40) ax1.plot(date, bid) ax1.plot(date, ask) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S')) for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) ax1_2 = ax1.twinx() ax1_2.fill_between(date, 0, (ask-bid), facecolor='g', alpha=.3) plt.subplots_adjust(bottom=.23) plt.grid(True) plt.show()
def hstack_plots(spacing=0, sharex=False, sharey = True, grid=False, show_x=True, show_y='once', clip_x=False, clip_y=False, remove_ticks = True, xlabel=None, ylabel=None, xlim=None, ylim=None, **adjust_kwargs): with CaptureNewSubplots() as cap: with _define_plot_settings(layout='h', show_y = False if show_y=='once' else show_y, show_x = show_x, grid=grid, sharex=sharex, sharey=sharey, xlabel=xlabel, xlim=xlim, ylim=ylim): plt.subplots_adjust(wspace=spacing, **adjust_kwargs) yield new_subplots = cap.get_new_subplots().values() if clip_x: set_same_xlims(new_subplots) if clip_y: set_same_ylims(new_subplots) assert len(new_subplots)>0, "No new plots have been created in this block... Why did you create the block at all?" if show_y in (True, 'once'): new_subplots[0].tick_params(axis='y', labelleft='on') new_subplots[0].set_ylabel(ylabel) if remove_ticks: for ax in new_subplots[:-1]: ax.set_xticks(ax.get_xticks()[:-1])
def vstack_plots(spacing=0, sharex=True, sharey = False, show_x = 'once', show_y=True, clip_x=False, clip_y=False, grid=False, remove_ticks = True, xlabel=None, ylabel=None, xlim=None, ylim=None, **adjust_kwargs): with CaptureNewSubplots() as cap: with _define_plot_settings(layout='v', show_x = False if show_x=='once' else show_x, show_y=show_y, grid=grid, sharex=sharex, sharey=sharey, ylabel=ylabel, xlim=xlim, ylim=ylim): plt.subplots_adjust(hspace=spacing, **adjust_kwargs) yield new_subplots = cap.get_new_subplots().values() if clip_x: set_same_xlims(new_subplots) if clip_y: set_same_ylims(new_subplots) assert len(new_subplots)>0, "No new plots have been created in this block... Why did you create the block at all?" if show_x in (True, 'once'): new_subplots[-1].tick_params(axis='x', labelbottom='on') new_subplots[-1].set_xlabel(xlabel) if remove_ticks: new_subplots[-1].get_xaxis().set_visible(True) for ax in new_subplots[:-1]: ax.set_yticks(ax.get_yticks()[:-1])
def plot_waveforms(self): nb_cells = len(self.cells) nb_cols = int(np.sqrt(nb_cells - 1)) + 1 nb_rows = (nb_cells - 1) / nb_cols + 1 plt.figure() for cell in self.cells.itervalues(): plt.subplot(nb_rows, nb_cols, cell.id + 1) t_min = 0.0 t_max = float(81) / self.sampling_rate t = np.linspace(t_min, t_max, num=81) w = cell.sample(0.0, t) t = 1.0e3 * t plt.plot(t, w, color=cell.color) plt.xlim(t[0], t[-1]) plt.suptitle(r"Waveforms") plt.tight_layout() plt.subplots_adjust(top=0.92) return
def save_ims(filename, ims, dpi=100): n, c, w, h = ims.shape x_plots = math.ceil(math.sqrt(n)) y_plots = x_plots if n % x_plots == 0 else x_plots - 1 plt.figure(figsize=(w*x_plots/dpi, h*y_plots/dpi), dpi=dpi) for i, im in enumerate(ims): plt.subplot(y_plots, x_plots, i+1) if c == 1: plt.imshow(im[0]) else: raise NotImplementedError plt.axis('off') plt.gca().set_xticks([]) plt.gca().set_yticks([]) plt.gray() plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) plt.savefig(filename, dpi=dpi*2, facecolor='black') plt.clf() plt.close()
def plot_single_var_normal(self): """ Método responsável por plotar a função normal (gaussiana) de cada classe para cada variável. """ x_values = np.arange(-1, 10, 0.1) inputs_by_class = self.get_inputs_by_class() num = 1 for var_name in inputs_by_class: plot.subplot(2, 2, num) plot.subplots_adjust(hspace=0.5) legend = [] variances, means = self.__get_variances_and_means(var_name) for class_name in inputs_by_class[var_name]: y_values = self.gaussian_vectorized(variances[class_name], means[class_name], x_values) legend.append(class_name) plot.plot(x_values, y_values) plot.legend(legend) plot.xlabel(var_name) num += 1 plot.show()
def three_spectrums(): """Makes a plot showing three spectrums for a sinusoid. """ thinkplot.preplot(rows=1, cols=3) pyplot.subplots_adjust(wspace=0.3, hspace=0.4, right=0.95, left=0.1, top=0.95, bottom=0.05) xticks = range(0, 900, 200) thinkplot.subplot(1) thinkplot.config(xticks=xticks) discontinuity(num_periods=30, hamming=False) thinkplot.subplot(2) thinkplot.config(xticks=xticks) discontinuity(num_periods=30.25, hamming=False) thinkplot.subplot(3) thinkplot.config(xticks=xticks) discontinuity(num_periods=30.25, hamming=True) thinkplot.save(root='windowing1')
def visualiseLearnedFeatures(self): """ Visualise the features learned by the autoencoder """ import matplotlib.pyplot as plt extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture # number of rows and columns to plot (number of hidden units also stored in self._architecture) plotDims = np.rint(np.sqrt(self._architecture[1])) plt.ion() fig = plt.figure() plt.set_cmap("gnuplot") plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1) learnedFeatures = self.getLearnedFeatures() for i in range(self._architecture[1]): image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000 ax = fig.add_subplot(plotDims, plotDims, i) plt.axis("off") ax.imshow(image, interpolation="nearest") plt.show() raw_input("Program paused. Press enter to continue.")
def visualiseLearnedFeatures(self): """ Visualise the features learned by the autoencoder """ import matplotlib.pyplot as plt extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture # number of rows and columns to plot (number of hidden units also stored in self._architecture) plotDims = np.rint(np.sqrt(self._architecture[1])) plt.ion() fig = plt.figure() plt.set_cmap("gnuplot") plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1) learnedFeatures = self.getLearnedFeatures() for i in range(self._architecture[1]): image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000 ax = fig.add_subplot(plotDims, plotDims, i) plt.axis("off") ax.imshow(image, interpolation="nearest") plt.show() input("Program paused. Press enter to continue.")
def plot_pdf(score_export, fname, swap=None, cutoff=1): cut_data = np.array([p for g, p in score_export.roc() if p < cutoff]) plots = ['density', 'kde'] n = len(plots) for i, f in enumerate(plots): plt.subplot(n, 1, i + 1) if f == 'density': plot_seaborn_density(cut_data) elif f == 'split': plot_seaborn_density_split(swap, cutoff) elif f == 'kde': plot_kde(cut_data) plt.suptitle('Probability Density Function') plt.tight_layout() plt.subplots_adjust(top=0.93) if fname: plt.savefig(fname, dpi=300) else: plt.show()
def pylot_show(): count=[] leixing = [] leixing_number={} with open("000000_0.txt", "r", encoding="utf-8") as fp: for line in fp.readlines(): leixing_number[line.strip().split("\t")[0]] = int(line.strip().split("\t")[1]) leixing.append(line.strip().split("\t")[0]) count.append(int(line.strip().split("\t")[1])) y_pos = np.arange(len(leixing)) # ??y???? plt.barh(y_pos, count, align='center', alpha=0.4) # alpha?????????(0~1)?? plt.yticks(y_pos, leixing) # ?y????????? for count, y_pos in zip(count, y_pos): # ?????????????????????????????? plt.text(count, y_pos, count, horizontalalignment='center', verticalalignment='center', weight='bold') plt.ylim(+40.0, -1.0) # ???????????y??? plt.title(u'??????') # ????? plt.ylabel(u'????') # ??y???? plt.subplots_adjust(bottom=0.15) plt.xlabel(u'????') # ??x???? plt.savefig('Y_leixing.png') # ???? plt.show()
def plot_hsv(image, bins=12): """ Plot HSV histograms of image INPUT: image with HSV channels OUPUT: plot of HSV histograms and color spectrum """ sns.set_style("whitegrid", {'axes.grid': False}) fig = plt.figure(figsize=(12, 5)) plt.subplots_adjust(top=2, bottom=1, wspace=.5, hspace=0) plt.subplot(231) plt.hist(image[:, :, 0].flatten(), bins=bins, color='gray') plt.title('Hue') plt.subplot(232) plt.hist(image[:, :, 1].flatten(), bins=bins, color='gray') plt.title('Saturation') plt.subplot(233) plt.hist(image[:, :, 2].flatten(), bins=bins, color='gray') plt.title('Value') plt.subplot(234) plt.imshow(all_hues, extent=(0, 1, 0, 0.2)) plt.show()
def gen_sample_summary(samples): fig, axes = plt.subplots(figsize=(5,3), nrows=3, ncols=5, sharey=True, sharex=True) plt.subplots_adjust(wspace=0, hspace=0) for ax, img in zip(axes.flatten(), samples): ax.axis('off') img = ((img - img.min())*255 / (img.max() - img.min())).astype(np.uint8) ax.set_adjustable('box-forced') im = ax.imshow(img, aspect='equal') arr = figure_to_numpy(fig) del(fig) return arr
def plot(x, y, title, xlabel, ylabel, fname): import matplotlib.mlab as mlab import matplotlib.pyplot as plt plt.plot(x, y) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.subplots_adjust(left=0.15) plt.savefig(fname + '.jpg') plt.close() # cross()
def linePlotGraphics(xLabel,yLabel,xValueList,yValueList,graphicTitle='??'): with plt.style.context('fivethirtyeight'): plt.title(graphicTitle,fontproperties=font_set,fontsize=20) plt.xlabel(xLabel,fontproperties=font_set) plt.ylabel(yLabel,fontproperties=font_set) plt.xticks(numpy.arange(len(xValueList)),xValueList,rotation=45,fontproperties=font_set) plt.plot(yValueList) yValueList.sort() #??y???????????x??? print("len(yValueList)=",len(yValueList)) plt.ylim(-1.0, yValueList[len(yValueList)-1]+1) plt.subplots_adjust(bottom=0.15,left=0.05,right=0.98,top=0.92) #???????????? ax = plt.gca() ax.get_xaxis().tick_bottom() #??????x??ticks ax.get_yaxis().tick_left() ax.grid(b=False,axis='x') axis = ax.xaxis for line in axis.get_ticklines(): line.set_color("gray") line.set_markersize(6) line.set_markeredgewidth(1) #????? plt.show() #plt.savefig('percent-bachelors-degrees-women-usa.png', bbox_inches='tight') #???:???