def coloured_chans_like_graphs(hillshade_file, tree_file): """ Plots outlines of channels taken from the *.tree file over a hillshade giving each channel a unique colour which corresponds to the colours used in the Chi plotting routines in chi_visualisation.py. """ label_size = 20 #title_size = 30 axis_size = 28 import matplotlib.pyplot as pp import numpy as np import matplotlib.colors as colors import matplotlib.cm as cmx from matplotlib import rcParams import matplotlib.lines as mpllines # make sure the nodata is formatted LSDP.CheckNoData(hillshade_file) #get data hillshade = LSDP.ReadRasterArrayBlocks(hillshade_file) #ignore nodata values hillshade = np.ma.masked_where(hillshade == -9999, hillshade) # now get the extent extent_raster = LSDP.GetRasterExtent(hillshade_file) x_min = extent_raster[0] x_max = extent_raster[1] y_min = extent_raster[2] y_max = extent_raster[3] #fonts rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['arial'] rcParams['font.size'] = label_size #get coordinates of streams from tree file channel_id = [] row = [] col = [] with open(tree_file, 'r') as f: lines = f.readlines() for q,line in enumerate(lines): if q > 0: #skip first line channel_id.append(int(line.split()[0])) row.append(float(line.split()[4])) col.append(float(line.split()[5])) #get bounding box & pad to 10% of the dimension x_max = max(col) x_min = min(col) y_max = max(row) y_min = min(row) pad_x = (x_max - x_min) * 0.1 pad_y = (x_max - y_min) * 0.1 if (pad_y > pad_x): pad_x = pad_y else: pad_y = pad_x x_max += pad_x x_min -= pad_x y_max += pad_y y_min -= pad_y fig = pp.figure(1, facecolor='white',figsize=(10,7.5)) ax = fig.add_subplot(1,1,1) ax.imshow(hillshade, vmin=0, vmax=255, cmap=cmx.gray) # now get the tick marks n_target_tics = 5 xlocs,ylocs,new_x_labels,new_y_labels = LSDP.GetTicksForUTM(hillshade_file,x_max,x_min,y_max,y_min,n_target_tics) pp.xticks(xlocs, new_x_labels, rotation=60) #[1:-1] skips ticks where we have no data pp.yticks(ylocs, new_y_labels) # some formatting to make some of the ticks point outward for line in ax.get_xticklines(): line.set_marker(mpllines.TICKDOWN) #line.set_markeredgewidth(3) for line in ax.get_yticklines(): line.set_marker(mpllines.TICKLEFT) #line.set_markeredgewidth(3) pp.xlim(x_min,x_max) pp.ylim(y_max,y_min) pp.xlabel('Easting (m)',fontsize = axis_size) pp.ylabel('Northing (m)', fontsize = axis_size) # channel ID Channel_ID_MIN = np.min(channel_id) Channel_ID_MAX = np.max(channel_id) cNorm_channel_ID = colors.Normalize(vmin=Channel_ID_MIN, vmax=Channel_ID_MAX) # the max number of channel segs is the 'top' colour jet = pp.get_cmap('jet') scalarMap_channel_ID = cmx.ScalarMappable(norm=cNorm_channel_ID, cmap=jet) #for a,i in enumerate(reversed(channel_id)): for a,i in enumerate(channel_id): if i != 0: # plot other stream segments colorVal = scalarMap_channel_ID.to_rgba(i) # this gets the distinct colour for this segment pp.scatter(col[a], row[a], 30,marker=".", color=colorVal,edgecolors='none') for a,i in enumerate(channel_id): if i == 0: # plot trunk stream in black pp.scatter(col[a], row[a], 40,marker=".", color='k',edgecolors='none') ax.spines['top'].set_linewidth(2.5) ax.spines['left'].set_linewidth(2.5) ax.spines['right'].set_linewidth(2.5) ax.spines['bottom'].set_linewidth(2.5) ax.tick_params(axis='both', width=2.5) pp.xlim(x_min,x_max) pp.ylim(y_max,y_min) pp.title("Channels colored by channel number",fontsize=label_size) pp.tight_layout() pp.show()
def sequential_color_mapper(value): sequential_cmap = cm.ScalarMappable(col.Normalize(0, max(value)), cm.YlGnBu) return sequential_cmap
def plot(self, ax, chrom_region, region_start, region_end): log.debug( f'chrom_region {chrom_region}, region_start {region_start}, region_end {region_end}' ) if chrom_region not in self.chrom_sizes: chrom_region_before = chrom_region chrom_region = change_chrom_names(chrom_region) if chrom_region not in self.chrom_sizes: self.log.warning( f"*Warning*\nNeither {chrom_region_before} nor {chrom_region} exists as a " f"chromosome name on the matrix. This will generate an empty track!!\n" ) self.img = None return chrom_region = self.check_chrom_str_bytes(self.chrom_sizes, chrom_region) if region_end > self.chrom_sizes[chrom_region]: self.log.warning( "*Warning*\nThe region to plot extends beyond the" " chromosome size. Please check.\n" f"{chrom_region} size: {self.chrom_sizes[chrom_region]}" f". Region to plot {region_start}-{region_end}\n") # expand region to plus depth on both sides # to avoid a 45 degree 'cut' on the edges # get bin id of start and end of region in given chromosome start_bp = max(0, region_start - self.properties['depth']) end_bp = min(self.chrom_sizes[chrom_region], region_end + self.properties['depth']) p1 = int(np.floor(start_bp / self.binsize)) p2 = int(np.ceil(end_bp / self.binsize)) # start pos need to include the last end start_pos = [int(i * self.binsize) for i in range(p1, p2 + 1)] # select only relevant matrix part matrix = self.hic_ma \ .matrix(balance=False, sparse=False) \ .fetch(f'{chrom_region}:{start_bp}-{end_bp}') matrix = np.triu(matrix) # limit the 'depth' based on the length of the region being viewed region_len = region_end - region_start depth = min(self.properties['depth'], int(region_len * 1.25)) if depth < self.properties['depth']: log.warning( f"The depth was set to {self.properties['depth']} which is more than 125%" " of the region plotted. The depth will be set " f"to {depth}.\n") # Replace all nan values by 0. np.nan_to_num(matrix, nan=0, copy=False) # scale matrix = matrix * self.properties['scale_factor'] if self.properties['transform'] == 'log1p': matrix += 1 elif self.properties['transform'] in ['-log', 'log']: if matrix.min() < 0: raise ValueError( 'HiC Matrix contains negative value, can not perform log transform.' ) # We first replace 0 values by minimum values after 0 mask = matrix == 0 try: matrix[mask] = matrix[~mask].min() matrix = np.log(matrix) except ValueError: self.log.info('All values are 0, no log applied.') else: if self.properties['transform'] == '-log': matrix *= -1 if self.properties['max_value'] is not None: vmax = self.properties['max_value'] else: # try to use a 'aesthetically pleasant' max value try: vmax = np.percentile(matrix.diagonal(1), 80) except IndexError: vmax = None if self.properties['min_value'] is not None: vmin = self.properties['min_value'] else: vmin = matrix.min() # if the region length is large with respect to the chromosome length, the diagonal may have # very few values or none. Thus, the following lines reduce the number of bins until the # diagonal is at least length 5 but make sure you have at least one value: num_bins_from_diagonal = max(1, int(region_len / self.binsize)) for num_bins in range(0, num_bins_from_diagonal)[::-1]: distant_diagonal_values = matrix.diagonal(num_bins) if len(distant_diagonal_values) > 5: break vmin = min(vmin, np.median(distant_diagonal_values)) self.log.info("setting min, max values for track " f"{self.properties['section_name']} to: " f"{vmin}, {vmax}\n") if self.properties['transform'] == 'log1p': self.norm = colors.LogNorm(vmin=vmin, vmax=vmax) else: self.norm = colors.Normalize(vmin=vmin, vmax=vmax) self.img = self.pcolormesh_45deg(ax, matrix, start_pos) if self.properties['rasterize']: self.img.set_rasterized(True) if self.properties['orientation'] == 'inverted': ax.set_ylim(depth, 0) else: ax.set_ylim(0, depth)
x = x[0:2400] print('ok') y = data['Grid/Grid_mid'].data[1]/1.0e-6 X, Y = np.meshgrid(x, y) name = 'Subset_high_e_density' den = data['Derived/Number_Density/electron'].data/denunit den_p = data['Derived/Number_Density/electron_no'].data/denunit den = den+den_p den = den[0:2400,:] if np.min(den.T) == np.max(den.T): continue levels = np.linspace(0.0, 52.499, 101) den.T[den.T > 52.499]=52.499 plt.contourf(X, Y, den.T, levels=levels, norm=mcolors.Normalize(vmin=levels.min(), vmax=levels.max()), cmap='Greys') #### manifesting colorbar, changing label and axis properties #### #cbar=plt.colorbar(ticks=np.linspace(0.0, 50.0, 5)) #cbar.set_label(name+'[$n_c$]', fontdict=font) name = 'ey' ex = data['Electric Field/'+str.capitalize(name)].data/exunit ex = ex[0:2400,:] if np.min(ex.T) == np.max(ex.T): continue levels = np.linspace(-22.5, 22.5, 21) ex.T[ex.T < -22.499]=-22.499 ex.T[ex.T > 22.499]= 22.499 plt.contour(X, Y, ex.T, levels=levels, cmap=cmap_br) #### manifesting colorbar, changing label and axis properties #### #cbar=plt.colorbar(ticks=np.linspace(-22.5, 22.5, 5))
def __init__( self, ax, cmap=None, norm=None, alpha=1.0, values=None, boundaries=None, orientation='vertical', extend='neither', spacing='uniform', # uniform or proportional ticks=None, format=None, drawedges=False, filled=True, ): self.ax = ax if cmap is None: cmap = cm.get_cmap() if norm is None: norm = colors.Normalize() self.alpha = alpha cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm) self.values = values self.boundaries = boundaries self.extend = extend self.spacing = spacing self.orientation = orientation self.drawedges = drawedges self.filled = filled # artists self.solids = None self.lines = None self.dividers = None self.extension_patch1 = None self.extension_patch2 = None if orientation == "vertical": self.cbar_axis = self.ax.yaxis else: self.cbar_axis = self.ax.xaxis if format is None: if isinstance(self.norm, colors.LogNorm): # change both axis for proper aspect self.ax.set_xscale("log") self.ax.set_yscale("log") self.cbar_axis.set_minor_locator(ticker.NullLocator()) formatter = ticker.LogFormatter() else: formatter = None elif isinstance(format, str): formatter = ticker.FormatStrFormatter(format) else: formatter = format # Assume it is a Formatter if formatter is None: formatter = self.cbar_axis.get_major_formatter() else: self.cbar_axis.set_major_formatter(formatter) if np.iterable(ticks): self.cbar_axis.set_ticks(ticks) elif ticks is not None: self.cbar_axis.set_major_locator(ticks) else: self._select_locator(formatter) self._config_axes() self.update_artists() self.set_label_text('')
bias=bias, tolerance=0.005, nMeasurements=10_000) # To plot samples, it's helpful to have colors for each. # We'll plot four cases: # - actually 0, classified as 0 # - actually 0, classified as 1 # - actually 1, classified as 1 # - actually 1, classified as 0 cases = [(0, 0), (0, 1), (1, 1), (1, 0)] # We can use these cases to define markers and colormaps for plotting. markers = [ '.' if actual == classified else 'x' for (actual, classified) in cases ] colormap = cmx.ScalarMappable(colors.Normalize(vmin=0, vmax=len(cases) - 1)) colors = [ colormap.to_rgba(idx_case) for (idx_case, case) in enumerate(cases) ] # It's also really helpful to have the samples as a NumPy array so that we # can find masks for each of the four cases. samples = np.array(data['ValidationData']['Features']) # Finally, we loop over the cases above and plot the samples that match # each. for (idx_case, ((actual, classified), marker, color)) in enumerate(zip(cases, markers, colors)): mask = np.logical_and(np.equal(actual_labels, actual), np.equal(classified_labels, classified)) if not np.any(mask):
den_a.T[den_a.T > eee] = eee #gs = gridspec.GridSpec(2, 2, width_ratios=[6, 1], height_ratios=[1, 3]) #ax=plt.subplot(3,2,1) ax = plt.subplot2grid((3, 3), (0, 0)) #axin1 = inset_axes(ax, width='15%', height='5%', loc='upper left',pad=0.2) #axin2 = inset_axes(ax, width='15%', height='5%', loc='lower left',pad=0.2) #axin1 = inset_axes(ax,width="5%",height="45%",loc='upper right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,) #axin2 = inset_axes(ax,width="5%",height="45%",loc='lower right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,) #### manifesting colorbar, changing label and axis properties #### image1 = ax.contourf(X, Y, den.T, levels=levels, norm=mcolors.Normalize(vmin=levels.min(), vmax=levels.max()), cmap='pink_r') ax.contour(X, Y, den_a.T, levels=[0.9], colors='limegreen', linewidths=3.5, origin='lower') # cbar=plt.colorbar(image1,pad=0.01,ticks=np.linspace(0.0, eee, 5),orientation="vertical") # cbar.set_label('$n_e$ [$n_c$]', fontdict=font2) # cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size']) name = 'ey' data = sdf.read(from_path + 'e_fields' + str(n1).zfill(4) + ".sdf", dict=True)
from skimage.measure import regionprops from skimage.transform import rotate from skimage import img_as_float from skimage import img_as_int from skimage import exposure from skimage.filters import threshold_otsu, threshold_adaptive import matplotlib.cm as cmx import matplotlib.colors as colors import seaborn as sns import pickle sns.set(style="ticks") values = range(100) RdYlBu = cm = plt.get_cmap('RdYlBu') cNorm = colors.Normalize(vmin=0, vmax=values[-1]) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=RdYlBu) Bl = scalarMap.to_rgba(values[-10]) Re = scalarMap.to_rgba(values[10]) #sns.set_style("whitegrid") #sns.set_style("whitegrid", {"legend.frameon": True}) rc = { 'font.size': 15, 'axes.labelsize': 15, 'legend.fontsize': 15.0, 'axes.titlesize': 15, 'xtick.labelsize': 15, 'ytick.labelsize': 15 }
def svg_validation_latlong(mod, lat, lon, extent=None, figsize=(6.0,10), show_diffs='linear', scaled_diffs=True, gridsize=60, headfont='Roboto Slab', textfont='Roboto', colormap='rainbow', tight_layout=True, headerlevel=2, header=None, short_header=None, colormin=None, colormax=None, omit_zero_zero=True, segmentation=None): """ A validation mapset for destination choice and similar models. Parameters ---------- lat, lon : ndarray Latitude and Longitude of the zonal centroids. Should be vectors with length equal to number of alternatives. extent : None or 4-tuple The limits of the map, give as (west_lon,east_lon,south_lat,north_lat). If None the limits are found automatically. figsize : tuple The (width,height) for the figure. show_diffs : {'linear', 'log', False} Whether to include a differences map, with linear or log scale. scaled_diffs : bool Include a scaled version of the diffs, scaled by log(obs). This de-emphasizes larger diffs when the total trips to the zone is very large. header : str, optional A header to prepend to the mapset, as a <hN> tag. headerlevel : int, optional The level N in the header tag. short_header : str, optional A shortened version of the header, for the table of contents. colormin, colormax : numeric If given use these values as the lower (upper) bound of the colormap normalization. segmentation : ndarray slicer or str, optional If given, this will be used to slice the first dimension of the probability and choice arrays, resulting in a segmented result (i.e. slice to get only observations that coorespond to a particular market segment.) If given as a string, it is first evaluated as a bool idco expression, with the result used as the slicer (in this case, a bool mask). """ from matplotlib import pyplot as plt plt.ioff() import matplotlib.colors as colors from matplotlib.ticker import LogLocator import matplotlib.cm as cm n_subplots = 2 if show_diffs: n_subplots += 1 if scaled_diffs: n_subplots += 1 plot_n = 1 if mod.data.weight is None: pr = mod.work.probability[:, :mod.nAlts()] ch = mod.data.choice.squeeze() wlabel = "" else: pr = mod.work.probability[:, :mod.nAlts()] * mod.data.weight ch = mod.data.choice.squeeze() * mod.data.weight wlabel = "Weighted " if segmentation is not None: if isinstance(segmentation, str): segmentation = mod.df.array_idco(segmentation, dtype=bool).squeeze() pr = pr[segmentation] ch = ch[segmentation] pr_0 = pr.sum(0).flatten() ch_0 = ch.sum(0).flatten() plt.clf() fig = plt.figure(figsize=figsize, tight_layout=tight_layout) def next_subplot(title=None, axisbg=None, ticks_off=True): ax = plt.subplot(n_subplots,1,next_subplot.plot_n, axisbg=axisbg) next_subplot.plot_n+=1 if title: ax.set_title(title, fontname=headfont) if ticks_off: ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) return ax next_subplot.plot_n = 1 if omit_zero_zero: retain = ~((lon==0) & (lat==0)) lon = lon[retain] lat = lat[retain] ch_0 = ch_0[retain] pr_0 = pr_0[retain] ax1 = next_subplot('Observed') hb1 = ax1.hexbin(lon, lat, C=ch_0, gridsize=gridsize, xscale='linear', yscale='linear', bins=None, extent=extent, cmap=colormap, norm=None, alpha=None, linewidths=0.1, edgecolors='none', reduce_C_function=numpy.sum, mincnt=None, marginals=False, data=None, ) ax2 = next_subplot('Modeled') hb2 = ax2.hexbin(lon, lat, C=pr_0, gridsize=gridsize, xscale='linear', yscale='linear', bins=None, extent=extent, cmap=colormap, norm=None, alpha=None, linewidths=0.1, edgecolors='none', reduce_C_function=numpy.sum, mincnt=None, marginals=False, data=None, ) # Renorm hb1 and hb2 to same scale renorm = colors.LogNorm() vst = numpy.vstack([hb1.get_array(),hb2.get_array()]) vst = vst[vst!=0] renorm.vmin=colormin renorm.vmax=colormax renorm.autoscale_None( vst ) hb1.set_norm( renorm ) hb2.set_norm( renorm ) # Colorbars cb = plt.colorbar(hb1, ax=ax1, ticks=LogLocator(subs=range(10))) cb.set_label(wlabel+'Counts', fontname=textfont) for l in cb.ax.yaxis.get_ticklabels(): l.set_family(textfont) cb = plt.colorbar(hb2, ax=ax2, ticks=LogLocator(subs=range(10))) cb.set_label(wlabel+'Total Prob', fontname=textfont) for l in cb.ax.yaxis.get_ticklabels(): l.set_family(textfont) # Diffs plots pr_ch_diff = pr_0-ch_0 if show_diffs: ax = next_subplot('Raw Over/Under-Prediction') hb = ax.hexbin(lon, lat, C=pr_ch_diff, gridsize=gridsize, xscale='linear', yscale='linear', bins=None, extent=extent, cmap='bwr_r', norm=None, alpha=None, linewidths=0.1, edgecolors='none', reduce_C_function=numpy.sum, mincnt=None, marginals=False, data=None, ) # Re-norm mid,top = numpy.percentile(numpy.abs(hb.get_array()),[66,99]) if show_diffs=='log': norm = colors.SymLogNorm(linthresh=mid, linscale=0.025, vmin=-top, vmax=top) else: norm = colors.Normalize(vmin=-top, vmax=top) hb.set_norm( norm ) cb = plt.colorbar(hb, ax=ax, extend='both') cb.set_label(wlabel+'Over / Under', fontname=textfont) for l in cb.ax.yaxis.get_ticklabels(): l.set_family(textfont) else: mid,top = None,None if scaled_diffs: pr_ch_diff_ = hb2.get_array()-hb1.get_array() pr_ch_scale = numpy.log1p((hb1.get_array()))+1 # Get bin centners verts = hb2.get_offsets() binx,biny = numpy.zeros_like(pr_ch_scale), numpy.zeros_like(pr_ch_scale) for offc in range(verts.shape[0]): binx[offc],biny[offc] = verts[offc][0],verts[offc][1] ax = next_subplot('Adjusted Over/Under-Prediction') hb = ax.hexbin(binx, biny, C=pr_ch_diff_/pr_ch_scale, gridsize=gridsize, xscale='linear', yscale='linear', bins=None, extent=extent, cmap='bwr_r', norm=None, alpha=None, linewidths=0.1, edgecolors='none', reduce_C_function=numpy.mean, mincnt=None, marginals=False, data=None, ) # Re-norm if mid is None or top is None: mid,top = numpy.percentile(numpy.abs(hb.get_array()),[66,99]) if show_diffs=='log': norm = colors.SymLogNorm(linthresh=mid, linscale=0.025, vmin=-top, vmax=top) else: norm = colors.Normalize(vmin=-top, vmax=top) hb.set_norm( norm ) plt.annotate('Raw Difference / (1+log(Observed Count+1))', xycoords='axes fraction', xy=(0.5,0), textcoords='offset points', xytext=(0,-2), horizontalalignment='center', verticalalignment='top', fontsize='x-small', fontstyle='italic') cb = plt.colorbar(hb, ax=ax, extend='both') cb.set_label(wlabel+'Over / Under', fontname=textfont) for l in cb.ax.yaxis.get_ticklabels(): l.set_family(textfont) return plt_as_svg_xhtml(headerlevel=headerlevel, header=header, anchor=short_header or header)
# -*- coding: utf-8 -*- """ Created on Fri Dec 3 15:26:34 2021 @author: Georgia Nixon """ place = "Georgia Nixon" import matplotlib.colors as col norm = col.Normalize(vmin=-1, vmax=1) from numpy import pi, log import numpy as np import matplotlib.pyplot as plt from scipy.special import jv, jn_zeros import pandas as pd import matplotlib as mpl import seaborn as sns from numpy import sin, cos, exp, pi import sys sys.path.append("/Users/" + place + "/Code/MBQD/floquet-simulations/src") from hamiltonians import hoppingHF, ConvertComplex, PhiString, ConvertFraction dataLoc = "C:/Users/" + place + "/OneDrive - University of Cambridge/MBQD/Data/floquet-simulations/" from fractions import Fraction def filter_duplicates(x): """ input dataframe, df.x, eg. df.localisation
filelist = sorted(glob.glob(winddir+windbasefile)) basemap_resolution = 'h' deg2km = 111125.1 cmap=plt.cm.jet cmap2=plt.cm.RdBu_r vmin = 0. vmax = 10. vmin2=-1.25 vmax2=1.25 dvar=2. dvar2=0.25 bounds = np.arange(vmin,vmax+0.01,dvar) norm = colors.Normalize(vmin=vmin,vmax=vmax+0.01) levels2plot = np.arange(vmin,vmax+0.001,dvar/10) bounds2 = np.arange(vmin2,vmax2+0.01,dvar2) bounds2[len(bounds2)/2] = 0 norm2 = colors.Normalize(vmin=vmin2,vmax=vmax2+0.01) levels2plot2 = np.arange(vmin2,vmax2+0.001,dvar2/10) #------------------------------------------------------------------------------------ # Region of interest lonmin = -13 lonmax = -9 latmin = 29 latmax = 33 dlon=1 dlat=1
y_optimizer.step() y_queue, _ = queue_update(queue=y_queue, m=m, K=K, t=t + 1, ft=copy.deepcopy(y_player.state_dict()), inc=inc) pbar.update(1) strategies.append([ x[0][0].item(), y[0][0].item() ]) # building trajectory for vis. Only the first strategy is plotted. # trajectory demonstration strategies = np.array(strategies)[0::Sample_fr] x = strategies[:-1, 0] y = strategies[:-1, 1] u = strategies[1:, 0] - strategies[:-1, 0] v = strategies[1:, 1] - strategies[:-1, 1] n = 0 color_array = np.sqrt(((u - n))**2 + ((v - n))**2) norm = colors.Normalize(color_array.min(), color_array.max()) color_array = cm.jet(norm(color_array)) plt.quiver(x, y, u, v, linewidth=0.0001, pivot='middle', color=color_array) plt.ioff() plt.plot() plt.savefig('ftpl_nonconvex') print("figure saved under the ftpl_nonconvex.png")
def plot_datasets(self, data, fname, extra_labels, showreboots=False, output='pdf'): """ Plot timeseries data (of type dataname). The data can be either simple (one or no datapoint at any point in time, or indexed (by indextype). dataname is assumed to be in the form of [title, [label1, label2, ...], [data1, data2, ...]] extra_labels is a list of tuples [(datetime, 'label'), ...] """ sar_parser = self.sar_parser title = data[0][0] unit = data[0][1] axis_labels = data[0][2] datanames = data[1] if not isinstance(datanames, list): raise Exception("plottimeseries expects a list of datanames: %s" % data) fig = plt.figure(figsize=(10.5, 6.5)) axes = fig.add_subplot(111) axes.set_title('{0} time series'.format(title), fontsize=12) axes.set_xlabel('Time') axes.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M')) # Twenty minutes. Could probably make it a parameter axes.xaxis.set_minor_locator(mdates.MinuteLocator(interval=20)) fig.autofmt_xdate() ylabel = title if unit: ylabel += " - " + unit axes.set_ylabel(ylabel) y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) axes.yaxis.set_major_formatter(y_formatter) axes.yaxis.get_major_formatter().set_scientific(False) color_norm = colors.Normalize(vmin=0, vmax=len(datanames) - 1) scalar_map = cm.ScalarMappable(norm=color_norm, cmap=plt.get_cmap('Set1')) timestamps = self.timestamps() counter = 0 for i in datanames: try: dataset = [sar_parser._data[d][i] for d in timestamps] except: print("Key {0} does not exist in this graph".format(i)) raise axes.plot(timestamps, dataset, 'o:', label=axis_labels[counter], color=scalar_map.to_rgba(counter)) counter += 1 # Draw extra_labels if extra_labels: for extra in extra_labels: axes.annotate(extra[1], xy=(mdates.date2num(extra[0]), sar_parser.find_max(extra[0], datanames)), xycoords='data', xytext=(30, 30), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # If we have a sosreport draw the reboots if showreboots and sar_parser.sosreport is not None and \ sar_parser.sosreport.reboots is not None: reboots = sar_parser.sosreport.reboots for reboot in reboots.keys(): reboot_date = reboots[reboot]['date'] rboot_x = mdates.date2num(reboot_date) (xmin, xmax) = plt.xlim() (ymin, ymax) = plt.ylim() if rboot_x < xmin or rboot_x > xmax: continue axes.annotate('', xy=(mdates.date2num(reboot_date), ymin), xycoords='data', xytext=(-30, -30), textcoords='offset points', arrowprops=dict(arrowstyle="->", color='blue', connectionstyle="arc3,rad=-0.1")) # Show any data collection gaps in the graph gaps = sar_parser.find_data_gaps() if len(gaps) > 0: for i in gaps: (g1, g2) = i x1 = mdates.date2num(g1) x2 = mdates.date2num(g2) (ymin, ymax) = plt.ylim() axes.add_patch( Rectangle((x1, ymin), x2 - x1, ymax - ymin, facecolor="lightgrey")) # Add a grid to the graph to ease visualization axes.grid(True) lgd = None # Draw the legend only when needed if len(datanames) > 1 or \ (len(datanames) == 1 and len(datanames[0].split('#')) > 1): # We want the legends box roughly square shaped # and not take up too much room props = matplotlib.font_manager.FontProperties(size='xx-small') if len(datanames) < LEGEND_THRESHOLD: cols = int((len(datanames)**0.5)) lgd = axes.legend(loc=1, ncol=cols, shadow=True, prop=props) else: cols = int(len(datanames)**0.6) lgd = axes.legend(loc=9, ncol=cols, bbox_to_anchor=(0.5, -0.29), shadow=True, prop=props) if len(datanames) == 0: return None try: if lgd: plt.savefig(fname, bbox_extra_artists=(lgd, ), bbox_inches='tight') else: plt.savefig(fname, bbox_inches='tight') except: import traceback print(traceback.format_exc()) import sys sys.exit(-1) plt.cla() plt.clf() plt.close('all')
UCERF3_FILE_FRIC = WORKING_DIR + 'UCERF3/UCERF3_EQSim_ReFaulted_ReSectioned_ReElemented_AseismicCut_0.11_Friction.dat' FINAL_FILE_GEO = WORKING_DIR + 'UCERF3/UCERF3_EQSim_ReIndexed_AseismicCut_0.11_Geometry.dat' FINAL_FILE_FRIC = WORKING_DIR + 'UCERF3/UCERF3_EQSim_ReIndexed_AseismicCut_0.11_Friction.dat' # ======== READ the actual strikes from the original model ========= STRIKE_FILE = WORKING_DIR + 'section_strikes_with_fixes.txt' # SAF strikes fixed strike_file = open(STRIKE_FILE, 'r') section_strikes = {} for line in strike_file: name, secs = line.split(" = ") section_strikes[name] = [float(num) for num in secs.split()] strike_file.close() #------------- UTILITIES --------------------------------- cmap = plt.get_cmap('Reds') norm = mcolor.Normalize(vmin=-.1, vmax=1) def get_color(magnitude): mag_slope = 1.0 / 1.1 return cmap(mag_slope * (magnitude + .1)) def dotproduct(v1, v2): return sum((a * b) for a, b in zip(v1, v2)) def length(v): return math.sqrt(dotproduct(v, v))
def network_evolve(N, J_couplings, H_fields): npoints = 100 param_range = np.linspace(0, 1, npoints) g = nx.Graph() for i in range(N): g.add_node(i) for i in range(N): for j in range(N): if (J_couplings[i, j] != 0): g.add_edge(i, j) g[i][j]["coupling"] = J_couplings[i, j] pos_fix = nx.spring_layout(g, k=0.2) #print(J_couplings) cumulative_spin = np.zeros((npoints, N)) for i in range(npoints): plt.clf() plt.close() gs = gridspec.GridSpec(8, 7) fig = plt.figure(figsize=(30, 30)) ax1 = plt.subplot(gs[0:5, 0:5]) plt.suptitle("Evolution of spins, parameter \u03BB=" + str("%.2f" % param_range[i]), fontsize=30) cumulative_spin[0, :] = 0 #plt.subplot(221)# draw_networkx_nodes versus nx.draw # draw_networkx_nodes versus nx.draw for j in range(N): g.nodes[j]["spin"] = expectation_values(N, param_range[i], J_couplings, H_fields)[j] cumulative_spin[i, :] = expectation_values(N, param_range[i], J_couplings, H_fields) color_the_nodes = [ (g.nodes[i]["spin"] * np.heaviside(g.nodes[i]["spin"], 0.5), 0, np.abs(g.nodes[i]["spin"]) * (np.heaviside(-g.nodes[i]["spin"], 0.5))) for i in range(N) ] color_the_edges = [ 'r' if J_couplings[i, j] > 0 else 'b' for i in range(N) for j in range(i) ] width_of_edges = [ 2 + 8 * abs(J_couplings[i, j]) for i in range(N) for j in range(i) ] nx.draw(g, pos=pos_fix, node_color=color_the_nodes, node_size=[ 2000 + 2000 * abs(g.nodes[i]["spin"]) for i in range(N) ], edge_color=color_the_edges, width=width_of_edges, with_labels=True, font_size=40, font_color='w', ax=ax1) #plt.subplot(222) ax2 = plt.subplot(gs[0:4, 5:8]) ax2.set_title("Couplings", fontsize=35) cmap = plt.cm.seismic norm = colors.Normalize(vmin=-1, vmax=1) jcoupl = ax2.imshow(J_couplings, cmap='seismic', vmin=np.amin(J_couplings), vmax=np.amax(J_couplings)) ax2.tick_params(axis='both', labelsize=30) cbar = fig.colorbar(jcoupl, cmap='seismic', norm=norm) cbar.ax.tick_params(labelsize=40) # plt.colors.Normalize(vmin=5, vmax=10) #plt.colorbar(plt.cm.ScalarMappable( cmap=cmap), orientation='horizontal', label='Some Units') ax3 = plt.subplot(gs[4:5, 5:8]) #ax3.H_fields,cmap='seismic') ax3.text(0.2, 2., s="H fields:", size=30) for l in range(H_fields.size): ax3.text(0.2, 1.75 - l * 0.175, s="h_" + str(l) + "=" + str("%.2f" % H_fields[l]), size=30) plt.setp(plt.gca(), frame_on=False, xticks=(), yticks=()) plt.xticks(fontsize=0) plt.yticks(fontsize=0) #plt.imshow(J_couplings,cmap='seismic',vmin=-1,vmax=1) #ax4=fig.add_subplot(323) #plt.plot(np.sin(np.linspace(0,10,100))) #plt. ax4 = plt.subplot(gs[5:-1, :]) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.xlim(0, 1) plt.ylim(-1, 1) for k in range(N): ax4.plot(param_range[:i], cumulative_spin[:i, k], label="Spin " + str(k), linewidth=5) plt.legend(loc='upper left', fontsize=20) #ax4=fig.add_subplot(223) #plt.figure(figsize=(8,8)) #plt.subplot(3,2,1) #plt.subplot(3,2,3) #plt.subplot(3,2,5) #plt.subplot(2,2,2) #plt.subplot(2,2,4) #plt.imshow(J_couplings,cmap='seismic') plt.savefig("evolution_new" + str(i) + ".png") plt.show() return 1
def plot_data(lda, X, y, y_pred, fig_index): splot = plt.subplot(2, 2, fig_index) if fig_index == 1: plt.title('Linear Discriminant Analysis') plt.ylabel('Data with\n fixed covariance') elif fig_index == 2: plt.title('Quadratic Discriminant Analysis') elif fig_index == 3: plt.ylabel('Data with\n varying covariances') tp = (y == y_pred) # True Positive tp0, tp1 = tp[y == 0], tp[y == 1] X0, X1 = X[y == 0], X[y == 1] X0_tp, X0_fp = X0[tp0], X0[~tp0] X1_tp, X1_fp = X1[tp1], X1[~tp1] alpha = 0.5 # class 0: dots plt.plot(X0_tp[:, 0], X0_tp[:, 1], 'o', alpha=alpha, color='red', markeredgecolor='k') plt.plot(X0_fp[:, 0], X0_fp[:, 1], '*', alpha=alpha, color='#990000', markeredgecolor='k') # dark red # class 1: dots plt.plot(X1_tp[:, 0], X1_tp[:, 1], 'o', alpha=alpha, color='blue', markeredgecolor='k') plt.plot(X1_fp[:, 0], X1_fp[:, 1], '*', alpha=alpha, color='#000099', markeredgecolor='k') # dark blue # class 0 and 1 : areas nx, ny = 200, 100 x_min, x_max = plt.xlim() y_min, y_max = plt.ylim() xx, yy = np.meshgrid(np.linspace(x_min, x_max, nx), np.linspace(y_min, y_max, ny)) Z = lda.predict_proba(np.c_[xx.ravel(), yy.ravel()]) Z = Z[:, 1].reshape(xx.shape) plt.pcolormesh(xx, yy, Z, cmap='red_blue_classes', norm=colors.Normalize(0., 1.)) plt.contour(xx, yy, Z, [0.5], linewidths=2., colors='k') # means plt.plot(lda.means_[0][0], lda.means_[0][1], 'o', color='black', markersize=10, markeredgecolor='k') plt.plot(lda.means_[1][0], lda.means_[1][1], 'o', color='black', markersize=10, markeredgecolor='k') return splot
def plot(self): """ plots the model with: -a radio dial for depth slice -radio dial for resistivity value """ # set plot properties plt.rcParams['font.size'] = self.font_size plt.rcParams['figure.subplot.left'] = self.subplot_left plt.rcParams['figure.subplot.right'] = self.subplot_right plt.rcParams['figure.subplot.bottom'] = self.subplot_bottom plt.rcParams['figure.subplot.top'] = self.subplot_top font_dict = {'size': self.font_size + 2, 'weight': 'bold'} # make sure there is a model to plot if self.res_model is None: self.get_model() self.cmin = np.floor(np.log10(min(self.res_list))) self.cmax = np.ceil(np.log10(max(self.res_list))) # -->Plot properties plt.rcParams['font.size'] = self.font_size # need to add an extra row and column to east and north to make sure # all is plotted see pcolor for details. plot_east = self.grid_east / self.dscale plot_north = self.grid_north / self.dscale # make a mesh grid for plotting # the 'ij' makes sure the resulting grid is in east, north self.mesh_east, self.mesh_north = np.meshgrid(plot_east, plot_north, indexing='ij') self.fig = plt.figure(self.fig_num, self.fig_size, dpi=self.fig_dpi) plt.clf() self.ax1 = self.fig.add_subplot(1, 1, 1, aspect='equal') # transpose to make x--east and y--north plot_res = np.log10(self.res_model[:, :, self.depth_index].T) self.mesh_plot = self.ax1.pcolormesh(self.mesh_east, self.mesh_north, plot_res, cmap=self.cmap, vmin=self.cmin, vmax=self.cmax) # on plus or minus change depth slice self.cid_depth = \ self.mesh_plot.figure.canvas.mpl_connect('key_press_event', self._on_key_callback) # plot the stations if self.station_east is not None: for ee, nn in zip(self.station_east, self.station_north): self.ax1.text(ee / self.dscale, nn / self.dscale, '*', verticalalignment='center', horizontalalignment='center', fontdict={ 'size': self.font_size - 2, 'weight': 'bold' }) # set axis properties if self.xlimits is not None: self.ax1.set_xlim(self.xlimits) else: self.ax1.set_xlim(xmin=self.grid_east.min() / self.dscale, xmax=self.grid_east.max() / self.dscale) if self.ylimits is not None: self.ax1.set_ylim(self.ylimits) else: self.ax1.set_ylim(ymin=self.grid_north.min() / self.dscale, ymax=self.grid_north.max() / self.dscale) # self.ax1.xaxis.set_minor_locator(MultipleLocator(100*1./dscale)) # self.ax1.yaxis.set_minor_locator(MultipleLocator(100*1./dscale)) self.ax1.set_ylabel('Northing (' + self.map_scale + ')', fontdict=self.fdict) self.ax1.set_xlabel('Easting (' + self.map_scale + ')', fontdict=self.fdict) depth_title = self.grid_z[self.depth_index] / self.dscale self.ax1.set_title('Depth = {:.3f} '.format(depth_title) + \ '(' + self.map_scale + ')', fontdict=self.fdict) # plot the grid if desired self.east_line_xlist = [] self.east_line_ylist = [] for xx in self.grid_east: self.east_line_xlist.extend([xx / self.dscale, xx / self.dscale]) self.east_line_xlist.append(None) self.east_line_ylist.extend([ self.grid_north.min() / self.dscale, self.grid_north.max() / self.dscale ]) self.east_line_ylist.append(None) self.ax1.plot(self.east_line_xlist, self.east_line_ylist, lw=.25, color='k') self.north_line_xlist = [] self.north_line_ylist = [] for yy in self.grid_north: self.north_line_xlist.extend([ self.grid_east.min() / self.dscale, self.grid_east.max() / self.dscale ]) self.north_line_xlist.append(None) self.north_line_ylist.extend([yy / self.dscale, yy / self.dscale]) self.north_line_ylist.append(None) self.ax1.plot(self.north_line_xlist, self.north_line_ylist, lw=.25, color='k') # plot the colorbar # self.ax2 = mcb.make_axes(self.ax1, orientation='vertical', shrink=.35) self.ax2 = self.fig.add_axes([.81, .45, .16, .03]) self.ax2.xaxis.set_ticks_position('top') # seg_cmap = ws.cmap_discretize(self.cmap, len(self.res_list)) self.cb = mcb.ColorbarBase(self.ax2, cmap=self.cmap, norm=colors.Normalize(vmin=self.cmin, vmax=self.cmax), orientation='horizontal') self.cb.set_label('Resistivity ($\Omega \cdot$m)', fontdict={'size': self.font_size}) self.cb.set_ticks(np.arange(self.cmin, self.cmax + 1)) self.cb.set_ticklabels([ mtplottools.labeldict[cc] for cc in np.arange(self.cmin, self.cmax + 1) ]) # make a resistivity radio button # resrb = self.fig.add_axes([.85,.1,.1,.2]) # reslabels = ['{0:.4g}'.format(res) for res in self.res_list] # self.radio_res = widgets.RadioButtons(resrb, reslabels, # active=self.res_dict[self.res_value]) # slider_ax_bounds = list(self.cb.ax.get_position().bounds) # slider_ax_bounds[0] += .1 slider_ax = self.fig.add_axes([.81, .5, .16, .03]) self.slider_res = widgets.Slider(slider_ax, 'Resistivity', self.cmin, self.cmax, valinit=2) # make a rectangular selector self.rect_selector = widgets.RectangleSelector(self.ax1, self.rect_onselect, drawtype='box', useblit=True) plt.show() # needs to go after show() self.slider_res.on_changed(self.set_res_value)
def _imshow_grid_values( grid, values, plot_name=None, var_name=None, var_units=None, grid_units=(None, None), symmetric_cbar=False, cmap="pink", limits=None, colorbar_label=None, allow_colorbar=True, vmin=None, vmax=None, norm=None, shrink=1.0, color_for_closed="black", color_for_background=None, show_elements=False, output=None, ): cmap = plt.get_cmap(cmap) if color_for_closed is not None: cmap.set_bad(color=color_for_closed) else: cmap.set_bad(alpha=0.0) if isinstance(grid, RasterModelGrid): if values.ndim != 2: raise ValueError("values must have ndim == 2") y = (np.arange(values.shape[0] + 1) * grid.dy - grid.dy * 0.5 + grid.xy_of_lower_left[1]) x = (np.arange(values.shape[1] + 1) * grid.dx - grid.dx * 0.5 + grid.xy_of_lower_left[0]) kwds = dict(cmap=cmap) (kwds["vmin"], kwds["vmax"]) = (values.min(), values.max()) if (limits is None) and ((vmin is None) and (vmax is None)): if symmetric_cbar: (var_min, var_max) = (values.min(), values.max()) limit = max(abs(var_min), abs(var_max)) (kwds["vmin"], kwds["vmax"]) = (-limit, limit) elif limits is not None: (kwds["vmin"], kwds["vmax"]) = (limits[0], limits[1]) else: if vmin is not None: kwds["vmin"] = vmin if vmax is not None: kwds["vmax"] = vmax myimage = plt.pcolormesh(x, y, values, **kwds) myimage.set_rasterized(True) plt.gca().set_aspect(1.0) plt.autoscale(tight=True) if allow_colorbar: cb = plt.colorbar(norm=norm, shrink=shrink) if colorbar_label: cb.set_label(colorbar_label) else: import matplotlib.colors as colors import matplotlib.cm as cmx if limits is not None: (vmin, vmax) = (limits[0], limits[1]) else: if vmin is None: vmin = values.min() if vmax is None: vmax = values.max() if symmetric_cbar: vmin, vmax = -max(abs(vmin), abs(vmax)), max( abs(vmin), abs(vmax)) cNorm = colors.Normalize(vmin, vmax) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap) colorVal = scalarMap.to_rgba(values)[grid.node_at_cell] patches = [] for corners in grid.corners_at_cell: valid_corners = corners[corners != grid.BAD_INDEX] closed_loop_corners = np.concatenate( [valid_corners, [valid_corners[0]]]) x = grid.x_of_corner[closed_loop_corners] y = grid.y_of_corner[closed_loop_corners] xy = np.vstack((x, y)).T patches.append(Polygon(xy, closed=True, fill=True)) patchcollection = PatchCollection(patches, facecolor=colorVal, edgecolor=colorVal) ax = plt.gca() ax.add_collection(patchcollection) if show_elements: x = grid.x_of_corner[grid.corners_at_face] y = grid.y_of_corner[grid.corners_at_face] segs = np.dstack((x, y)) line_segments = LineCollection(segs) line_segments.set_color("black") ax.add_collection(line_segments) ax.set_aspect(1.0) ax.set_rasterized(True) plt.xlim((np.min(grid.x_of_node), np.max(grid.x_of_node))) plt.ylim((np.min(grid.y_of_node), np.max(grid.y_of_node))) scalarMap.set_array(values) if allow_colorbar: cb = plt.colorbar(scalarMap, shrink=shrink) if grid_units[1] is None and grid_units[0] is None: grid_units = grid.axis_units if grid_units[1] == "-" and grid_units[0] == "-": plt.xlabel("X") plt.ylabel("Y") else: plt.xlabel("X (%s)" % grid_units[1]) plt.ylabel("Y (%s)" % grid_units[0]) else: plt.xlabel("X (%s)" % grid_units[1]) plt.ylabel("Y (%s)" % grid_units[0]) if plot_name is not None: plt.title("%s" % (plot_name)) if var_name is not None or var_units is not None: if var_name is not None: assert type(var_name) is str if var_units is not None: assert type(var_units) is str colorbar_label = var_name + " (" + var_units + ")" else: colorbar_label = var_name else: assert type(var_units) is str colorbar_label = "(" + var_units + ")" assert type(colorbar_label) is str assert allow_colorbar cb.set_label(colorbar_label) if color_for_background is not None: plt.gca().set_facecolor(color_for_background) if output is not None: if type(output) is str: plt.savefig(output) plt.clf() elif output: plt.show()
def make_cylinder_graphic(node_df, str_time_steps, inputs): times = [] stills = [] times = ['T @ ' + i for i in str_time_steps] timesteps = list(np.arange(0, (inputs['TimeIterations[#]'] + 1))) for n, i in enumerate(times): max_temp = node_df[i].max() min_temp = node_df[i].min() normalize = colors.Normalize(vmin=min_temp, vmax=max_temp) fig = plt.figure() ax = plt.gca() ax.set_aspect('equal') heatmap = ax.tricontourf(node_df['x'], node_df['y'], node_df[i], cmap=cm.viridis, norm=normalize, alpha=0.9) plt.axis('off') cbaxes = fig.add_axes([0.02, 0.1, 0.03, 0.8]) # This is the position for the colorbar fig.colorbar(heatmap, cax=cbaxes, format='%.1f') new_axis = fig.add_axes(ax.get_position(), projection='polar', frameon=False, rlabel_position=90) new_axis.set_theta_zero_location("S") new_axis.yaxis.grid(color='w', linewidth=0.75, alpha=0.2) new_axis.xaxis.grid(color='w', linewidth=0.75, alpha=0.2) radii_ticks = np.round(np.unique(node_df['radii'].values), 1) new_axis.set_rticks(radii_ticks) new_axis.set_title('Temperature After {0}s [K]'.format( "{:2.2f}".format(timesteps[n] * inputs['TimeStep[s]']))) filename = os.path.dirname(os.getcwd()) + r'/tmp/3d_Temp_Step' + str( timesteps[n]) + '.png' stills.append(filename) plt.savefig(filename, dpi=96) plt.close(fig) print('\rCreating image {0} of {1}.'.format(int(n) + 1, len(times)), end='', flush=True) fps = len(timesteps) / 60 print('\nCreating gif file...') gif_path = os.path.dirname(os.getcwd()) + r'/Output/TimeGraph.gif' with imageio.get_writer(gif_path, mode='I', duration=fps) as writer: for still in stills: image = imageio.imread(still) writer.append_data(image) print('\rCreating mp4 file...') vid_path = os.path.dirname(os.getcwd()) + r'/Output/TimeGraph.mp4' writer = imageio.get_writer(vid_path, fps=fps, macro_block_size=1) for still in stills: writer.append_data(imageio.imread(still)) writer.close()
def _UpdateDataSetValues(self): """ """ self.dataSetValues = None self.imageData = None self.npinx = self.npiny = 0 self.channelMode = self.dmgr.IsChannelType(self.curDataSet) ds_type = self.dmgr.GetDataSetType(self.curDataSet) self.nodalMode = self.dmgr.IsNodalType(ds_type) # -- Must have data # -- core = dset = None if self.dmgr.HasData(): dset = self.dmgr.GetH5DataSet(self.curDataSet, self.timeValue) core = self.dmgr.GetCore() if dset is not None and core is not None: # -- "Item" refers to channel or pin # -- item_factors = None if self.state.weightsMode == 'on': item_factors = self.dmgr.GetFactors(self.curDataSet) dset_array = np.array(dset) dset_shape = dset.shape ## if self.nodalMode: ## #self.npinx = self.npiny = item_col_limit = item_row_limit = 2 ## self.npinx = self.npiny = 2 ## else: ## item_col_limit = core.npinx ## item_row_limit = core.npiny ## if self.channelMode: ## item_col_limit += 1 ## item_row_limit += 1 ## self.npinx = min( item_col_limit, dset_shape[ 1 ] ) ## self.npiny = min( item_row_limit, dset_shape[ 0 ] ) if self.nodalMode: self.npinx = self.npiny = 2 else: self.npinx = dset_shape[1] self.npiny = dset_shape[0] draw_value_flag = \ self.curDataSet is not None and \ dset_shape[ 0 ] == 1 and dset_shape[ 1 ] == 1 node_value_draw_list = [] #assy_value_draw_list = [] del self.textDrawList[:] axial_level = min(self.axialValue.pinIndex, dset_shape[2] - 1) axial_value = \ self.dmgr.GetAxialValue( self.curDataSet, core_ndx = axial_level ) self.cellRange = self.dmgr.ExtractSymmetryExtent() im_wd = self.cellRange[4] * self.npinx im_ht = self.cellRange[5] * self.npiny self.dataSetValues = np.empty((im_wd, im_ht), dtype=np.float64) self.dataSetValues[:] = np.nan self.imageData = np.zeros((im_wd, im_ht, 4), dtype=np.uint8) # -- Create mapper # -- ds_range = self._ResolveDataRange( self.curDataSet, self.timeValue if self.state.scaleMode == 'state' else -1.0) if self.scaleType == 'log': norm = colors.LogNorm(vmin=max(ds_range[0], 1.0e-16), vmax=max(ds_range[1], 1.0e-16), clip=True) else: norm = colors.Normalize(vmin=ds_range[0], vmax=ds_range[1], clip=True) self.mapper = cm.ScalarMappable(norm=norm, cmap=cm.get_cmap( self.colormapName)) self.mapper.set_array(dset_array) #trans_color_arr = np.array( [ 200, 200, 200, 255 ], dtype = np.uint8 ) fc = np.array(self.fig.get_facecolor()) * 255.0 trans_color_arr = fc.astype(np.uint8) # -- Map data values to colors # -- im_row = 0 for assy_row in range(self.cellRange[1], self.cellRange[3]): im_row_to = im_row + self.npiny im_col = 0 for assy_col in range(self.cellRange[0], self.cellRange[2]): im_col_to = im_col + self.npinx assy_ndx = core.coreMap[assy_row, assy_col] - 1 if assy_ndx < 0 or assy_ndx >= dset_shape[3]: self.imageData[ im_row : im_row_to, im_col : im_col_to ] = \ trans_color_arr else: # if assy_ndx >= 0 and assy_ndx < dset_shape[ 3 ]: cur_array = dset_array[:, :, axial_level, assy_ndx] cur_colors = self.mapper.to_rgba(cur_array, bytes=True) if item_factors is not None: cur_factors = item_factors[:, :, axial_level, assy_ndx] cur_colors[cur_factors == 0] = trans_color_arr cur_colors[np.isnan(cur_array)] = trans_color_arr cur_colors[np.isinf(cur_array)] = trans_color_arr if self.nodalMode: cur_array = cur_array.reshape((2, 2)) cur_colors = cur_colors.reshape((2, 2, 4)) self.dataSetValues[ im_row : im_row_to, im_col : im_col_to ] = \ cur_array self.imageData[ im_row : im_row_to, im_col : im_col_to ] = \ cur_colors #end else assy_ndx >= 0 and assy_ndx < dset_shape[ 3 ] im_col = im_col_to #end for assy_col in range( self.cellRange[ 0 ], self.cellRange[ 2 ] ) im_row = im_row_to #end for assy_row in range( self.cellRange[ 1 ], self.cellRange[ 3 ] ) if draw_value_flag: for r in range(im_ht): for c in range(im_wd): if not np.array_equal(self.imageData[r, c], trans_color_arr): clr = Widget.GetContrastColor(*self.imageData[r, c]) self.textDrawList.append((self._CreateValueString( self.dataSetValues[r, c]), np.array(clr) / 255.0, c + 0.5, r + 0.5)) #end if draw_value_flag tickbase = self.npiny / 2.0 self.ytickLocs = [(i * self.npiny) + tickbase for i in range(self.cellRange[5])] self.ytickLabels = [ core.GetRowLabel(i) for i in range(self.cellRange[1], self.cellRange[3]) ] tickbase = self.npinx / 2.0 self.xtickLocs = [(i * self.npinx) + tickbase for i in range(self.cellRange[4])] self.xtickLabels = [ core.GetColLabel(i) for i in range(self.cellRange[0], self.cellRange[2]) ]
from os import listdir from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter files = listdir('.\datafiles') files = [[files[2 * i], files[2 * i + 1]] for i in range(0, int(len(files) / 2))] print(files) lorentz = np.loadtxt('LorentzData.txt') rossler = np.loadtxt('RosslerData.txt') #Make color maps col = cm.get_cmap('plasma') #Lorentz lornorm = colors.Normalize(vmin=min(lorentz.T[2]), vmax=max(lorentz.T[2])) lorcolors = [col(lornorm(value)) for value in lorentz.T[2]] #Rossler rossnorm = colors.Normalize(vmin=min(rossler.T[2]), vmax=max(rossler.T[2])) rosscolors = [col(lornorm(value)) for value in rossler.T[2]] ################################ Plot original datasets ################################# # fig = plt.figure() # axlor = plt.subplot(121,projection = '3d') # axros = plt.subplot(122,projection = '3d') # # Rossler plot # axros.plot(rossler[:,0],rossler[:,1],rossler[:,2],linewidth=0.7,alpha = 0.8) # # Rossler plot # axlor.plot(lorentz[:,0],lorentz[:,1],lorentz[:,2],linewidth=0.7,alpha = 0.8) # plt.show()
def _norm(): return mcolors.Normalize() # autoscale
def __init__( self, ax, cmap=None, norm=None, alpha=None, values=None, boundaries=None, orientation='vertical', ticklocation='auto', extend='neither', spacing='uniform', # uniform or proportional ticks=None, format=None, drawedges=False, filled=True, extendfrac=None, extendrect=False, label='', ): #: The axes that this colorbar lives in. self.ax = ax self._patch_ax() if cmap is None: cmap = cm.get_cmap() if norm is None: norm = colors.Normalize() self.alpha = alpha cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm) self.values = values self.boundaries = boundaries self.extend = extend self._inside = self._slice_dict[extend] self.spacing = spacing self.orientation = orientation self.drawedges = drawedges self.filled = filled self.extendfrac = extendfrac self.extendrect = extendrect self.solids = None self.lines = list() self.outline = None self.patch = None self.dividers = None if ticklocation == 'auto': ticklocation = 'bottom' if orientation == 'horizontal' else 'right' self.ticklocation = ticklocation self.set_label(label) if cbook.iterable(ticks): self.locator = ticker.FixedLocator(ticks, nbins=len(ticks)) else: self.locator = ticks # Handle default in _ticker() if format is None: if isinstance(self.norm, colors.LogNorm): self.formatter = ticker.LogFormatterMathtext() else: self.formatter = ticker.ScalarFormatter() elif cbook.is_string_like(format): self.formatter = ticker.FormatStrFormatter(format) else: self.formatter = format # Assume it is a Formatter # The rest is in a method so we can recalculate when clim changes. self.config_axis() self.draw_all()
def _run(args): executable = 'python3' if args.py3 else 'python' port = 1769 nthreads = args.numthreads settings = deep_trainer.TrainSettings( train_bot='or_reinforce.deep.deep2.deep2', adver_bot='optimax_rogue_bots.randombot.RandomBot', bot_folder=os.path.join('out', 'or_reinforce', 'deep', 'deep2'), train_seq=[ deep_trainer.SessionSettings( tie_len=111, tar_ticks=args.numexps, train_force_amount=args.train_force_amount, regul_factor=args.regul_factor, beta=args.beta, alpha=args.alpha, holdover=0, balance=True, balance_technique='action') ], cur_ind=0 ) deep_trainer._get_experiences_async( # pylint: disable=protected-access settings, executable, port, port+nthreads*10, 0, False, False, nthreads) network = deep2.Deep2Network.load(deep2.EVAL_MODELFILE) states, exps = get_unique_states_with_exps(deep2.REPLAY_FOLDER) network.eval() with torch.no_grad(): labels = network(states) print(f'loaded {len(states)} states for analysis...') train_pwl = pwl.SimplePointWithLabelProducer(states, labels, 4, True) print('--storing meta info--') store_meta(network, states, exps) print('--fetching top 3 pcs--') traj: pca_gen.PCTrajectoryGen = pca_gen.find_trajectory(network, train_pwl, 3) if args.pca3d: print('--performing 3d plot--') if USE_MARKER_SHAPES: markers = MODULE + '._markers' ots = MODULE + '._ots' norm = MODULE + '._norm' cmap = 'cividis' else: print('--caching markers--') _cache_markers(_correctness_markers(network, states, exps)) markers = MODULE + '._mark_cached_moves' ots = MODULE + '._ots_argmax' norm = MODULE + '._norm' cmap = 'Set1' print('--generating clusters--') clusts = [] for lyr, snap in enumerate(traj.snapshots): print(f'--generating clusters for layer {lyr}--') snap: pca_gen.PCTrajectoryGenSnapshot lyr_clusts: clusters.Clusters = clusters.find_clusters(snap.projected_samples.numpy()) clusts.append(lyr_clusts) print(f'--found {lyr_clusts.num_clusters} clusters for layer {lyr}--') print('--beginning plot--') pca_3d.plot_gen(traj, os.path.join(SAVEDIR, 'pca_3d'), True, markers, ots, norm, cmap, args.mpf, args.marker_size, None, ['Input', 'Layer 1', 'Layer 2', 'Layer 3', 'Layer 4', 'Layer 5', 'Layer 6', 'Output'], clusts) print('--plotting top 2 pcs--') pca_deep2.plot_trajectory(traj, os.path.join(SAVEDIR, 'pca'), exist_ok=True, transparent=False, norm=mcolors.Normalize(-0.2, 0.2)) print('--measuring participation ratio--') pr_traj: pr.PRTrajectory = pr.measure_pr_gen(network, train_pwl) print('--plotting participation ratio--') pr.plot_pr_trajectory(pr_traj, os.path.join(SAVEDIR, 'pr'), exist_ok=True) print('--finished--')
#Get labels for x - axis ticks labels = list(health.loc[:, "district_eng"].value_counts().sort_values( ascending=False).index) #Generate bar positions from numpy import arange bar_positions = arange(len(labels)) + 1 #Get bar heights from data bar_heights = h_inst_per_district_eng.loc[:, "health_count"].values.astype(int) # --- Color Information --- # For health data when both graphs and maps are used. sequential_cmap = cm.ScalarMappable(col.Normalize(0, max(bar_heights)), cm.YlGnBu) # --- Plot Figure --- ax_2.bar(bar_positions, bar_heights, width=0.7, align="center", color=sequential_cmap.to_rgba(bar_heights)) # --- Add color legend --- #Import required toolkit from mpl_toolkits.axes_grid1.inset_locator import inset_axes
def plot_figs(self, step, lat, lon, scalar, imlabels, imlabelsu, imrelab, comp_ids, medax, spines): """ make plots for tutorial/presentation """ # set up for plotting import matplotlib.pyplot as plt import matplotlib.patches as plt_mp import matplotlib.image as plt_img comp_alph = 0.75 plt.rcParams['figure.max_open_warning'] = 0 imext = [lon[0], lon[-1], lat[0], lat[-1]] # plot scalar in fig = plt.figure(figsize=(8.0, 4.0)) self.plot_tex(lat, lon) cmap = plt.get_cmap('magma') plt.imshow(scalar, aspect='equal', extent=imext, \ origin='lower', cmap=cmap, zorder=2) plt.xlabel('deg lon') plt.ylabel('deg lat') plt.title('Scalar variable (%s) step=%d'%(self.scalar_variable, step)) plt.savefig('%s_scalar_variable_%06d.png'%(self.out_file, step), dpi=self.dpi) if self.interact: plt.show() plt.close(fig) # plot scalar and segmentation fig = plt.figure(figsize=(8.0, 4.0)) self.plot_tex(lat, lon) segscalar = np.where(imlabelsu > 0, scalar, imlabelsu) cmap = plt.get_cmap('magma') cmap.set_under((0.,0.,0.,0.)) plt.contour(imlabelsu, [0.125], colors='k', \ extent=imext, origin='lower', zorder=3) cmap = plt.get_cmap('magma') plt.imshow(segscalar, aspect='equal', extent=imext, \ origin='lower', cmap=cmap, vmin=0.5, zorder=2) plt.xlabel('deg lon') plt.ylabel('deg lat') plt.title('Segmented scalar variable (%s) step=%d'%(self.scalar_variable, step)) plt.savefig('%s_scalar_variable_and_seg_%06d.png'%(self.out_file, step), dpi=self.dpi) if self.interact: plt.show() plt.close(fig) # plot unfiltered connected components fig = plt.figure(figsize=(8.0, 4.0)) self.plot_tex(lat, lon) cmap = plt.get_cmap('cool') cmap.set_under((0.,0.,0.,0.)) plt.imshow(imlabelsu, cmap=cmap, aspect='equal', \ extent=imext, origin='lower', vmin=0.5, alpha=comp_alph, \ zorder=2) plt.contour(imlabelsu, [0.125], colors='k', \ extent=imext, origin='lower', zorder=3) plt.xlabel('deg lon') plt.ylabel('deg lat') plt.title('Labeled segmentation (unfiltered) step=%d'%(step)) plt.savefig('%s_labeled_segmentation_unfilt_%06d.png'%( \ self.out_file, step), dpi=self.dpi) if self.interact: plt.show() plt.close(fig) # plot filtered connected components fig = plt.figure(figsize=(8.0, 4.0)) self.plot_tex(lat, lon) cmap = plt.get_cmap('cool') cmap.set_under((0.,0.,0.,0.)) plt.imshow(imlabels, cmap=cmap, aspect='equal', \ extent=imext, origin='lower', vmin=0.5, alpha=comp_alph, \ zorder=2) plt.contour(imlabels, [0.125], colors='k', \ extent=imext, origin='lower', zorder=3) plt.xlabel('deg lon') plt.ylabel('deg lat') plt.title('Labeled segmentation (filtered) step=%d'%(step)) plt.savefig('%s_labeled_segmentation_filt_%06d.png'%( \ self.out_file, step), dpi=self.dpi) if self.interact: plt.show() plt.close(fig) # plot filtered connected components with medial axis transform fig = plt.figure(figsize=(8.0, 4.0)) self.plot_tex(lat, lon) cmap = plt.get_cmap('gray') cmap.set_under((0.,0.,0.,0.)) plt.imshow(np.where(imlabels > 0, 1., 0.), cmap=cmap, aspect='equal', \ extent=imext, origin='lower', vmin=0.5, alpha=comp_alph, zorder=2) plt.contour(imlabels, [0.125], colors='k', \ extent=imext, origin='lower', zorder=3) cmap = pltcm.ScalarMappable(norm=pltcolors.Normalize(vmin=1, \ vmax=np.max(comp_ids)), cmap=plt.get_cmap('cool')) for comp_id in comp_ids: if comp_id == 0: continue mapts = np.where(np.logical_and((imrelab == comp_id), (medax > 0))) c = cmap.to_rgba(comp_id) plt.plot(lon[mapts[1]], lat[mapts[0]], '.', color=c, \ markersize=3, zorder=3) plt.xlabel('deg lon') plt.ylabel('deg lat') plt.title('Medial axis tranform. step=%d'%(step)) plt.savefig('%s_medial_axis_%06d.png'%(self.out_file, step), dpi=self.dpi) if self.interact: plt.show() plt.close(fig) # plot filtered connected components with medial axis transform and spine fig = plt.figure(figsize=(8.0, 4.0)) self.plot_tex(lat, lon) cmap = plt.get_cmap('gray') cmap.set_under((0.,0.,0.,0.)) plt.imshow(np.where(imlabels > 0, 1., 0.), cmap=cmap, aspect='equal', \ extent=imext, origin='lower', vmin=0.5, alpha=comp_alph, zorder=2) plt.contour(imlabels, [0.125], colors='k', \ extent=imext, origin='lower', zorder=3) cmap = pltcm.ScalarMappable(norm=pltcolors.Normalize(vmin=1, vmax=np.max(comp_ids)), \ cmap=plt.get_cmap('cool')) for comp_id in comp_ids: mapts = np.where(np.logical_and((imrelab == comp_id), (medax > 0))) c = cmap.to_rgba(comp_id) plt.plot(lon[mapts[1]], lat[mapts[0]], '.', markersize=2, \ color='k', alpha=0.035, zorder=3) comp_id = 1 for path in spines: c = cmap.to_rgba(comp_id) comp_id += 1 path_i = lon[path[0]] path_j = lat[path[1]] plt.plot(path_i, path_j, color=c, linewidth=2, zorder=4) plt.xlabel('deg lon') plt.ylabel('deg lat') plt.title('Medial axis tranform and spine. step=%d'%(step)) plt.savefig('%s_medial_axis_spine_%06d.png'%(self.out_file, step), dpi=self.dpi) if self.interact: plt.show() plt.close(fig) # plot the figure fig = plt.figure(figsize=(8.0, 4.0)) self.plot_tex(lat, lon) # color by scalar segscalar = np.where(imlabels > 0, scalar, imlabels) cmap = plt.get_cmap('magma') nc = cmap(np.linspace(0, 1, cmap.N)) a = 2.0*np.linspace(0, 1, cmap.N) nc[:,-1] = np.where(a <= 1.0, a, 1.0) cmap = pltcolors.ListedColormap(nc) plt.imshow(segscalar, aspect='equal', extent=imext, \ origin='lower', cmap=cmap, zorder=2) plt.contour(imlabels, [0.125], colors='k', \ extent=imext, origin='lower', zorder=3) for path in spines: path_i = lon[path[0]] path_j = lat[path[1]] plt.plot(path_i, path_j, \ 'g' if path_j[0] > 0. else 'b', linewidth=2, zorder=4) plt.xlabel('deg lon') plt.ylabel('deg lat') plt.title('NH/SH Jet Stream Spines step=%d'%(step)) plt.savefig('%s_spine_and_wind_%06d.png'%(self.out_file, step), dpi=self.dpi) if self.interact: plt.show() plt.close(fig) # plot just the spine fig = plt.figure(figsize=(8.0, 4.0)) self.plot_tex(lat, lon) for path in spines: path_i = lon[path[0]] path_j = lat[path[1]] plt.plot(path_i, path_j, \ 'g' if path_j[0] > 0. else 'b', linewidth=2, zorder=4) plt.xlabel('deg lon') plt.ylabel('deg lat') plt.title('NH/SH Jet Stream Spines step=%d'%(step)) plt.savefig('%s_spine_%06d.png'%(self.out_file, step), dpi=self.dpi) if self.interact: plt.show() plt.close(fig)
x = np.linspace(0, Lx, ncol) y = np.linspace(0, Ly, nrow) c = plt.contour(x, y, h[0], np.arange(500, 1000, 50)) plt.clabel(c, fmt='%2.1f') plt.axis('scaled') plt.axis((0, Lx, 0, Ly)) plt.savefig(os.path.join(output, modelname+'_SP2.png')) plt.show() # Output based on this example: http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#surface-plots fig = plt.figure() ax = fig.gca(projection='3d') X = np.linspace(0, Lx, ncol) Y = np.linspace(0, Ly, nrow) X, Y = np.meshgrid(X, Y) Z = h[0] # set layer 1 norm = mc.Normalize(vmin=0, vmax=np.max(Z), clip=False) # set min/max of the colors surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.Set1, linewidth=-0.005, antialiased=False, norm=norm) ax.set_zlim(0, 1000) # set limit of z-axis ax.xaxis.set_major_locator(LinearLocator(2)) ax.yaxis.set_major_locator(LinearLocator(2)) ax.zaxis.set_major_locator(LinearLocator(2)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.01f')) fig.colorbar(surf, shrink=0.7, aspect=10) plt.savefig(os.path.join(output, modelname+'_SP3.png')) ax.set_xlabel('meters') ax.set_zlabel('meters') plt.show() m.check()
import numpy as np import math from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import animation import matplotlib.cm as cm import matplotlib.colors as colors cmapjet = plt.get_cmap('jet') cNorm = colors.Normalize(vmin=0.0, vmax=1.0) scalarMap = cm.ScalarMappable(norm=cNorm, cmap=cmapjet) # This program integrates the polyhedral shape functions import ZTET import ZHEX Nref = 20 xr, yr, zr = ZTET.GetTetRefPoints(Nref) print("Number of reference points = %d" % len(xr)) # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Ref Tet RefTet = ZTET.Tet() # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Arb Tet 1 scaled tet_points = np.zeros((4, 3)) scale = 0.5 tet_points[0, :] = np.array([0.0, 0.0, 0.0]) tet_points[1, :] = np.array([1.0, 0.0, 0.])
def draw_bg_trial(analysis_info, draw_cbar=False): """ ---------------------------------------------------------------------- draw_bg_trial(analysis_info,draw_cbar = False) ---------------------------------------------------------------------- Goal of the function : Draw eye traces figure background ---------------------------------------------------------------------- Input(s) : analysis_info: analysis settings draw_cbar: draw color circle (True) or not (False) ---------------------------------------------------------------------- Output(s): incircle: (True) = yes, (False) = no ---------------------------------------------------------------------- Function created by Martin Rolfs adapted by Martin SZINTE ([email protected]) ---------------------------------------------------------------------- """ import numpy as np import cortex import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.ticker import FormatStrFormatter import matplotlib.colors as colors import ipdb deb = ipdb.set_trace # Saccade analysis per run and sequence # Define figure title_font = {'loc': 'left', 'fontsize': 14, 'fontweight': 'bold'} axis_label_font = {'fontsize': 14} bg_col = (0.9, 0.9, 0.9) axis_width = 0.75 line_width_corr = 1.5 # Horizontal eye trace screen_val = 12.5 ymin1, ymax1, y_tick_num1 = -screen_val, screen_val, 11 y_tick1 = np.linspace(ymin1, ymax1, y_tick_num1) xmin1, xmax1, x_tick_num1 = 0, 1, 5 x_tick1 = np.linspace(xmin1, xmax1, x_tick_num1) # Vertical eye trace ymin2, ymax2, y_tick_num2 = -screen_val, screen_val, 11 y_tick2 = np.linspace(ymin2, ymax2, y_tick_num2) xmin2, xmax2, x_tick_num2 = 0, 1, 5 x_tick2 = np.linspace(xmin2, xmax2, x_tick_num2) cmap = 'hsv' cmap_steps = 16 col_offset = 0 #1/14.0 base = cortex.utils.get_cmap(cmap) val = np.linspace(0, 1, cmap_steps + 1, endpoint=False) colmap = colors.LinearSegmentedColormap.from_list('my_colmap', base(val), N=cmap_steps) pursuit_polar_ang = np.deg2rad(np.arange(0, 360, 22.5)) pursuit_ang_norm = (pursuit_polar_ang + np.pi) / (np.pi * 2.0) pursuit_ang_norm = (np.fmod(pursuit_ang_norm + col_offset, 1)) * cmap_steps pursuit_col_mat = colmap(pursuit_ang_norm.astype(int)) pursuit_col_mat[:, 3] = 0.2 saccade_polar_ang = np.deg2rad(np.arange(0, 360, 22.5) + 180) saccade_ang_norm = (saccade_polar_ang + np.pi) / (np.pi * 2.0) saccade_ang_norm = (np.fmod(saccade_ang_norm + col_offset, 1)) * cmap_steps saccade_col_mat = colmap(saccade_ang_norm.astype(int)) saccade_col_mat[:, 3] = 0.8 polar_ang = np.deg2rad(np.arange(0, 360, 22.5)) fig = plt.figure(figsize=(15, 7)) gridspec.GridSpec(2, 8) # Horizontal eye trace ax1 = plt.subplot2grid((2, 8), (0, 0), rowspan=1, colspan=4) ax1.set_ylabel('Hor. coord. (dva)', axis_label_font, labelpad=0) ax1.set_ylim(bottom=ymin1, top=ymax1) ax1.set_yticks(y_tick1) ax1.set_xlabel('Time (%)', axis_label_font, labelpad=10) ax1.set_xlim(left=xmin1, right=xmax1) ax1.set_xticks(x_tick1) ax1.set_facecolor(bg_col) ax1.set_title('Horizontal eye position', **title_font) ax1.xaxis.set_major_formatter(FormatStrFormatter('%.2g')) for rad in analysis_info['rads']: ax1.plot(x_tick1, x_tick1 * 0 + rad, color=[1, 1, 1], linewidth=axis_width * 2) ax1.plot(x_tick1, x_tick1 * 0 - rad, color=[1, 1, 1], linewidth=axis_width * 2) # Vertical eye trace ax2 = plt.subplot2grid((2, 8), (1, 0), rowspan=1, colspan=4) ax2.set_ylabel('Ver. coord. (dva)', axis_label_font, labelpad=0) ax2.set_ylim(bottom=ymin2, top=ymax2) ax2.set_yticks(y_tick2) ax2.set_xlabel('Time (%)', axis_label_font, labelpad=10) ax2.set_xlim(left=xmin2, right=xmax2) ax2.set_xticks(x_tick2) ax2.set_facecolor(bg_col) ax2.set_title('Vertical eye position', **title_font) ax2.xaxis.set_major_formatter(FormatStrFormatter('%.2g')) for rad in analysis_info['rads']: ax2.plot(x_tick2, x_tick2 * 0 + rad, color=[1, 1, 1], linewidth=axis_width * 2) ax2.plot(x_tick2, x_tick2 * 0 - rad, color=[1, 1, 1], linewidth=axis_width * 2) # Screen eye trace ax3 = plt.subplot2grid((2, 8), (0, 4), rowspan=2, colspan=4) ax3.set_xlabel('Horizontal coordinates (dva)', axis_label_font, labelpad=10) ax3.set_ylabel('Vertical coordinates (dva)', axis_label_font, labelpad=0) ax3.set_xlim(left=ymin1, right=ymax1) ax3.set_xticks(y_tick1) ax3.set_ylim(bottom=ymin2, top=ymax2) ax3.set_yticks(y_tick2) ax3.set_facecolor(bg_col) ax3.set_title('Screen view', **title_font) ax3.set_aspect('equal') theta = np.linspace(0, 2 * np.pi, 100) for rad in analysis_info['rads']: ax3.plot(rad * np.cos(theta), rad * np.sin(theta), color=[1, 1, 1], linewidth=axis_width * 3) plt.subplots_adjust(wspace=1.4, hspace=0.4) # color legend if draw_cbar == True: cbar_axis = fig.add_axes([0.47, 0.77, 0.8, 0.1], projection='polar') norm = colors.Normalize(0, 2 * np.pi) t = np.linspace(0, 2 * np.pi, 200, endpoint=True) r = [0, 1] rg, tg = np.meshgrid(r, t) im = cbar_axis.pcolormesh(t, r, tg.T, norm=norm, cmap=colmap) cbar_axis.set_yticklabels([]) cbar_axis.set_xticklabels([]) cbar_axis.set_theta_zero_location("W", offset=-360 / cmap_steps / 2) cbar_axis.spines['polar'].set_visible(False) else: cbar_axis = [] return ax1, ax2, ax3, cbar_axis
def m_values_over_hillshade(hillshade_file, tree_file): """ Plots m values of channels taken from the *.tree file over a hillshade """ label_size = 20 #title_size = 30 axis_size = 28 import matplotlib.pyplot as pp import numpy as np import matplotlib.colors as colors import matplotlib.cm as cmx from matplotlib import rcParams import matplotlib.lines as mpllines #get data hillshade = LSDP.ReadRasterArrayBlocks(hillshade_file) #ignore nodata values hillshade = np.ma.masked_where(hillshade == -9999, hillshade) # now get the extent extent_raster = LSDP.GetRasterExtent(hillshade_file) x_min = extent_raster[0] x_max = extent_raster[1] y_min = extent_raster[2] y_max = extent_raster[3] #ignore nodata values hillshade = np.ma.masked_where(hillshade == -9999, hillshade) #fonts rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['arial'] rcParams['font.size'] = label_size #get coordinates of streams from tree file M_chi_value = [] channel_id = [] row = [] col = [] with open(tree_file, 'r') as f: lines = f.readlines() for q,line in enumerate(lines): if q > 0: #skip first line channel_id.append(float(line.split()[0])) M_chi_value.append(float(line.split()[11])) row.append(float(line.split()[4])) col.append(float(line.split()[5])) #get bounding box & pad to 10% of the dimension x_max = max(col) x_min = min(col) y_max = max(row) y_min = min(row) pad_x = (x_max - x_min) * 0.1 pad_y = (x_max - y_min) * 0.1 if (pad_y > pad_x): pad_x = pad_y else: pad_y = pad_x x_max += pad_x x_min -= pad_x y_max += pad_y y_min -= pad_y fig = pp.figure(1, facecolor='white',figsize=(10,7.5)) ax = fig.add_subplot(1,1,1) ax.imshow(hillshade, vmin=0, vmax=255, cmap=cmx.gray) # now get the tick marks n_target_tics = 5 xlocs,ylocs,new_x_labels,new_y_labels = LSDP.GetTicksForUTM(hillshade_file,x_max,x_min,y_max,y_min,n_target_tics) pp.xticks(xlocs, new_x_labels, rotation=60) #[1:-1] skips ticks where we have no data pp.yticks(ylocs, new_y_labels) for line in ax.get_xticklines(): line.set_marker(mpllines.TICKDOWN) #line.set_markeredgewidth(3) for line in ax.get_yticklines(): line.set_marker(mpllines.TICKLEFT) #line.set_markeredgewidth(3) pp.xlim(x_min,x_max) pp.ylim(y_max,y_min) pp.xlabel('Easting (m)',fontsize = axis_size) pp.ylabel('Northing (m)',fontsize = axis_size) # channel ID M_chi_value_MIN = np.min(M_chi_value) M_chi_value_MAX = np.max(M_chi_value) cNorm_M_chi_value = colors.Normalize(vmin=M_chi_value_MIN, vmax=M_chi_value_MAX) # the max number of channel segs is the 'top' colour hot = pp.get_cmap('RdYlBu_r') scalarMap_M_chi_value = cmx.ScalarMappable(norm=cNorm_M_chi_value, cmap=hot) for a,i in enumerate(M_chi_value): #print "a: " +str(a)+" i: " +str(i) if channel_id[a] != 0: # plot other stream segments colorVal = scalarMap_M_chi_value.to_rgba(i) # this gets the distinct colour for this segment pp.scatter(col[a], row[a], 30,marker=".", color=colorVal,edgecolors=colorVal) for a,i in enumerate(M_chi_value): if channel_id[a] == 0: # plot trunk stream in black colorVal = scalarMap_M_chi_value.to_rgba(i) pp.scatter(col[a], row[a], 40,marker=".", color=colorVal,edgecolors=colorVal) sm = pp.cm.ScalarMappable(cmap=hot, norm=pp.normalize(vmin=min(M_chi_value), vmax=max(M_chi_value))) sm._A = [] ax.spines['top'].set_linewidth(2.5) ax.spines['left'].set_linewidth(2.5) ax.spines['right'].set_linewidth(2.5) ax.spines['bottom'].set_linewidth(2.5) ax.tick_params(axis='both', width=2.5) from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(pp.gca()) cax = divider.append_axes("right", "5%", pad="3%") pp.colorbar(sm, cax=cax).set_label('$M_{\chi}$',fontsize=axis_size) cax.tick_params(labelsize=label_size) #pp.xlim(x_min,x_max) #pp.ylim(y_max,y_min) pp.tight_layout() pp.show()