def test_num_axes_hist(image_array_2bands, basic_image): """We expect one AxesSubplot object per band.""" f_1, ax_1 = ep.hist(basic_image) assert len(f_1.axes) == 1 f_2, ax_2 = ep.hist(image_array_2bands) assert len(f_2.axes) == 2 plt.close(f_1) plt.close(f_2)
def test_single_hist_2titles(image_array_single_band): """Test that a single custom title works for one band hists.""" custom_title = ["Great hist", "another title"] with pytest.raises(ValueError, match="You have one array to plot but more than one"): ep.hist(image_array_single_band, title=custom_title) plt.close()
def test_number_of_hist_bins(basic_image): """Test that the number of bins is customizable.""" n_bins = [1, 10, 100] for n in n_bins: f, ax = ep.hist(basic_image, bins=n) assert n == len(ax.patches) plt.close()
def test_hist_number_of_columns(image_array_2bands): """Test that the col argument changes the number of columns.""" number_of_columns = [1, 2] for n in number_of_columns: f, ax = ep.hist(image_array_2bands, cols=n) assert [a.numCols for a in ax] == [n] * 2 plt.close(f)
def viewhist(self): # Function to display the histogram in the frame and save it in the specified directory if self.display.winfo_exists(): self.display.grid_forget() self.display.destroy() self.display = ttk.Frame(self) self.display.grid(row = 0, column = 4,rowspan=2, sticky = 'nwes') frame=self.display band_path=[] for file in self.histfiles: band_path.append(file) # dir = self.dir[0] # band_path = glob.glob(os.path.join(dir,"*.tif")) # band_path = glob.glob(os.path.join(dir,"*.TIF")) band_path.sort() band_stack, meta_data = es.stack(band_path, nodata=-9999) size = len(band_path) color_list = ["Indigo","Blue","Green","Yellow","Red","Maroon","Purple","Violet"] titles = [] for i in range(size): titles.append("File"+str(i+1)) self.figure,self.plot = ep.hist(band_stack, title = titles,figsize = (6,4)) self.canvas = FigureCanvasTkAgg(self.figure,frame) self.toolbar = NavigationToolbar2Tk(self.canvas,frame) self.toolbar.update() self.canvas.get_tk_widget().pack()
def test_hist_partially_masked_array(image_array_3bands): ones = np.ones(image_array_3bands[0].shape) image_array_3bands[2] = ones masked_arr = np.ma.masked_where(image_array_3bands == 1, image_array_3bands) f, ax = ep.hist(masked_arr, cols=3) assert len(f.axes) == 3
def test_hist_fully_masked_array(image_array_single_band): masked_arr = np.ma.masked_where( image_array_single_band >= 0, image_array_single_band ) with pytest.raises(ValueError, match="is not finite"): f, ax = ep.hist(masked_arr) plt.close(f)
def test_multiband_hist_title(image_array_2bands): """Test that custom titles work for multiband hists.""" custom_titles = ["Title 1", "Title 2"] f, ax = ep.hist(image_array_2bands, title=custom_titles) num_plts = image_array_2bands.shape[0] assert [f.axes[i].get_title() for i in range(num_plts)] == custom_titles plt.close(f)
def test_hist_1band_masked_array(image_array_single_band): """Ensure that a masked single band arr plots & the number of bins is correct""" masked_arr = np.ma.masked_where(image_array_single_band == 4, image_array_single_band) nbins = 3 f, ax = ep.hist(masked_arr, title=["TITLE HERE"], bins=nbins) assert len(f.axes) == 1 assert len(ax.patches) == nbins plt.close(f)
def test_hist_plot_odd_axes(image_array_3bands): """A histogram with 2 cols and 3 plots should have 4 axes total. this will ensure code coverage for clearing out those axes""" ncols = 2 f, ax = ep.hist(image_array_3bands, cols=ncols) assert len(f.axes) == ncols * 2 plt.close(f)
def test_hist_color_string(image_array_2bands): f, ax = ep.hist(image_array_2bands, colors="blue") colors = [a.patches[0].__dict__.get("_original_facecolor") for a in ax] expected_colors = [ np.array([0.0, 0.0, 1.0, 1.0]), np.array([0.0, 0.0, 1.0, 1.0]), ] for i in range(2): assert np.array_equal(colors[i], expected_colors[i]) plt.close(f)
def test_hist_masked_array(image_array_2bands): """ Test that a masked 2 band array plots properly""" masked_arr = np.ma.masked_where(image_array_2bands == 6, image_array_2bands) nbins = 6 f, ax = ep.hist(masked_arr, bins=nbins) for a in ax: assert len(a.patches) == 6 assert len(f.axes) == 2 plt.close(f)
def test_hist_color_multi_band(image_array_2bands): """Test that multiple colors work for multiband images.""" f, ax = ep.hist(image_array_2bands, colors=["red", "blue"]) colors = [a.patches[0].__dict__.get("_original_facecolor") for a in ax] expected_colors = [ np.array([1.0, 0.0, 0.0, 1.0]), np.array([0.0, 0.0, 1.0, 1.0]), ] for i in range(2): assert np.array_equal(colors[i], expected_colors[i])
def test_hist_bbox(basic_image): """Test that the bbox dimensions are customizable.""" f, ax = ep.hist(basic_image, figsize=(50, 3)) bbox = str(f.__dict__.get("bbox_inches")) assert bbox == "Bbox(x0=0.0, y0=0.0, x1=50.0, y1=3.0)"
def test_hist_color_single_band(basic_image): """Check that the color argument works for single bands.""" f, ax = ep.hist(basic_image, colors=["red"]) facecolor = ax.patches[0].__dict__.get("_original_facecolor") assert np.array_equal(facecolor, np.array([1.0, 0.0, 0.0, 1.0]))
def test_num_plot_titles_mismatch_hist(image_array_2bands): """Raise an error if the number of titles != number of bands.""" with pytest.raises(ValueError, match="number of plot titles"): ep.hist(image_array_2bands, title=["One", "too", "many"])
def test_single_hist_title(basic_image): """Test that custom titles work for one band hists.""" custom_title = "Great hist" f, ax = ep.hist(basic_image, title=[custom_title]) assert ax.get_title() == custom_title
def test_hist_1band_range(image_array_single_band): """Ensure that the range limits are reflected in the plot""" f, ax = ep.hist(image_array_single_band, hist_range=(2, 5)) range_check = ax.get_xlim() assert range_check[0] > 1.5 and range_check[1] < 5.5
stretch=True, extent=extent, str_clip=0.5, title="RGB Image of Un-cropped Raster", ) plt.show() ################################################################################ # Explore the Range of Values in the Data # --------------------------------------- # You can explore the range of values found in the data using the EarthPy ``hist()`` # function. Do you notice any extreme values that may be impacting the stretch # of the image? ep.hist(array, title=["Band 1", "Band 2", "Band 3"]) plt.show() ########################################################################### # No Data Option # --------------- # ``es.stack()`` can handle ``nodata`` values in a raster. To use this # parameter, specify ``nodata=``. This will mask every pixel that contains # the specified ``nodata`` value. The output will be a numpy masked array. os.chdir(os.path.join(et.io.HOME, "earth-analytics")) array_nodata, raster_prof_nodata = es.stack(stack_band_paths, nodata=-9999) # View hist of data with nodata values removed ep.hist( array_nodata,
arr_st, meta = es.stack(landsat_paths_pre) # Import the landsat qa layer with rio.open( "data/cold-springs-fire/landsat_collect/LC080340322016070701T1-SC20180214145604/crop/LC08_L1TP_034032_20160707_20170221_01_T1_pixel_qa_crop.tif" ) as landsat_pre_cl: landsat_qa = landsat_pre_cl.read(1) landsat_ext = plotting_extent(landsat_pre_cl) ############################################################################### # Plot Histogram of Each Band in Your Data # ---------------------------------------- # You can view a histogram for each band in your dataset by using the # ``hist()`` function from the ``earthpy.plot`` module. ep.hist(arr_st) plt.show() ############################################################################### # Customize Histogram Plot with Titles and Colors # ----------------------------------------------- ep.hist( arr_st, colors=["blue"], title=[ "Band 1", "Band 2", "Band 3", "Band 4", "Band 5",
sns.set(font_scale=1.5, style="whitegrid") # Open data and assign negative values to nan with rio.open(str(p)) as src: dem = src.read(1, masked=True) std = np.std(dem) print(std) # fig, ax = plt.subplots(figsize = (10, 5)) # im = ax.imshow(dem.squeeze()) # ep.colorbar(im) # ax.set(title="Diff") # ax.set_axis_off() # plt.show() # View object dimensions fig, ax = ep.hist(dem, colors=['grey'], title="3σ histogram %s" % p.name, xlabel='Band value (meters)', bins=20, hist_range=(-3 * std, 3 * std)) plt.text(0.5, 0.5, r'$n=%d,\ \sigma=%.3f$' % (len(dem), std), transform=ax.transAxes, bbox=dict(facecolor='red', )) plt.grid(True) plt.savefig('histogram-%s.png' % p.name, )
def test_hist_plot_1_dim(image_array_2bands): """A single dimensional array should plot properly.""" array_1_dim = image_array_2bands.ravel() f, ax = ep.hist(array_1_dim) assert len(f.axes) == 1 plt.close(f)
# Creating a raster histogram to investigate the differences in elevation # In[15]: lidar_dem_im #values in array # In[16]: # Plotting the histogram ep.hist(lidar_dem_im[~lidar_dem_im.mask].ravel(), bins=100, title="Lee Hill Road - Digital elevation (terrain) model - \nDistribution of elevation values") plt.show() # We can see here that there are some differences in elevation. Most raster cells have values around 1,700 meters, but there are also many values that are between 1,800 - 1,950 meters tall. # Now, I'm adjusting the plotting extent, so that we can "zoom up" on the data. # # (This just means that we readjust the bounding box of the raster, and plot a smaller area. This way, we can see more detail on some of the cells.) # In[17]: # Define a spatial extent that is "smaller" - so that this is what we're zooming up on in the final product.
def test_hist_axes(image_array_2bands): f, ax = ep.hist(image_array_2bands, xlabel="xlabel", ylabel="ylabel") for i in range(2): assert ax[i].get_xlabel() == "xlabel" assert ax[i].get_ylabel() == "ylabel"
def test_hist_single_band_3_dims(image_array_single_band_3dims): f, ax = ep.hist(image_array_single_band_3dims) assert len(f.axes) == 1 plt.close(f)
def test_title_string(basic_image): """Test that custom titles work for one band hists.""" custom_title = "Great hist" f, ax = ep.hist(basic_image, title=custom_title) assert ax.get_title() == custom_title plt.close(f)
ax.set_title("Digital Elevation Model \n Shuttle Radar Topography Mission (SRTM), NASA \n , Western Uganda", fontsize=24) plt.show() lidar_dem_im #values in array # In the original GeoTIFF, I was having trouble visualizing (in a 2D method) the elevation for the raster histogram. # # All I 'knew' about this data was the following: # * The Rwenzori mountains are the tallest mountain range in Africa # * The main town in the region, Fort Portal, Uganda, is *roughly* the same height as Denver, CO, USA. # # As a result, I thought this would be a particularly useful exercise to see just HOW MUCH elevation differences there would be! ep.hist(lidar_dem_im[~lidar_dem_im.mask].ravel(), bins=100, title="Digital Elevation Model \n Shuttle Radar Topography Mission (SRTM), NASA \n , Western Uganda \nDistribution of elevation values") plt.show() # The above isn't very useful - we see the "5000 [m]" entry, but it's an outlier. I'm curious to see if there's a distribution of heights listed. ep.hist(lidar_dem_im[~lidar_dem_im.mask].ravel(), bins=500, title="Digital Elevation Model \n Shuttle Radar Topography Mission (SRTM), NASA \n , Western Uganda \nDistribution of elevation values (500 bins)") plt.show() #downgrading the number of bins shown ep.hist(lidar_dem_im[~lidar_dem_im.mask].ravel(), bins=50,
def test_hist_plot_1_band_array(basic_image): """A 2 dim image should plot properly returning a single axis object""" f, ax = ep.hist(basic_image) assert len(f.axes) == 1 plt.close(f)
"midnightblue", "Blue", "Green", "Red", "Maroon", "Purple", "Violet", ] # Create the list of titles for each band. The titles and colors listed # in this example reflect the order and wavelengths of the Landsat 8 bands titles = ["Ultra Blue", "Blue", "Green", "Red", "NIR", "SWIR 1", "SWIR 2"] # Plot the histograms with the color and title lists you just created # sphinx_gallery_thumbnail_number = 5 ep.hist(array_stack, colors=colors_list, title=titles) plt.show() ############################################################################### # Customize Bin Size and Arrangement of Histograms # ------------------------------------------------- # # You can customize the number of bins each histogram plot uses to group the # data it is plotting. The default number is 20. This can be adjusted to match # the data you are trying to display. Additionally, you can change the # arrangement of the image overall by modifying the number of columns used # to plot the data. # Plot each histogram with 50 bins, arranged across three columns ep.hist(array_stack, bins=50, cols=3) plt.show()
def test_hist_multiband_array(image_array_3bands): f, ax = ep.hist(image_array_3bands, hist_range=(2, 5), cols=3) for a in ax: range_check = a.get_xlim() assert range_check[0] > 1.5 and range_check[1] < 5.5