def plot_graph(G, fname=None, edge_weight="length", vertex_weight="both", show=False): pos = nx.spring_layout(G) # color = range(G_diff.size()) color = [G[u][v][edge_weight] for u, v in G.edges()] print(color) node_color = "Y" if vertex_weight == "both": _node_color = [ nx.get_node_attributes(G, "prob_in")[x] + nx.get_node_attributes(G, "prob_out")[x] for x in list(G.nodes()) ] else: _node_color = [ nx.get_node_attributes(G, vertex_weight)[x] for x in list(G.nodes()) ] fig = plt.figure(frameon=False) fig.set_size_inches(13,6.25) nx.draw( G, pos, node_color=_node_color, edge_color=color, width=1, cmap=cm.get_cmap("Reds"), edge_cmap=cm.get_cmap("rainbow"), with_labels=True, ) if fname: plt.savefig(img_dir + fname, quality=100) if show: plt.show()
def run_pie_example(): print('Simple Category Classifier Pie Example.') model = CategoryClassifierModel(name='CategoryClassifier').setup( objective='softmax_crossentropy_loss', metric=('loss', 'accuracy')) if not os.path.isfile( 'modules/examples/models/category_classifier_pie.json'): generate_pie() print(model.summary) model.learn(training_input_t, expected_output_t, epoch_limit=50, batch_size=32, tl_split=0.2, tl_shuffle=True) model.save_snapshot('modules/examples/models/', save_as='category_classifier_pie') anim = model.plot() anim.save('modules/examples/plots/category_classifier_pie.gif', dpi=80, writer='pillow') else: model.load_snapshot( 'modules/examples/models/category_classifier_pie.json', overwrite=True) print(model.summary) (x_min, x_max) = (0, 1) (y_min, y_max) = (0, 1) (xx, yy) = np.meshgrid(np.arange(x_min, x_max, 0.005), np.arange(y_min, y_max, 0.005)) testing_input_t = np.c_[xx.ravel(), yy.ravel()] generate_pie() predicted_output_t = model.predict(testing_input_t) zz = predicted_output_t.argmax(axis=1).reshape(xx.shape) figure = plt.figure() figure.suptitle('Classification Prediction Results') cmap_spring = cm.get_cmap('spring') cmap_cool = cm.get_cmap('cool') plt.contourf(xx, yy, zz, cmap=cmap_spring, alpha=0.8) plt.scatter(training_input_t[:, 0], training_input_t[:, 1], c=expected_output_labels, s=5, cmap=cmap_cool) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.grid() plt.show()
def plot(self): learning_losses = [] testing_losses = [] learning_accuracies = [] testing_accuracies = [] for report in self._reports: evaluation_metric = report['evaluation_metric'] learning_losses.append(evaluation_metric['learning']['loss']) testing_losses.append(evaluation_metric['testing']['loss']) learning_accuracies.append(evaluation_metric['learning']['accuracy']) testing_accuracies.append(evaluation_metric['testing']['accuracy']) figure1 = plt.figure() figure1.suptitle('Evaluations') plt.subplot(2, 1, 1) plt.xlabel('Epoch') plt.ylabel('Loss') plt.plot(learning_losses, color='orangered', linewidth=1, linestyle='solid', label='Learning Loss') plt.plot(testing_losses, color='salmon', linewidth=1, linestyle='dotted', label='Testing Loss') plt.legend(fancybox=True) plt.grid() plt.subplot(2, 1, 2) plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.plot(learning_accuracies, color='deepskyblue', linewidth=1, linestyle='solid', label='Learning Accuracy') plt.plot(testing_accuracies, color='aqua', linewidth=1, linestyle='dotted', label='Testing Accuracy') plt.legend(fancybox=True) plt.grid() figure2 = plt.figure() figure2.suptitle('Training Results Per Epoch') epoch_limit = len(self._training_snapshots) (x_min, x_max) = (0, 1) (y_min, y_max) = (0, 1) (xx, yy) = np.meshgrid(np.arange(x_min, x_max, 0.005), np.arange(y_min, y_max, 0.005)) cmap_spring = cm.get_cmap('spring') cmap_cool = cm.get_cmap('cool') imgs = [] for epoch in range(epoch_limit): zz = self._training_snapshots[epoch] im = plt.contourf(xx, yy, zz, cmap=cmap_spring) imgs.append(im.collections) plt.scatter(training_input_t[:, 0], training_input_t[:, 1], c=expected_output_labels, s=5, cmap=cmap_cool) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.grid() anim = animation.ArtistAnimation(figure2, imgs, interval=48, repeat_delay=1000, repeat=True) plt.show() return anim
def create_heatmap(benchmark, state, matrix, confidence_level, text=None): if len(matrix[0]) == 0: return fig, ax = plt.subplots(figsize=(7, 7)) ax.imshow(matrix, cmap=cm.get_cmap("coolwarm")) ax.set_xticks(np.arange(len(JVMS))) ax.set_yticks(np.arange(len(JVMS))) ax.set_xticklabels(JVMS) ax.set_yticklabels(JVMS) ax.xaxis.tick_top() plt.setp(ax.get_xticklabels(), rotation=45, ha="left", rotation_mode="anchor") for i in range(len(matrix)): for j in range(len(matrix[i])): if text is not None: ax.text(j, i, text[i][j], ha="center", va="center", color="w") else: ax.text(j, i, matrix[i][j], ha="center", va="center", color="w") plt.title(benchmark + " " + state + "\n" + confidence_level + " confidence level") fig.tight_layout() filename = benchmark + "_" + state + "_heatmap" plt.savefig(filename) plt.close(fig)
def plot_tsne_graph_for_model(model, label, legend_position="upper right"): n_colors = len(model["topics"]) colors_numbers = np.linspace(0, 1, n_colors) color_map = cm.get_cmap("gist_rainbow") fig, ax = plt.subplots(1) for idx, X in enumerate(model["topics_vectors"]["word_vectors"]): Z = TSNE().fit_transform(X).T color = [list(color_map(colors_numbers[idx]))] weights = list( map( lambda x: map_number(x, [0, 1], [ DEFAULT_MIN_POINT_SIZE, DEFAULT_MAX_POINT_SIZE ]), model["topics_vectors"]["word_weights"][idx])) ax.scatter(Z[0], Z[1], s=weights, c=color, cmap=color_map, alpha=0.7, label=f'Tópico {idx+1}') ax.legend(bbox_to_anchor=(1.04, 1.0), ncol=1 if n_colors <= MAXIMUM_NUMBER_OF_LEGEND_ROWS \ else int(math.ceil(n_colors/MAXIMUM_NUMBER_OF_LEGEND_ROWS))) ax.grid(b=True, alpha=0.4) filename = os.path.join(OUTPUT_PATH, f'{label}_tsne{FILE_FORMAT}') os.makedirs(os.path.dirname(filename), exist_ok=True) fig.savefig(filename, bbox_inches='tight') plt.show()
def _check_cmap(self, proposal): if isinstance(proposal['value'], str): return cm.get_cmap(proposal['value']) elif not isinstance(proposal['value'], Colormap): raise TypeError('cmap should be set to a Matplotlib colormap') else: return proposal['value']
def error_plot(self, ax_lb, ax_ub, cax, cborientation='vertical'): # plot the error map ttP_lb = np.zeros((self.dims[1::])) ttP_ub = ttP_lb.copy() for _i1 in xrange(self.dims[1]): for _i2 in xrange(self.dims[2]): for _i3 in xrange(self.dims[3]): ttP_lb[_i1, _i2, _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3], 16) ttP_ub[_i1, _i2, _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3], 84) mlb = copy(self.m) mlb.ax = ax_lb mub = copy(self.m) mub.ax = ax_ub cmap = cm.get_cmap(self.cmapname) cmap.set_over('grey') mlb.contourf(self.x, self.y, ttP_lb[:, :, 0], cmap=cmap, levels=np.arange(self.vmin, self.vmax + 0.5, 0.5), norm=Normalize(vmin=self.vmin, vmax=self.vmax), extend=self.extend) mub.contourf(self.x, self.y, ttP_ub[:, :, 0], cmap=cmap, levels=np.arange(self.vmin, self.vmax + 0.5, 0.5), norm=Normalize(vmin=self.vmin, vmax=self.vmax), extend=self.extend) mlb.drawcoastlines(zorder=2) mlb.drawcountries(linewidth=1.0, zorder=2) mub.drawcoastlines(zorder=2) mub.drawcountries(linewidth=1.0, zorder=2) cb = ColorbarBase(cax, cmap=cmap, norm=Normalize(vmin=self.vmin, vmax=self.vmax), orientation=cborientation, extend=self.extend) cb.set_label(self.cb_label) return mlb, mub
def __init__(self, parent=None): img_size = 35 # square dimension of output image data = np.mgrid[0:255:255j, 0:255][0] ugly_maps = [ 'Accent', 'Paired', 'Dark', 'Pastel', 'tab', 'Set', 'flag', '_r', 'gray', 'Greys' ] pretty_cmaps = [ i for i in mpl_cmaps() if not any([(j in i) for j in ugly_maps]) ] root = QFileInfo(__file__).absolutePath() gradient_icons = [ i.split('.')[0] for i in os.listdir(root + "/icons/gradients/") ] for cmap_name in pretty_cmaps: if cmap_name not in gradient_icons: cmap = cm.get_cmap(cmap_name) sizes = np.shape(data) fig = plt.figure(figsize=(1, 1)) #fig.set_size_inches(1. * sizes[0] / sizes[1], 1, forward=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(data[::-1], cmap) plt.savefig("icons/gradients/{}.png".format(cmap_name), dpi=img_size) plt.close()
def plot_mean_and_std(time, mean_traj, std_traj, indices=None): color_cycle = cycle(np.linspace(0, 1, 10)) color_map = cm.get_cmap('rainbow') legend_handles = [] if not indices: indices = range(mean_traj.shape[1]) for i in indices: plt.figure() curve = mean_traj[:, i] curve_std = std_traj[:, i] lower_bound = curve - 2 * curve_std upper_bound = curve + 2 * curve_std x = time color = color_map(next(color_cycle)) plt.fill_between(x, lower_bound, upper_bound, color=color, alpha=0.5) label = 'Joint %d' % (i) new_handle = plt.plot(x, curve, color=color, label=label) legend_handles.append(new_handle[0]) plt.legend(handles=legend_handles) plt.xlabel('time') plt.ylabel('q') plt.autoscale(enable=True, axis='x', tight=True)
def plot_densities_on_map_by_time_point(population_data, time): plt.figure(figsize=(14, 8)) my_map = Basemap(projection='robin', lat_0=57, lon_0=-135, resolution='l', area_thresh=1000.0, llcrnrlon=-136.25, llcrnrlat=56, urcrnrlon=-134.25, urcrnrlat=57.75) my_map.drawcoastlines() my_map.drawcountries() my_map.fillcontinents(color='lightgray', zorder=0) my_map.drawmapboundary() my_map.drawmeridians(np.arange(0, 360, 30)) my_map.drawparallels(np.arange(-90, 90, 30)) time_index = -1 for i in range(0, len(population_data.time_array)): if time == population_data.time_array[ i] * population_data.time_multiplier: time_index = i break lats = [] lons = [] dens = [] for i in range(0, len(population_data.density_array[time_index])): density = population_data.density_array[time_index][i] if density != 0: lats.append(population_data.lat_array[i]) lons.append(population_data.lon_array[i]) dens.append(density) cmap = cm.get_cmap('jet') dens = np.array(dens).astype(float) / 3000 x, y = my_map(lons, lats) rgba = cmap(dens) ax = my_map.scatter(x, y, marker='o', c=rgba, s=3, zorder=1) sm = cm.ScalarMappable(cmap=cmap) sm.set_array([]) sm.set_clim([0, 3000]) plt.colorbar(sm, orientation='horizontal', pad=0.03, aspect=50) plt.savefig("densitites_on_map_" + population_data.name + "_" + str(time) + "Kya.png") map_path = get_map_file_path(population_data.name.lower() + "_densitites_on_map_" + str(time) + ".png") print("Map filepath: " + map_path) plt.savefig(map_path, dpi=500) plt.close()
def create_christmas_colormap(): christmas_colormap = cm.get_cmap('viridis', 31) christmas_colormap.colors[0, 0:-1] = [1, 1, 1] for i in range(1, 29): christmas_colormap.colors[i, 0:-1] = [0, 0.9 - i * 0.02, 0] christmas_colormap.colors[-2, 0:-1] = [0.5, 0, 0] christmas_colormap.colors[-1, 0:-1] = [1, 0, 0] return christmas_colormap
def create_histogram_yearly(self, name="hist"): for i in self.regulatory_phases: colours_list = cm.get_cmap("viridis") yearly_df = self.wind_data.loc[ (self.wind_data.year >= self.regulatory_phases[i][0]) & (self.wind_data.year < self.regulatory_phases[i][1])] ax = plt.axes() sns.histplot(ax=ax, data=yearly_df, x="average wind speed", bins=20, kde=True, weights="electrical_capacity", stat="probability", color=colours_list(0)) ax.set_title( str(i) + ": " + str(self.regulatory_phases[i][0]) + " - " + str(self.regulatory_phases[i][1] - 1)) text_props = dict(boxstyle='square', facecolor='white', edgecolor="none", alpha=0.9, pad=0.5) total_added_capacity = round( yearly_df['electrical_capacity'].sum()) years_period = self.regulatory_phases[i][ 1] - self.regulatory_phases[i][0] y = ax.get_ylim() x = ax.get_xlim() avg = yearly_df["average wind speed"].mean() med = yearly_df["average wind speed"].median() stand_dev = yearly_df["average wind speed"].std() plt.text(x[0] * 1.05, y[1] * 0.95, "Total added capacity: " + str(total_added_capacity) + " MW" + "\n" "Added capacity per year: " + str(round(total_added_capacity / years_period)) + " MW" + "\n" "Mean: " + str(round(avg, 1)) + "\n" "Median: " + str(round(med, 1)) + "\n" "Standard deviation: " + str(round(stand_dev, 1)), fontsize=10, verticalalignment='top', ha="left", bbox=text_props) plt.savefig(name + "years" + str(i)) plt.clf() plt.close()
def render_surface(self, scalar_func, cmap_name=None): mesh = pv.PolyData(self.v, self.faces) plotter = pv.Plotter() plotter.add_mesh(mesh, show_edges=True, scalars=scalar_func, cmap=cm.get_cmap(cmap_name)) plotter.add_scalar_bar(n_labels=2) return plotter
def plot_bw(): tex.setup(width=1, height=None, span=False, l=0.15, r=0.98, t=0.98, b=0.17, params={'hatch.linewidth': 0.5}) PAYLOAD_SIZE = [256, 512, 1024, 1400] cmap = cm.get_cmap('tab10') csv_names = ['udp_bw_dpdk_fwd_kni_2core.csv', 'udp_bw_xdp_dpdk_fwd.csv'] N = 4 ind = np.arange(N) # the x locations for the groups width = 0.25 # the width of the bars fig, ax = plt.subplots() labels = ["Centralized", "Chain-based"] markers = ['o', 'x', '^'] line_styles = ['dashed', 'solid', '--'] for idx, csv in enumerate(csv_names): csv_path = os.path.join("./bandwidth/results/", csv) bw_arr = np.genfromtxt( csv_path, delimiter=',', usecols=list(range(0, 2))) / 1000.0 bw_avg = bw_arr[:, 1] # bar = ax.bar(ind + idx * width, bw_avg, width, color=cmap(idx), bottom=0, # edgecolor='black', alpha=0.8, lw=0.6, # hatch=hatch_patterns[idx], # label=labels[idx]) # label_bar(bar, ax) ax.plot(ind, bw_avg, color=cmap(STYLE_MAP[labels[idx]]['color']), ls=line_styles[idx], label=labels[idx], marker=markers[idx], markerfacecolor="None", markeredgecolor=cmap(STYLE_MAP[labels[idx]]['color']), ms=3) ax.set_ylabel('Bandwidth (Mbits/sec)') ax.set_xticks(ind) ax.set_xticklabels(('256', '512', '1024', '1400')) ax.set_xlabel('Payload Size (Bytes)') handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels, loc='upper left') ax.autoscale_view() ax.grid(linestyle='--') save_fig(fig, "./bandwidth")
def plot_net_w_routes(nodes, edges, plot_edges=True, blocking=True, file_name=None, single=-1, weights=None): fig = figure(figsize=fig_size) ax = fig.gca() ax.axis('off') if weights is None: colour = 'r' if single is None else 'k' ax.scatter(nodes[:, 2], nodes[:, 1], c=colour, s=5) # Plot airports if single is not None and single > -1: ax.scatter(nodes[single, 2], nodes[single, 1], c='r', s=40) # Plot airports else: cmap = cm.get_cmap('Blues') min_val = min(weights) max_val = max(weights) sizes = [10 if weight == 0 else 25 for weight in weights] plot_data = [[node[2], node[1], weights[i], sizes[i]] for i, node in enumerate(nodes)] plot_data = sorted(plot_data, key=lambda k: k[2]) sizes = [data[3] for data in plot_data] plot_data = array(plot_data)[:, :3].astype(float) ax.scatter(plot_data[:, 0], plot_data[:, 1], c=plot_data[:, 2], vmin=min_val, vmax=max_val, cmap=cmap, s=sizes, linewidths=.5, edgecolor='k') if plot_edges: for _, (src, dest) in enumerate(edges): # Plot routes if type(src) is not list: src = nodes[src, 1:] dest = nodes[dest, 1:] ax.plot((src[1], dest[1]), (src[0], dest[0]), 'k', alpha=.1) if file_name is not None: try: savefig(file_name, bbox_inches='tight', pad_inches=0) except: print('Bad save!') if blocking: show()
def _plot_image(self, x, y, z, title, xlabel, ylabel): # TODO overhaul colour bar selection either through a dropdown list or use some check colour_map = self.computed_data.colourmap cmap = cm.get_cmap(colour_map) cf = self.axes.contourf(x, y, z, cmap=cmap) self.colourbar = self.figure.colorbar(cf) self.axes.set_title(title) self.axes.set_xlabel(xlabel) self.axes.set_ylabel(ylabel)
def visualize_frustum_ptcloud_with_cam(frustum_ptcloud): ''' :param frustum_ptcloud: np.ndarray, shape (n,4) [x,y,z,s], s is the class activation score \in (0,1) ''' cm = colormap.get_cmap('RdBu') #inferno color_mapper = colormap.ScalarMappable(norm=matplotlib.colors.Normalize( vmin=0, vmax=1, clip=True), cmap=cm) color = color_mapper.to_rgba(frustum_ptcloud[:, 3])[:, :3] * 255 visualize_ptcloud_with_color(frustum_ptcloud[:, 0:3], color)
def _plot_field(result, x, y, n_min, n_max, n_step): levels = arange(n_min, n_max + n_step, n_step) color_map = cm.get_cmap('plasma') contourf(x, y, clip(result, n_min, n_max), 10, cmap=color_map, levels=levels, extend='both')
def plotallimages(cy3file, cy5file, labelsfile, Clustersfile): from matplotlib.pyplot import imread, savefig, subplots, cm from nipype.utils.filemanip import split_filename import os import numpy as np import scipy.io as sio def get_centroids(labels): labelnums = np.unique(labels) centroids = [] for label in labelnums: centroids.append( np.mean(np.asarray(np.nonzero(labels == label)), axis=1)) return centroids cy3 = imread(cy3file) cy5 = imread(cy5file) Clusters = np.asarray(sio.loadmat(labelsfile)["label"]) labels = np.asarray(sio.loadmat(Clustersfile)["k"]) _, name, ext = split_filename(Clustersfile) outfile = os.path.abspath(name + "_img_all.png") fig, ax = subplots(ncols=4, nrows=1, figsize=(36, 12)) ax[0].imshow(cy3, cmap=cm.Greys) k = len(np.unique(labels)) cmap = cm.get_cmap('jet', k) l = ax[1].imshow(labels, cmap=cmap) ax[1].set_title('K Means Clustering') nlabels = len(np.unique(Clusters)) cmap = cm.get_cmap('jet', nlabels) b = ax[2].imshow(Clusters, cmap=cmap, alpha=0.3) ax[2].set_title("ROI Labelling") centroids = get_centroids(Clusters) for i, c in enumerate(centroids): ax[2].annotate('%d' % i, c[::-1], color="black") ax[3].imshow(cy5, cmap=cm.Greys) ax[3].set_title('Cy5 - Defect') ax[0].set_title('Cy3 - Object') savefig(outfile, bbox_inches="tight") return outfile
def plotallimages(cy3file,cy5file,labelsfile,Clustersfile): from matplotlib.pyplot import imread, savefig,subplots,cm from nipype.utils.filemanip import split_filename import os import numpy as np import scipy.io as sio def get_centroids(labels): labelnums = np.unique(labels) centroids = [] for label in labelnums: centroids.append(np.mean(np.asarray(np.nonzero(labels==label)), axis = 1)) return centroids cy3 = imread(cy3file) cy5=imread(cy5file) Clusters = np.asarray(sio.loadmat(labelsfile)["label"]) labels = np.asarray(sio.loadmat(Clustersfile)["k"]) _,name,ext = split_filename(Clustersfile) outfile = os.path.abspath(name+"_img_all.png") fig,ax = subplots(ncols=4,nrows=1,figsize=(36,12)) ax[0].imshow(cy3,cmap=cm.Greys) k = len(np.unique(labels)) cmap = cm.get_cmap('jet', k) l = ax[1].imshow(labels,cmap=cmap) ax[1].set_title('K Means Clustering') nlabels = len(np.unique(Clusters)) cmap = cm.get_cmap('jet', nlabels) b=ax[2].imshow(Clusters,cmap=cmap,alpha=0.3) ax[2].set_title("ROI Labelling") centroids = get_centroids(Clusters) for i,c in enumerate(centroids): ax[2].annotate('%d'%i,c[::-1],color="black"); ax[3].imshow(cy5,cmap=cm.Greys) ax[3].set_title('Cy5 - Defect') ax[0].set_title('Cy3 - Object') savefig(outfile,bbox_inches="tight") return outfile
def save_summaries(writer: SummaryWriter, data: Dict, predicted: List, endpoints: Dict = None, losses: Dict = None, metrics: Dict = None, step: int = 0): """Save tensorboard summaries""" subset = [0, 1] with torch.no_grad(): # Save clouds if 'points_src' in data: points_src = data['points_src'][subset, ..., :3] points_ref = data['points_ref'][subset, ..., :3] colors = torch.from_numpy( np.concatenate([np.tile(ORANGE, (*points_src.shape[0:2], 1)), np.tile(BLUE, (*points_ref.shape[0:2], 1))], axis=1)) iters_to_save = [0, len(predicted)-1] if len(predicted) > 1 else [0] # Save point cloud at iter0, iter1 and after last iter concat_cloud_input = torch.cat((points_src, points_ref), dim=1) writer.add_mesh('iter_0', vertices=concat_cloud_input, colors=colors, global_step=step) for i_iter in iters_to_save: src_transformed_first = se3.transform(predicted[i_iter][subset, ...], points_src) concat_cloud_first = torch.cat((src_transformed_first, points_ref), dim=1) writer.add_mesh('iter_{}'.format(i_iter+1), vertices=concat_cloud_first, colors=colors, global_step=step) if endpoints is not None and 'perm_matrices' in endpoints: color_mapper = colormap.ScalarMappable(norm=None, cmap=colormap.get_cmap('coolwarm')) for i_iter in iters_to_save: ref_weights = torch.sum(endpoints['perm_matrices'][i_iter][subset, ...], dim=1) ref_colors = color_mapper.to_rgba(ref_weights.detach().cpu().numpy())[..., :3] writer.add_mesh('ref_weights_{}'.format(i_iter), vertices=points_ref, colors=torch.from_numpy(ref_colors) * 255, global_step=step) if endpoints is not None: if 'perm_matrices' in endpoints: for i_iter in range(len(endpoints['perm_matrices'])): src_weights = torch.sum(endpoints['perm_matrices'][i_iter], dim=2) ref_weights = torch.sum(endpoints['perm_matrices'][i_iter], dim=1) writer.add_histogram('src_weights_{}'.format(i_iter), src_weights, global_step=step) writer.add_histogram('ref_weights_{}'.format(i_iter), ref_weights, global_step=step) # Write losses and metrics if losses is not None: for l in losses: writer.add_scalar('losses/{}'.format(l), losses[l], step) if metrics is not None: for m in metrics: writer.add_scalar('metrics/{}'.format(m), metrics[m], step) writer.flush()
def _plot_surface(self, x, y, z, title, xlabel, ylabel, zlabel): colour_map = self.computed_data.colourmap cmap = cm.get_cmap(colour_map) fig = self.figure ax = fig.gca(projection="3d") surf = ax.plot_surface(x, y, z, cmap=cmap) self.colourbar = fig.colorbar(surf, ax=ax) ax.set_zlabel(zlabel) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel)
def create_histogram(self, name="hist"): colours_list = cm.get_cmap("viridis") ax = plt.axes() sns.histplot(data=self.wind_data, ax=ax, x="average wind speed", bins=20, kde=True, weights="electrical_capacity", stat="probability", color=colours_list(0)) ax.set_title( str(self.wind_data['year'].min()) + " - " + str(self.wind_data['year'].max())) text_props = dict(boxstyle='square', facecolor='white', edgecolor="none", alpha=0.9, pad=0.5) total_added_capacity = round( self.wind_data['electrical_capacity'].sum(), 1) years_period = self.wind_data['year'].max( ) - self.wind_data['year'].min() y = ax.get_ylim() x = ax.get_xlim() avg = self.wind_data["average wind speed"].mean() med = self.wind_data["average wind speed"].median() stand_dev = self.wind_data["average wind speed"].std() plt.text(x[0] * 1.05, y[1] * 0.95, "Total added capacity: " + str(total_added_capacity) + " MW" + "\n" "Added capacity per year: " + str(round(total_added_capacity / years_period)) + " MW" + "\n" "Mean: " + str(round(avg, 1)) + "\n" "Median: " + str(round(med, 1)) + "\n" "Standard deviation: " + str(round(stand_dev, 1)), fontsize=10, verticalalignment='top', ha="left", bbox=text_props) plt.savefig(name) plt.clf() plt.close()
def render_pointcloud(self, scalar_func, cmap_name=None, center=None): pointcloud = pv.PolyData(self.v) plotter = pv.Plotter() plotter.add_mesh(pointcloud, render_points_as_spheres=True, scalars=scalar_func, cmap=cm.get_cmap(cmap_name)) if center is not None: plotter.add_points(center, render_points_as_spheres=True, point_size=20, color='black') plotter.add_scalar_bar(n_labels=2) return plotter
def _np_to_uri( in_array, # type: np.ndarray cmap="RdBu", # type: str do_norm=True, # type: bool new_size=(128, 128), # type: Tuple[int, int] img_format="png", # type: str alpha=True, # type: bool ): # type: (...) -> str """ Convert a numpy array to a data URI with an encode image inside :param in_array: the image to convert :param cmap: the color map to use :param do_norm: if the image should be normalized first :param new_size: the dimensions of the output images :param img_format: the file-format to save as :param alpha: if the alpha channel should be included :return: the base64 string Examples ======== >>> print(_np_to_uri(np.zeros((100,100)))[:50]) iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAABUE >>> print(_np_to_uri(np.zeros((5, 10)), img_format = 'jpeg')[:50]) /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQ >>> len(_np_to_uri(np.zeros((100,100)), alpha = False)) 484 >>> len(_np_to_uri(np.zeros((100,100)), alpha = True)) 524 """ test_img_data = np.array(in_array).astype(np.float32) if do_norm: test_img_data -= test_img_data.mean() test_img_data /= test_img_data.std() test_img_data = (test_img_data + 0.5).clip(0, 1) test_img_color = cm.get_cmap(cmap)(test_img_data) test_img_color *= 255 pre_array = test_img_color.clip(0, 255).astype(np.uint8) max_dim = max(*pre_array.shape[0:2]) sq_array = force_array_dim(pre_array, (max_dim, max_dim) + pre_array.shape[2:]) p_data = PImage.fromarray(sq_array) rs_p_data = p_data.resize(new_size, resample=PImage.BICUBIC) out_img_data = BytesIO() if img_format == "jpeg" or not alpha: rs_p_data = rs_p_data.convert("RGB") rs_p_data.save(out_img_data, format=img_format) out_img_data.seek(0) # rewind enc_img = base64.b64encode(out_img_data.read()) return enc_img.decode("ascii").replace("\n", "")
def _check_cmap(self, proposal): if isinstance(proposal['value'], str): if proposal['value'] not in VALID_COLORMAPS: raise ValueError('Colormap should be one of ' + '/'.join(VALID_COLORMAPS) + ' (got {0})'.format(proposal['value'])) return cm.get_cmap(proposal['value']) elif not isinstance(proposal['value'], Colormap): raise TypeError('cmap should be set to a Matplotlib colormap') else: if proposal['value'].name not in VALID_COLORMAPS: raise ValueError('Colormap should be one of ' + ', '.join(VALID_COLORMAPS) + ' (got {0})'.format(proposal['value'].name)) return proposal['value']
def plot_pretty_compare(x, y, threshold, xlim, ylim, x_color='g', y_color='r', cmap='Blues'): from matplotlib.pyplot import cm from matplotlib.ticker import FormatStrFormatter cmap = cm.get_cmap(cmap) g = sns.JointGrid(x, y, size=8, xlim=xlim, ylim=ylim) mask = np.logical_or(x > threshold, y > threshold) #np.where(Xt[1]>threshold)[0] _ = g.plot_joint(plt.hexbin, bins='log', gridsize=30, cmap=cmap, extent=xlim + ylim) ax1 = g.ax_marg_x.hist( x, log=True, color=x_color, bins=30, range=xlim) #distplot(color=".5",kde=False) #hist_kws={'log':True} ax2 = g.ax_marg_y.hist(y, log=True, color=y_color, bins=30, orientation='horizontal', range=ylim) g.ax_marg_x.get_yaxis().reset_ticks() g.ax_marg_x.get_yaxis().set_ticks([1e0, 1e2, 1e4]) g.ax_marg_x.get_yaxis().set_ticklabels(['$10^0$', '$10^2$', '$10^4$']) g.ax_marg_x.set_ylabel('Count', labelpad=10) g.ax_marg_x.get_yaxis().grid(True) #g.ax_marg_x.get_yaxis().set_major_formatter(FormatStrFormatter('%d')) g.ax_marg_y.get_xaxis().reset_ticks() g.ax_marg_y.get_xaxis().set_ticks([1e0, 1e2, 1e4]) g.ax_marg_y.get_xaxis().set_ticklabels(['', '', '']) g.ax_marg_y.get_xaxis().grid(True) mm = [min(xlim[0], ylim[0]), max(xlim[1], ylim[1])] g.ax_joint.plot(mm, mm, '--k', lw=2) g.ax_joint.plot([mm[0], threshold], [threshold, threshold], '-r', lw=2) g.ax_joint.plot([threshold, threshold], [mm[0], threshold], '-r', lw=2) g.ax_joint.plot([threshold, mm[1]], [threshold, threshold], '--r', lw=2) g.ax_joint.plot([threshold, threshold], [threshold, mm[1]], '--r', lw=2) return g
def _build_colourbar(self): colour_fig = Figure(figsize=(2, 0.25)) axes = colour_fig.add_subplot(111) cmap = cm.get_cmap('jet') self.colourbar = cmap(np.arange(cmap.N)) axes.imshow([self.colourbar], extent=[0, 500, 0, 55]) axes.get_yaxis().set_visible(False) axes.get_xaxis().set_visible(False) colour_fig.patch.set_facecolor(rgb_to_rgba(BACKGROUND)) colour_fig.set_tight_layout('True') image = FigureCanvasTkAgg(colour_fig, master=self.root) image.draw() image.get_tk_widget().grid(column=0, row=2, padx=0, pady=0)
def mixture(chord_transitions, sc2): sc2 = cmm.NoteState.piece_to_state_chain(piece2, use_chords=True) x = np.zeros((len(sc2), ), dtype=np.float) for i in range(len(sc2) - 1): x[i] = 0 if (sc2[i].chord, sc2[i + 1].chord) in chord_transitions else 1 fig = figure() x.shape = 1, len(x) axprops = dict(xticks=[], yticks=[]) barprops = dict(aspect='auto', cmap=cm.get_cmap('binary'), interpolation='bicubic') ax = fig.add_axes([0.1, 0.1, 0.8, 0.1], **axprops) ax.imshow(x, **barprops) show()
def plotDistribution(shapefile,speciesData,month,specie,baseout,xii,yii,survivalDefinedDistribution): print "Plotting the distributions for month: %s"%(month) plt.clf() plt.figure(figsize=(10,10), frameon=False) ax = plt.subplot(111) mymap = Basemap(llcrnrlon=-3.0, llcrnrlat=53.0, urcrnrlon=13.5, urcrnrlat=63.0, resolution='i',projection='tmerc',lon_0=5,lat_0=10,area_thresh=50.) x, y = mymap(xii,yii) levels=np.arange(np.min(speciesData),np.max(speciesData),0.5) CS1 = mymap.contourf(x,y,np.fliplr(np.rot90(speciesData,3)),levels,cmap=cm.get_cmap('Spectral_r',len(levels)-1), extend='both',alpha=1.0) plt.colorbar(CS1,orientation='vertical',extend='both', shrink=0.5) mymap.drawcoastlines() mymap.fillcontinents(color='grey',zorder=2) mymap.drawcountries() mymap.drawmapboundary() plt.title('Species: %s month: %s'%(specie,month)) if survivalDefinedDistribution: plotfile=baseout+'/'+str(specie)+'_distribution_'+str(month)+'_survivalDefinedDistribution.png' else: plotfile=baseout+'/'+str(specie)+'_distribution_'+str(month)+'.png' print "=> Creating plot %s"%(plotfile) plt.savefig(plotfile,dpi=300) print "Adding polygons to plot" mypatches=createPathsForPolygons(shapefile,mymap) p = PatchCollection(mypatches,alpha=1.0,facecolor='none',lw=1.0,edgecolor='purple',zorder=2) ax.add_collection(p) plt.title('Species: %s month: %s'%(specie,month)) if survivalDefinedDistribution: plotfile=baseout+'/'+str(specie)+'_distribution_'+str(month)+'_spawningground__survivalDefinedDistribution.png' else: plotfile=baseout+'/'+str(specie)+'_distribution_'+str(month)+'_spawningground.png' print "=> Creating plot %s"%(plotfile) plt.savefig(plotfile,dpi=300)
def error_plot(self, ax_lb, ax_ub, cax, cborientation='vertical'): # plot the error map ttP_lb = np.zeros((self.dims[1::])) ttP_ub = ttP_lb.copy() for _i1 in xrange(self.dims[1]): for _i2 in xrange(self.dims[2]): for _i3 in xrange(self.dims[3]): ttP_lb[_i1, _i2, _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3], 16) ttP_ub[_i1, _i2, _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3], 84) mlb = copy(self.m) mlb.ax = ax_lb mub = copy(self.m) mub.ax = ax_ub cmap = cm.get_cmap(self.cmapname) cmap.set_over('grey') mlb.contourf(self.x, self.y, ttP_lb[:, :, 0], cmap=cmap, levels=np.arange(self.vmin, self.vmax + 0.5, 0.5), norm=Normalize(vmin=self.vmin, vmax=self.vmax), extend=self.extend) mub.contourf(self.x, self.y, ttP_ub[:, :, 0], cmap=cmap, levels=np.arange(self.vmin, self.vmax + 0.5, 0.5), norm=Normalize(vmin=self.vmin, vmax=self.vmax), extend=self.extend) mlb.drawcoastlines(zorder=2) mlb.drawcountries(linewidth=1.0, zorder=2) mub.drawcoastlines(zorder=2) mub.drawcountries(linewidth=1.0, zorder=2) cb = ColorbarBase(cax, cmap=cmap, norm=Normalize(vmin=self.vmin, vmax=self.vmax), orientation=cborientation, extend=self.extend) cb.set_label(self.cb_label) return mlb, mub
def __init__(self, *args, **kwargs): super(Plots, self).__init__(*args, **kwargs) # Create a color map and index the satellite names so that both plots share # the same color for each satellite. self._all_satellites = set() for node in args[0]['cn0_by_sat'].keys(): self._all_satellites.update(args[0]['cn0_by_sat'][node]) self._color_map = cm.get_cmap(name='nipy_spectral', lut=len(self._all_satellites)) self._all_satellites_list = list(self._all_satellites) self._all_satellites_index_map = { self._all_satellites_list[i]: i for i in range(len(self._all_satellites_list)) } # If the timestamp array is provided, use it for the x-axis, otherwise, use # the index. timestamp = None if 'timestamp' in args[0]['cn0_by_sat']: timestamp = args[0]['cn0_by_sat']['timestamp'] xlabel = 'Time [UTC]' if timestamp is not None else 'Time [samples]' nodes = args[0]['cn0_by_sat'].keys() if 'timestamp' in nodes: nodes.remove('timestamp') # Dynamically create the PlotCarrierToNoiseDensityRatio functions for the # given nodes provided in the `cn0_by_sat map`. The function name is set to # 'PlotCarrierToNoiseDensityRatio<node name>'. For example, if the nodes # provided are 'FcA' and 'GpsBaseStation', then this class will contain two # plotting methods: PlotCarrierToNoiseDensityRatioFcA() and # PlotCarrierToNoiseDensityRatioGpsBaseStation(). for node in nodes: setattr( self, # Set the name of the method. 'PlotCarrierToNoiseDensityRatio' + node, # types.MethodType binds the function to the name as a callable # function. types.MethodType( # MFig(args)(function) applies the decorator to the function. MFig(title='Carrier to noise density ratio ' + node, ylabel='C/No [dB-Hz]', xlabel=xlabel) (self._get_plot_carrier_to_noise_density_ratio_function( node, timestamp=timestamp)), self, Plots))
def plot_data(data, group_by, kind='area'): ''' param:data = Data frame param: column group "type" or "day" param : area or bar graph Data is filtered and grouped based on colum value provided returns: seaborn graph ''' data_grouped = data[['duration', group_by, 'start_date']] .groupby([group_by, 'start_date']) .agg({"duration": {'Total_Duration': 'sum', 'Number_of_Rides': 'count'}}) \ .reset_index() data_grouped.columns = [ ''.join(col).strip().replace('duration', '') for col in data_grouped.columns.values ] print(data_grouped.head()) cols = ['Number_of_Rides', 'Total_Duration'] fig, axes = plt.subplots(2, 1, figsize=(15, 10)) sns.set_style("whitegrid") cmap = cm.get_cmap('Dark2', 11) for i in range(len(cols)): data_group = data_grouped.pivot('start_date', group_by, cols[i]) data_group.index = [str(x) for x in data_group.index] # Plotting on a (2,2) panel axes[i].set_title(cols[i]) fig.tight_layout(pad=3) data_group.plot(kind=kind, stacked=True, legend=None, ax=axes[i], cmap=cmap) handles, labels = axes[0].get_legend_handles_labels() lg = axes[1].legend(handles, labels, bbox_to_anchor=(1.3, 1), loc=0, fontsize=10) for lo in lg.legendHandles: lo.set_linewidth(10)
def plot2D(self, fig, ax, depth=8, vs=3.5, nnst=6, procdelay=False, scale=False, boxin=(45.4, 48.3, 5.6, 11.1), geofilter=None, boxout=(45, 48.5, 5, 12, 47), target=None, meridians=np.arange(5, 12, 2), interactive=False, parallels=np.arange(44, 49, 2), blindzone=False, pga=False, clevels=None, cbshrink=0.8): self.m.ax = ax if target is not None: tln, tlt = target latmin, latmax, lonmin, lonmax = boxin cmap = cm.get_cmap(self.cmapname) cmap.set_over('grey') if procdelay: self.vmin = 6. self.vmax = 25. self.cb_label = 'Time since origin time [s]' unit = 's' clevels_colours = ['lightgray', 'gray'] dlevel = 0.5 if target is not None: self.extend = 'both' self.vmin = -10. self.vmax = 60. cmap = cm.get_cmap(self.cmapname + '_r') self.cb_label = 'Lead time [s]' clevels_colours = ['lightgray', 'gray'] unit = 's' dlevel = 0.5 if not procdelay and target is None: self.vmin = 0. self.vmax = 15. self.cb_label = 'P-wave travel time to %d stations [s]' % nnst clevels_colours = ['gray', 'gray'] unit = 's' dlevel = 0.5 if blindzone: self.vmin = 22. self.vmax = 55. self.cb_label = 'Blind zone [km]' clevels_colours = ['lightgray', 'gray'] unit = 'km' dlevel = 0.5 if pga: self.extend = 'both' self.vmin = 0.01 self.vmax = 0.1 cmap = cm.get_cmap('PuBu') self.cb_label = 'Maximum pga [g]' unit = 'g' dlevel = 0.005 # Mask points outside of polygon if geofilter is not None: if self.dims > 2: rowidx = 0 colidx = 0 idx = 0 ydim = self.lat.shape[1] for _lat, _lon in zip(self.lat.ravel(), self.lon.ravel()): rowidx = idx / ydim colidx = idx - rowidx * ydim idx += 1 if not geofilter.point_in_polygon([_lon], [_lat])[0]: self.ttP[:, rowidx, colidx, :] = np.nan else: idx = 0 for _lat, _lon in zip(self.lat, self.lon): if not geofilter.point_in_polygon([_lon], [_lat])[0]: self.ttP[:, idx] = np.nan idx += 1 ttPmed = np.median(self.ttP, axis=0) ttPmed = np.median(ttPmed, axis=-1) print "The minimum alert time is: ", np.ma.masked_invalid(ttPmed).min() if target is not None: print self.tstarget.min(), self.tstarget.max() ttPmed = self.tstarget[:, :, 0] - ttPmed if blindzone: bz = np.sqrt(ttPmed * ttPmed * vs * vs - depth * depth) if pga: sg = SwissGmpe() sg.grid_setup(self.lat, self.lon) mag = 6.5 r, pgaforeland = sg.get_pga(mag, bz, 'foreland', 'median') r, pgaalpine = sg.get_pga(mag, bz, 'alpine', 'median') ttPmed = pgaforeland * sg.forelandmask + pgaalpine * sg.alpinemask ttPmed *= 1.7 ttPmed /= 1000 print ttPmed.min(), ttPmed.max() else: ttPmed = bz print "The minimum blindzone is: ", ttPmed.min() cf = self.m.contourf(self.x, self.y, ttPmed, cmap=cmap, levels=np.arange(self.vmin, self.vmax + dlevel, dlevel), norm=Normalize(vmin=self.vmin, vmax=self.vmax), extend=self.extend) if target is not None: xt, yt = self.m(tln, tlt) self.m.plot(xt, yt, marker='*', ms=14, color='black') # Add contour lines if clevels is not None: for _lev, _col in zip(clevels, clevels_colours): cs = self.m.contour(self.x, self.y, ttPmed, colors=_col, levels=[_lev], linestyles='solid', linewidths=3) with warnings.catch_warnings(record=True): plt.clabel(cs, fmt="%d " + unit, fontsize=12, colors=_col) if scale: cb = fig.colorbar(cf, ax=ax, extend=self.extend, orientation='vertical', spacing='uniform', shrink=cbshrink) cb.set_label(self.cb_label) self.m.drawmeridians(meridians, labels=[0, 0, 0, 1], color='lightgray', linewidth=0.5, zorder=0) self.m.drawparallels(parallels, labels=[1, 0, 0, 0], color='lightgray', linewidth=0.5, zorder=0) self.m.drawcoastlines(zorder=2) self.m.drawcountries(linewidth=1.0, zorder=2) self.m.drawstates(zorder=2) if pga and target is not None: mag = 6.25 lon, lat, pga = pgamap(mag, latmin, latmax, lonmin, lonmax, self.ngp, tlt, tln) cs = self.m.contour(self.x, self.y, pga / 1000., colors='black', levels=[0.01, 0.02, 0.04, 0.06, 0.1], linestyles='solid', linewidths=3) plt.clabel(cs, fmt="%.2f ", fontsize=12, colors='black') txtx, txty = self.m(5.5, 45.3) ax.text(txtx, txty, 'Magnitude=%.2f + 1$\sigma$' % mag, horizontalalignment='left', verticalalignment='center', backgroundcolor='white') return self.m
meridians = np.arange(5, 12, 2) parallels = np.arange(44, 49, 2) llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon, lat_ts = boxout m = Basemap(projection='merc', llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, lat_ts=lat_ts, resolution='i') xmin, ymin = m(lonmin, latmin) xmax, ymax = m(lonmax, latmax) nx = int((xmax - xmin) / 5000.) + 1 ny = int((ymax - ymin) / 5000.) + 1 dat, x, y = m.transform_scalar(pga / 1000., lon, lat, nx, ny, returnxy=True, masked=True) # m.fillcontinents(zorder=0) cmap = cm.get_cmap('jet') cf = m.contourf(x, y, dat, cmap=cmap) cs = m.contour(x, y, dat, colors='black', levels=[0.01, 0.02, 0.04, 0.06, 0.1], linestyles='solid', linewidths=3) plt.clabel(cs, fmt="%.2f ", fontsize=12, colors='black') m.drawmeridians(meridians, labels=[0, 0, 0, 1], color='lightgray', linewidth=0.5, zorder=0) m.drawparallels(parallels, labels=[1, 0, 0, 0], color='lightgray', linewidth=0.5, zorder=0) m.drawcoastlines(zorder=2) m.drawcountries(linewidth=1.0, zorder=2) line = 0.32 * np.arange(5, 12, 0.1) + 44.4 x, y = m(np.arange(5, 12, 0.1), line) # m.plot(x, y, 'k-')
def plot(self, toplot='retrievals', savefig=None, **kargs): """ Provide overview plots for data contained in a dataset. :type toplot: str :param toplot: Choose the datatype to plot. Parameters specific to `retrievals` contour plots: :type log: bool :param log: Turn on logarithmic colour scales. :type cmap_name: str :param cmap_name: The name of the matplotlib colour scale to use. :type angle_bins: :class:`numpy.ndarray` :param angle_bins: Define the bins onto which the angles of the retrievals are discretized to. :type ncontours: int :param ncontours: Number of contours used in the contour plot. """ if toplot.lower() == 'retrievals': cmap_name = kargs.get('cmap_name', 'RdBu_r') log = kargs.get('log', False) angle_bins = kargs.get('angle_bins', np.arange(0, 180, 1.0)) ncontours = kargs.get('ncontours', 100) ts = kargs.get('timeshift', 0.0) * 60. * 60. cmap = cm.get_cmap(cmap_name) # dicretize all retrievals onto a grid to show a daily plot rts = self.retrievals nretrieval = len(rts) m = np.zeros((nretrieval, angle_bins.size - 1)) # first sort retrievals based on start time def mycmp(r1, r2): s1 = r1.spectra_id.get_referred_object() t1 = s1.time[r1.slice].min() s2 = r2.spectra_id.get_referred_object() t2 = s2.time[r2.slice].min() if t1 < t2: return -1 if t1 == t2: return 0 if t1 > t2: return 1 rts.sort(cmp=mycmp) for i, _r in enumerate(rts): _s = _r.spectra_id.get_referred_object() _angle = _s.angle[_r.slice] _so2 = _r.sca _so2_binned = binned_statistic( _angle, _so2, 'mean', angle_bins) m[i, :] = _so2_binned.statistic fig = plt.figure() if log: z = np.where(m > 0.0, m, 0.1) plt.contourf(range(nretrieval), angle_bins[1:], z.T, ncontours, norm=LogNorm(z.min(), z.max()), cmap=cmap) else: z = np.ma.masked_invalid(m) plt.contourf(range(nretrieval), angle_bins[1:], m.T, ncontours, norm=Normalize(z.min(), z.max()), cmap=cmap) new_labels = [] new_ticks = [] ymin = angle_bins[-1] ymax = angle_bins[0] for _xt in plt.xticks()[0]: try: _r = rts[int(_xt)] _s = _r.spectra_id.get_referred_object() _a = _s.angle[_r.slice] ymin = min(_a.min(), ymin) ymax = max(_a.max(), ymax) dt = datetime.datetime.fromtimestamp( _s.time[_r.slice].min(), tz=tz.gettz('UTC')) dt += datetime.timedelta(seconds=ts) new_labels.append(dt.strftime("%Y-%m-%d %H:%M")) new_ticks.append(_xt) except IndexError: continue plt.xticks(new_ticks, new_labels, rotation=30, horizontalalignment='right') cb = plt.colorbar() cb.set_label('Slant column amount SO2 [ppm m]') plt.ylim(ymin, ymax) plt.ylabel(r'Angle [$\circ$]') if savefig is not None: plt.savefig( savefig, bbox_inches='tight', dpi=300, format='png') return fig else: print 'Plotting %s is has not been implemented yet' % toplot
def plot_moveout(streams, epilat, epilon, channel, cmap='viridis', figsize=None, file=None, minfontsize=14, normalize=False, scale=1, title=None, xlabel=None, ylabel=None): """ Create moveout plots. Args: stream (obspy.core.stream.Stream): Set of acceleration data with units of gal (cm/s/s). epilat (float): Epicenter latitude. epilon (float): Epicenter longitude. channel (list): List of channels (str) of each stream to view. cmap (str): Colormap name. figsize (tuple): Tuple of height and width. Default is None. file (str): File where the image will be saved. Default is None. minfontsize (int): Minimum font size. Default is 14. normalize (bool): Normalize the data. Default is faulse. scale (int, float): Value to scale the trace by. Default is 1. title (str): Title for plot. Default is None. xlabel (str): Label for x axis. Default is None. ylabel (str): Label for y axis. Default is None. Returns: tuple: (Figure, matplotlib.axes._subplots.AxesSubplot) """ if len(streams) < 1: raise Exception('No streams provided.') colors = cm.get_cmap(cmap) color_array = colors(np.linspace(0, 1, len(streams))) if figsize is None: figsize = (10, len(streams)) fig, ax = plt.subplots(figsize=figsize) for idx, stream in enumerate(streams): traces = stream.select(channel=channel) if len(traces) > 0: trace = traces[0] if normalize or scale != 1: warnings.filterwarnings("ignore", category=FutureWarning) trace.normalize() trace.data *= scale lat = trace.stats.coordinates['latitude'] lon = trace.stats.coordinates['longitude'] distance = gps2dist_azimuth(lat, lon, epilat, epilon)[0] / 1000 times = [] start = trace.stats.starttime for time in trace.times(): starttime = start td = datetime.timedelta(seconds=time) ti = starttime + td times += [ti.datetime] label = trace.stats.network + '.' + \ trace.stats.station + '.' + trace.stats.channel ax.plot(times, trace.data + distance, label=label, color=color_array[idx]) ax.invert_yaxis() ax.legend(bbox_to_anchor=(1, 1), fontsize=minfontsize) if title is None: title = ('Event on ' + str(starttime.month) + '/' + str(starttime.day) + '/' + str(starttime.year)) if scale != 1: title += ' scaled by ' + str(scale) if xlabel is None: xlabel = 'Time (H:M:S)' if ylabel is None: ylabel = 'Distance (km)' ax.set_title(title, fontsize=minfontsize + 4) ax.set_xlabel(xlabel, fontsize=minfontsize) ax.set_ylabel(ylabel, fontsize=minfontsize) ax.xaxis.set_tick_params(labelsize=minfontsize - 2) ax.yaxis.set_tick_params(labelsize=minfontsize - 2) if file is not None: fig.savefig(file, format='png') plt.show() return (fig, ax)