def MultiDrapeMaps(DataDir, ElevationRaster, DrapeRasterWild, cmap, drape_min_threshold=None, drape_max=None): """ Plots flood extents from water depth rasters draped over the catchment elevation raster in a series of subplots Takes a wildcard for the drapes Expexts a fixed elevation raster, but this could be modified in future. Thought: consider, if plotting multiple datasets, how you are going to deal with min a max values in the colur range. imshow will automatically set vmin and vmax and stretch the colour bar over this - which can be visually misleading. Ideally, you want to have the same colour map used for *all* subplots, and this is not default behaviour. """ f, ax_arr = plt.subplots(2, 2, figsize=(10, 5), sharex=True, sharey=True) ax_arr = ax_arr.ravel() FPFiles = sorted(glob.glob(DataDirectory+DrapeRasterWild), key=str) n_files = len(FPFiles) print("Number of files = ", n_files) elev_raster_file = DataDir + ElevationRaster hillshade = LSDP.Hillshade(elev_raster_file) #hillshade_array = LSDP.ReadRasterArrayBlocks(elev_raster_file) # now get the extent extent_raster = LSDP.GetRasterExtent(elev_raster_file) x_min = extent_raster[0] x_max = extent_raster[1] y_min = extent_raster[2] y_max = extent_raster[3] # now get the tick marks n_target_tics = 5 xlocs,ylocs,new_x_labels,new_y_labels = LSDP.GetTicksForUTM(elev_raster_file,x_max,x_min,y_max,y_min,n_target_tics) print("xmax: " + str(x_max)) print("xmin: " + str(x_min)) print("ymax: " + str(y_max)) print("ymin: " + str(y_min)) """ Find the maximum water depth in all rasters. You need this to normalize the colourscale accross all plots when teh imshow is done later. """ try: print("Calculating max drape raster value by scanning rasters...") max_water_depth = findmaxval_multirasters(FPFiles) drape_max = max_water_depth except: print("Something went wrong trying to obtain the max value in \ your drape raster file list.") finally: print("The drape(s) max value is set to: ", drape_max) for i in range(n_files): print("The floodplain file name is: ", FPFiles[i]) FP_raster = LSDP.ReadRasterArrayBlocks(FPFiles[i]) #FP_raster = np.ma.masked_where(FP_raster <= 0, FP_raster) filename = os.path.basename(FPFiles[i]) title = mplext.labels.make_line_label(filename) print(title) low_values_index = FP_raster < drape_min_threshold FP_raster[low_values_index] = np.nan im = ax_arr[i].imshow(hillshade, "gray", extent=extent_raster, interpolation="nearest") """ Now we can set vmax to be the maximum water depth we calcualted earlier, making our separate subplots all have the same colourscale """ im = ax_arr[i].imshow(FP_raster, cmap, extent=extent_raster, alpha=1.0, interpolation="none", vmin=drape_min_threshold, vmax=drape_max) ax_arr[i].set_title(title) f.subplots_adjust(right=0.8) cax = f.add_axes([0.9, 0.1, 0.03, 0.8]) cbar = f.colorbar(im, cax=cax) cbar.set_label("Water depth (m)") #cbar.set_ticks(np.linspace(0, 8, 8)) #cbar = mplext.colours.colorbar_index(f, cax, 8, cmap, # drape_min_threshold, drape_max) cbar.set_label("Water depth (m)") #tick_locator = ticker.MaxNLocator(nbins=8) #cbar.locator = tick_locator #cbar.update_ticks() f.text(0.5, 0.04, 'Easting (m)', ha='center') f.text(0.04, 0.5, 'Northing (m)', va='center', rotation='vertical')
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()
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 TestAxisLocation(): tick_label_size = 10 text_size = 12 # Set up fonts for plots rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['arial'] rcParams['font.size'] = text_size rcParams['xtick.labelsize'] = tick_label_size rcParams['ytick.labelsize'] = tick_label_size DataDirectory = "C:\\Vagrantboxes\\LSDTopoTools\\Topographic_projects\\Meghalaya\\Divides\\" #DataDirectory = "T:\\analysis_for_papers\\Meghalaya\\divide_migration\\" Base_file = "Mega_divide" bil = ".bil" #Filename = "Mega_clip.bil" #HSFilename = "Mega_clip_hs.bil" #BasinFilename = "Mega_clip_AllBasins.bil" DEMname = DataDirectory + Base_file + bil FigFileName = DataDirectory + Base_file + "Picture.png" FigFormat = "png" # get the data #raster = LSDP.ReadRasterArrayBlocks(DEMname) # now get the extent extent_raster = LSDP.GetRasterExtent(DEMname) x_min = extent_raster[0] x_max = extent_raster[1] y_min = extent_raster[2] y_max = extent_raster[3] print(extent_raster) fig = plt.figure(1, facecolor='white', figsize=(10, 10)) # Add an axis. This will be used to check how high the text is. ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.7], zorder=-1) # turn off the ticks ax2.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off') # labels along the bottom edge are off ax2.tick_params( axis='y', # changes apply to the x-axis which='both', # both major and minor ticks are affected left='off', # ticks along the bottom edge are off right='off', # ticks along the top edge are off labelleft='off') # labels along the bottom edge are off ax1 = fig.add_axes([0.0, 0.09, 0.85, 0.85]) #ax1.set(alpha=0.25) ax1.text( 0.1, 0.1, "x: Tick 10pt, Font 12pt need 0.9 inches.\n", transform=ax1.transAxes, ) #im = ax1.imshow(raster[::-1], "jet", extent = extent_raster, interpolation="nearest") n_target_tics = 5 xlocs, ylocs, new_x_labels, new_y_labels = LSDP.GetTicksForUTM( DEMname, x_max, x_min, y_max, y_min, n_target_tics) ax1.set_xticks(xlocs) ax1.set_yticks(ylocs) ax1.set_xticklabels(new_x_labels, rotation=60) ax1.set_yticklabels(new_y_labels) # This gets all the ticks, and pads them away from the axis so that the corners don't overlap ax1.tick_params(axis='both', width=1, pad=2) for tick in ax1.xaxis.get_major_ticks(): tick.set_pad(2) # This affects all axes because we set share_all = True. ax1.set_xlim(x_min, x_max) ax1.set_ylim(y_max, y_min) ax1.set_xlabel("YumYumDonuts") ax1.set_ylabel("Bigmama") #ax3 = fig.add_axes([0.0,0.5,0.5,0.5]) #ax1.text(0,0,"Hello",fontsize = 94) plt.savefig(FigFileName, format=FigFormat, dpi=100) yo = 284 / 3 print(yo) # So in every inch there are 94 points of text # The bottom plt.show()