def draw_slice(theta0,theta,r,h,colors='b'): #cntr={x:0,y:0} ls = LightSource(azdeg=0, altdeg=65) # Shade data, creating an rgb array. Xc,Yc,Zc = create_arc(0,0,r,theta0,theta,h) rgb = ls.shade(Zc, plt.cm.RdYlBu) ax.plot_surface(Xc, Yc, Zc, rstride=1, cstride=1, antialiased=False, color=colors,linewidth=1, edgecolor='b',facecolors=rgb) Xc,Yc,Zc = create_wall(0,0,r,theta0,h) rgb = ls.shade(Zc, plt.cm.RdYlBu) ax.plot_surface(Xc, Yc, Zc, rstride=1, cstride=1, antialiased=False, color=colors,linewidth=1, edgecolor='b',facecolors=rgb) Xc,Yc,Zc = create_wall(0,0,r,theta0+theta,h) rgb = ls.shade(Zc, plt.cm.RdYlBu) ax.plot_surface(Xc, Yc, Zc, rstride=1, cstride=1, antialiased=False, color=colors,linewidth=1, edgecolor='b',facecolors=rgb) Xc,Yc,Zc = create_lid(0,0,r,theta0,theta,h) #rgb = ls.shade(Xc, plt.cm.RdYlBu) ax.plot_surface(Xc, Yc, Zc, rstride=1, cstride=1, antialiased=False, color=colors,linewidth=1, edgecolor='b',facecolors=rgb)
def draw_figure(self): ls = LightSource(azdeg=315, altdeg=45) self.surf = self.data # try to plot the whole array try: blended_surface = ls.shade(self.surf, cmap=self.colormap, vert_exag=5, blend_mode=b"overlay", vmin=np.nanmin(self.surf), vmax=np.nanmax(self.surf)) # too big, two attempts for sub-sampling except MemoryError: rows = self.data.shape[0] cols = self.data.shape[1] # 1st attempt: <= 1024x1024 try: max_elements = 1024 row_stride = rows // max_elements + 1 col_stride = cols // max_elements + 1 self.surf = self.data[::row_stride, ::col_stride] blended_surface = ls.shade(self.surf, cmap=self.colormap, vert_exag=5, blend_mode=b"overlay", vmin=np.nanmin(self.surf), vmax=np.nanmax(self.surf)) except MemoryError: # 2st attempt: <= 512x512 max_elements = 512 row_stride = rows // max_elements + 1 col_stride = cols // max_elements + 1 self.surf = self.data[::row_stride, ::col_stride] blended_surface = ls.shade(self.surf, cmap=self.colormap, vert_exag=5, blend_mode=b"overlay", vmin=np.nanmin(self.surf), vmax=np.nanmax(self.surf)) log.debug("too big: %s x %s > subsampled to %s x %s" % (self.data.shape[0], self.data.shape[1], self.surf.shape[0], self.surf.shape[1])) self.axes.coastlines(resolution='50m', color='gray', linewidth=1) img = self.axes.imshow(blended_surface, origin='lower', cmap=self.colormap, extent=self.geo_extent, transform=ccrs.PlateCarree()) img.set_clim(vmin=np.nanmin(self.surf), vmax=np.nanmax(self.surf)) # add gridlines with labels only on the left and on the bottom grl = self.axes.gridlines(crs=ccrs.PlateCarree(), color='gray', draw_labels=True) grl.xformatter = LONGITUDE_FORMATTER grl.yformatter = LATITUDE_FORMATTER grl.xlabel_style = {'size': 8} grl.ylabel_style = {'size': 8} grl.ylabels_right = False grl.xlabels_top = False if self.cb: self.cb.on_mappable_changed(img) else: self.cb = plt.colorbar(img, ax=self.axes) self.cb.ax.tick_params(labelsize=8)
def add_dem(self, dem_file, cpt_topography=None, cpt_bathymetry=None, sun_azimuth=230, sun_altitude=15, topo_exag=100, bathy_exag=100): # Read dem lon, lat, elevation = dem.read(dem_file) georef = [lon[0], lon[-1], lat[0], lat[-1]] cmap_topo = dem.cpt(cpt_topography) cmap_bathy = dem.cpt(cpt_bathymetry) # Sun properties sun = LightSource(azdeg=sun_azimuth, altdeg=sun_altitude) sun_kw = dict(blend_mode='soft') # Add topography topo = elevation.copy() topo[topo < 0] = 0 img = (topo - np.nanmin(topo)) / (np.nanmax(topo) - np.nanmin(topo)) img = sun.shade(img, cmap=cmap_topo, vert_exag=topo_exag, fraction=1.1, **sun_kw) self.plot_img(img, extent=georef) # Colorbar img = self.plot_img(topo, cmap=cmap_topo) img.remove() cax = self.figure.add_axes([1.1, 0.4, 0.03, 0.4]) plt.colorbar(img, cax=cax, extend='max') # Bathymetry bathy = elevation.copy() bathy[bathy >= 0] = 0 img = (bathy - np.nanmin(bathy)) /\ (np.nanmax(bathy) - np.nanmin(bathy)) img = sun.shade(img, cmap=cmap_bathy, vert_exag=bathy_exag, fraction=1, **sun_kw) img[bathy == 0, -1] = 0 self.plot_img(img, extent=georef) # Colorbar img = self.plot_img(bathy, cmap=cmap_bathy) img.remove() cax = self.figure.add_axes([1.1, 0.2, 0.03, 0.2]) plt.colorbar(img, cax=cax, extend='min') # Colorbars label cb_label = 'Elevation (m)' self.figure.text(1.25, .5, cb_label, va='center', rotation=90, weight='normal')
def plot_shaded(self, cmap=plt.cm.terrain, lightsource_kwargs=None, *args, **kwargs): if lightsource_kwargs is None: lightsource_kwargs = {'azdeg':225, 'altdeg':5} extent = [self.x.min(), self.x.max(), self.y.min(), self.y.max()] arr = self.z.copy() nan_mask = np.isnan(arr) arr_min = arr[~nan_mask].min() if nan_mask.any(): arr[nan_mask] = max(arr_min-10, 0) ls = LightSource(**lightsource_kwargs) shaded = ls.shade(arr, cmap=cmap) fig = plt.figure() ax = fig.add_subplot(111) im = ax.imshow(shaded, cmap=cmap, extent=extent, *args, **kwargs) plt.colorbar(im) ax.get_xaxis().get_major_formatter().set_useOffset(False) ax.get_yaxis().get_major_formatter().set_useOffset(False) plt.show()
def SurfPlot(data): from mpl_toolkits.mplot3d import Axes3D from matplotlib import cbook from matplotlib import cm from matplotlib.colors import LightSource import matplotlib.pyplot as plt import numpy as np ncols, nrows = data.shape if ncols * nrows > 20000: print('Warning, surface plotting things of this size is slow...') z = data x = np.linspace(0, ncols, ncols) y = np.linspace(0, nrows, nrows) x, y = np.meshgrid(x, y) region = np.s_[0:min(ncols, nrows), 0:min(ncols, nrows)] x, y, z = x[region], y[region], z[region] fig, ax = plt.subplots(subplot_kw=dict(projection='3d'), figsize=(10, 10)) ls = LightSource(270, 45) # To use a custom hillshading mode, override the built-in shading and pass # in the rgb colors of the shaded surface calculated from "shade". rgb = ls.shade(z, cmap=cm.CMRmap, vert_exag=0.01, blend_mode='soft') surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=True, shade=False) plt.show()
def method_lighting(self): ls = LightSource(270, 45) rgb = ls.shade(self.z, cmap=cm.get_cmap(self.cmap), vert_exag=0.1, blend_mode='soft') return rgb
def plot_data(xi,yi,z,label,clabel,shaded=False): # #Plotting data from xyz file fig = plt.figure(figsize=(14, 6)) ax1 = fig.add_subplot('111') if shaded: ls = LightSource(azdeg=315, altdeg=45) ve = 0.1 #rgb = ls.shade(z,cmap=plt.cm.rainbow, blend_mode = 'overlay', vert_exag=1000, fraction = 0.3, dx = 200, dy = 200) plt.imshow(ls.hillshade(z,vert_exag=ve),cmap='gray') rgb = ls.shade(z,cmap=plt.cm.rainbow, blend_mode = 'hsv',vert_exag=ve) #pcm = plt.imshow(z,cmap=plt.cm.rainbow) plt.imshow(rgb,extent=[xi.min(),xi.max(),yi.min(),yi.max()]) #if you want to normalize in log > e.g. norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,vmin=z.min(), vmax=z.max()) else: #pcm = plt.contourf(xi, yi, z,50,vmin=z.min(), vmax=z.max(),cmap=plt.cm.rainbow) pcm = plt.imshow(z,extent=[xi.min(),xi.max(),yi.min(),yi.max()],cmap=plt.cm.rainbow,vmin = -300, vmax = 300) cbar = plt.colorbar(pcm,orientation='horizontal',fraction=0.046, pad=0.1) cbar.set_label(clabel,fontsize = 12) ax1.set_xlabel('x (m)',fontsize = 12) ax1.set_ylabel('y (m)',fontsize = 12) ax1.set_title(label,fontsize = 16,style='italic') plt.axis('scaled') plt.xlim(xi.min(),xi.max()) plt.ylim(yi.min(),yi.max()) plt.tight_layout()
def main(): fig, ax = plt.subplots(3, 2, figsize=(7, 10)) fig.tight_layout() if 1: # Same terrain and data. data = make_test_data('circles', noise_factor=0.05) * 2 - 7 terrain = data else: # Different terrain and data. Matplotlib hill shading can only show the data. data = make_test_data('hills') * -1 terrain = make_test_data('circles', noise_factor=0.05) * 2 assert terrain.shape == data.shape, "{} != {}".format(terrain.shape, data.shape) print("data range: {} {}".format(np.min(data), np.max(data))) if len(sys.argv) > 1: cmap_name = sys.argv[1] else: #cmap_name = 'copper' # from http://matplotlib.org/examples/pylab_examples/shading_example.html?highlight=codex%20shade #cmap_name = 'gist_earth' # works reasonably fine with all of them cmap_name = 'bwr' # shows that mpl & pegtop don't work when there is no increasing intensity #cmap_name = 'cubehelix' # shows that HSV blending does not work were color is black #cmap_name = 'rainbow' # shows that mpl & pegtop don't work when there is no increasing intensity #cmap_name = 'Paired_r' # is nice to inspect when the data is different from the terrain print ("Using colormap: {!r}".format(cmap_name)) cmap = plt.cm.get_cmap(cmap_name) cmap.set_bad('cyan') cmap.set_over('cyan') cmap.set_under('cyan') abs_max = np.max(np.abs(data)) # force color bar to be symmetrical. norm = mpl.colors.Normalize(vmin=-abs_max, vmax=abs_max) #norm = mpl.colors.Normalize(vmin=-2, vmax=3) draw(ax[0, 0], cmap=cmap, norm=norm, title='No shading', image_data = data) draw(ax[0, 1], cmap=plt.cm.gray, title='Matplotlib intensity', image_data = mpl_surface_intensity(terrain)) ls = LightSource(azdeg=DEF_AZIMUTH, altdeg=DEF_ELEVATION) draw(ax[1, 0], cmap=cmap, norm=norm, title='Matplotlib hill shading', image_data = ls.shade(data, cmap=cmap, norm=norm)) draw(ax[1, 1], cmap=cmap, norm=norm, title='Pegtop blending', image_data = mpl_hill_shade(data, terrain=terrain, cmap=cmap, norm=norm, blend_function=pegtop_blending)) draw(ax[2, 0], cmap=cmap, norm=norm, title='RGB blending', image_data = mpl_hill_shade(data, terrain=terrain, cmap=cmap, norm=norm, blend_function=rgb_blending)) draw(ax[2, 1], cmap=cmap, norm=norm, title='HSV blending', image_data = mpl_hill_shade(data, terrain=terrain, cmap=cmap, norm=norm, blend_function=hsv_blending)) plt.show()
def createLatLonTimeAverageMap3d(res, meta, startTime=None, endTime=None): latSeries = [m[0]['lat'] for m in res][::-1] lonSeries = [m['lon'] for m in res[0]] data = np.zeros((len(latSeries), len(lonSeries))) for t in range(0, len(latSeries)): latSet = res[t] for l in range(0, len(lonSeries)): data[len(latSeries) - t - 1][l] = latSet[l]['avg'] data[data == 0.0] = np.nan x, y = np.meshgrid(latSeries, lonSeries) z = data region = np.s_[0:178, 0:178] x, y, z = x[region], y[region], z[region] fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) ls = LightSource(270, 45) masked_array = np.ma.array(z, mask=np.isnan(z)) rgb = ls.shade(masked_array, cmap=cm.gist_earth) # , vert_exag=0.1, blend_mode='soft') surf = ax.plot_surface(x, y, masked_array, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False, shade=False) sio = StringIO() plt.savefig(sio, format='png') return sio.getvalue()
def exec(self): file = self.ui.LoadFilePath.text() if not (os.path.exists(file) and (os.path.isfile(file))): QtWidgets.QMessageBox.information(None, "エラー", "指定したファイル「" + file + "」が見つかりませんでした。", QMessageBox.Ok) return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: Z = pd.read_table(file, sep=' ', header=None, skiprows=6, engine = 'python') #「Initializing from file failed」エラー回避のためengineにpython指定 Z[Z == -9999] = np.nan X, Y = np.meshgrid(np.linspace(0,1,self.ui.RowNum.value()), np.linspace(0,1,self.ui.ColNum.value())) #2D表示 plt.imshow(Z) plt.show() #3D表示 ax = plt.axes(projection='3d') ax.plot_surface(X, Y, Z) plt.show() #3D表示 色付き ax = plt.axes(projection='3d') Z = Z.get_values() ls = LightSource() rgb = ls.shade(Z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft') surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False, shade=False) plt.show() finally: QApplication.restoreOverrideCursor() QtWidgets.QMessageBox.information(None, "終了", "終了しました。", QMessageBox.Ok)
def plot_matrix2(g): plt.figure(figsize=(9, 3)) azimuth = 137 altitude = 40 mat = g.mat plt.axis('off') ax = plt.subplot(131, projection='3d') light = LightSource(90, 45) green = np.array([0, 1.0, 0]) X, Y = np.meshgrid([m for m in range(len(mat[0]))], [n for n in range(len(mat))]) z = np.array(mat) ax.view_init(altitude, azimuth) illuminated_surface = light.shade(z, cmap=cm.coolwarm) rgb = np.ones((z.shape[0], z.shape[1], 3)) green_surface = light.shade_rgb(rgb * green, z) ax.plot_surface(X, Y, g.mat, rstride=1, cstride=1, linewidth=0, antialiased=True, facecolors=illuminated_surface) ax.set_zticks([]) ax.grid(False) sbplt = plt.subplot(132) plt.contour(g.mat, cmap=plt.get_cmap('gray'), origin='lower') # plotting the asymmetric gradient field plt.subplot(133) plt.quiver(g.gradient_asymmetric_dx, g.gradient_asymmetric_dy, scale=g.rows * g.cols / 2) plt.tight_layout() plt.show()
def _get_image_object(self): """ Return a shaded image using the matplotlib lightsource based shading engine :return: rgb array """ # Hill shade props lightsource_default_props = {'azdeg': 315.0, 'altdeg': 45.0} shade_default_props = {'blend_mode': 'soft', 'vert_exag': 2.5} # Colormap cmap = truncate_colormap(cmocean.cm.ice, 0.25, 0.95) cmap.set_bad("white") # nodata = np.where(np.isnan(self.dem.grid)) # self.dem.grid[nodata] = 100 vmin, vmax = [-0.25, 1.0] ls = LightSource(**lightsource_default_props) rgb = ls.shade(self.dem.grid, cmap=cmap, vmin=vmin, vmax=vmax, dx=0.5, dy=0.5, **shade_default_props) # nodata_indices = np.where(rgb == [np.nan, np.nan, np.nan, 1]) # for nodata_index in nodata_indices: # rgb[nodata_index] = [0.9, 0.9, 0.9, 1.0] return rgb
def error_signal(utility, fig=None, persp="heat"): plt.title('Used error signals') max_cycles = np.max(np.argmin(utility, axis=1)) + 1 valuesToShow = utility[:, :max_cycles].T # switch cycles and episodes # plt.plot(valuesToShow) if persp == "3d": cycle_axis = np.linspace(0, valuesToShow.shape[0], valuesToShow.shape[0]) episode_axis = np.linspace(0, valuesToShow.shape[1], valuesToShow.shape[1]).T sx = cycle_axis.size sy = episode_axis.size cycle_axis = np.tile(cycle_axis, (sy, 1)) episode_axis = np.tile(episode_axis, (sx, 1)).T if fig is None: newfig = plt.figure() ax = newfig.add_subplot(1, 1, 1, projection='3d') else: ax = fig.add_subplot(3, 1, 1, projection='3d') light = LightSource(315, 45) cm = plt.cm.get_cmap("inferno") azimuth = 45 altitude = 60 ax.view_init(altitude, azimuth) if gv.num_episodes > 1: illuminated_surface = light.shade(valuesToShow, cmap=cm) ax.plot_surface(cycle_axis, episode_axis, valuesToShow, rstride=1, cstride=1, linewidth=0, antialiased=False, facecolors=illuminated_surface, label="utilities") else: ax.plot_surface(cycle_axis, episode_axis, valuesToShow, rstride=1, cstride=1, linewidth=0, antialiased=False, label="utilities") else: current_cmap = plt.cm.get_cmap("inferno") current_cmap.set_bad(color='green') legend = plt.imshow(valuesToShow, cmap=current_cmap, interpolation='nearest') plt.colorbar(legend) plt.ylabel("cycle") plt.xlabel("episode") # plt.title("Utility per cycle") #title is covered in condensed view # plt.legend() if fig is None: plt.show()
def test_light_source_shading_color_range(): # see also #http://matplotlib.org/examples/pylab_examples/shading_example.html from matplotlib.colors import LightSource from matplotlib.colors import Normalize refinput = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) norm = Normalize(vmin=0, vmax=50) ls = LightSource(azdeg=0, altdeg=65) testoutput = ls.shade(refinput, plt.cm.jet, norm=norm) refoutput = np.array([ [[0., 0., 0.58912656, 1.], [0., 0., 0.67825312, 1.], [0., 0., 0.76737968, 1.], [0., 0., 0.85650624, 1.]], [[0., 0., 0.9456328, 1.], [0., 0., 1., 1.], [0., 0.04901961, 1., 1.], [0., 0.12745098, 1., 1.]], [[0., 0.22156863, 1., 1.], [0., 0.3, 1., 1.], [0., 0.37843137, 1., 1.], [0., 0.45686275, 1., 1.]] ]) assert_array_almost_equal(refoutput, testoutput)
def ThrShow(self, data): font1 = { 'family': 'STXihei', 'weight': 'normal', 'size': 50, } fig, ax = plt.subplots(subplot_kw=dict(projection='3d'), figsize=(50, 20)) ls = LightSource(data.shape[0], data.shape[1]) rgb = ls.shade(data, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft') x = np.array([list(range(data.shape[0]))] * data.shape[1]) print(x.shape, x.T.shape, data.shape) surf = ax.plot_surface(x, x.T, data, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False, shade=False, alpha=0.3) fig.colorbar(surf, shrink=0.5, aspect=5) cset = ax.contour(x, x.T, data, zdir='z', offset=37, cmap=cm.coolwarm) cset = ax.contour(x, x.T, data, zdir='x', offset=-30, cmap=cm.coolwarm) cset = ax.contour(x, x.T, data, zdir='y', offset=-30, cmap=cm.coolwarm) plt.show()
def createTopographicImage(self): try: lat, lon = float(self.latEdit.text()), float(self.lonEdit.text()) except: QMessageBox.information( self, "None file Error", "Can't create map. <br> Please Press lat and lon.", QMessageBox.Ok) return elevs = self.elev(lat, lon) elevs[np.isnan(elevs)] = -9999.0 fig, ax = plt.subplots() elevs = np.flipud(elevs) ls = LightSource(azdeg=180, altdeg=65) color = ls.shade(elevs, cmap.rainbow) cs = ax.imshow(elevs, cmap.rainbow) ax.imshow(color) make_axes = make_axes_locatable(ax) cax = make_axes.append_axes("right", size="2%", pad=0.05) fig.colorbar(cs, cax) ax.set_xticks([]) ax.set_yticks([]) fig.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9) canvas = FigureCanvas(fig) canvas.draw() w, h = canvas.get_width_height() self.image = QImage(canvas.buffer_rgba(), w, h, QImage.Format_ARGB32) self.canvas.setPixmap(QPixmap(self.image))
def draw_elevation_shade(self, geodata: 'Optional[GeoData]' = None, layer: 'str' = 'elevation', with_colorbar: 'bool' = False, label: 'str' = "Elevation", **kwargs): gd = self._geodata if geodata is None else geodata z = gd[layer].T[::-1, ...] if 'vmin' not in kwargs: kwargs['vmin'] = np.nanmin(z) if 'vmax' not in kwargs: kwargs['vmax'] = np.nanmax(z) if 'cmap' not in kwargs: kwargs['cmap'] = matplotlib.cm.gist_earth if 'interpolation' not in kwargs: kwargs['interpolation'] = 'none' if 'extent' not in kwargs: kwargs['extent'] = self._image_scale ls = LightSource(azdeg=315, altdeg=35) axim = self.axes.imshow( ls.shade(z, cmap=kwargs['cmap'], blend_mode='soft', vert_exag=1, dx=gd.cell_width, dy=gd.cell_height, vmin=kwargs['vmin'], vmax=kwargs['vmax']), **kwargs) self._drawings.append(axim) if with_colorbar: self._add_elevation_shade_colorbar(axim, label) return axim
def SurfPlot(data): from mpl_toolkits.mplot3d import Axes3D from matplotlib import cbook from matplotlib import cm from matplotlib.colors import LightSource import matplotlib.pyplot as plt import numpy as np ncols, nrows = data.shape if ncols * nrows > 20000: print 'Warning, surface plotting things of this size is slow...' z = data x = np.linspace(0, ncols, ncols) y = np.linspace(0, nrows, nrows) x, y = np.meshgrid(x, y) region = np.s_[0:min(ncols,nrows), 0:min(ncols,nrows)] x, y, z = x[region], y[region], z[region] fig, ax = plt.subplots(subplot_kw=dict(projection='3d'), figsize=(10,10)) ls = LightSource(270, 45) # To use a custom hillshading mode, override the built-in shading and pass # in the rgb colors of the shaded surface calculated from "shade". rgb = ls.shade(z, cmap=cm.CMRmap, vert_exag=0.01, blend_mode='soft') surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=True, shade=False) plt.show()
def background_map(self, ax): llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon, lat_ts = (31, 44, -126, -113, 37.5) m = Basemap(projection='merc', llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, lat_ts=lat_ts, resolution='i', ax=ax) m.drawmapboundary(fill_color='lightblue', zorder=0) m.fillcontinents(zorder=0) etopofn = '/home/behry/uni/data/etopo1_central_europe_gmt.grd' etopodata = Dataset(etopofn, 'r') z = etopodata.variables['z'][:] x_range = etopodata.variables['x_range'][:] y_range = etopodata.variables['y_range'][:] spc = etopodata.variables['spacing'][:] lats = np.arange(y_range[0], y_range[1], spc[1]) lons = np.arange(x_range[0], x_range[1], spc[0]) topoin = z.reshape(lats.size, lons.size, order='C') # transform to nx x ny regularly spaced 5km native projection grid nx = int((m.xmax - m.xmin) / 5000.) + 1; ny = int((m.ymax - m.ymin) / 5000.) + 1 topodat, x, y = m.transform_scalar(np.flipud(topoin), lons, lats, nx, ny, returnxy=True) ls = LightSource(azdeg=300, altdeg=15, hsv_min_sat=0.2, hsv_max_sat=0.3, hsv_min_val=0.2, hsv_max_val=0.3) # shade data, creating an rgb array. rgb = ls.shade(np.ma.masked_less(topodat / 1000.0, 0.0), cm.gist_gray_r) m.imshow(rgb) m.drawmeridians(np.arange(6, 12, 2), labels=[0, 0, 0, 1], color='white', linewidth=0.5, zorder=0) m.drawparallels(np.arange(44, 50, 2), labels=[1, 0, 0, 0], color='white', linewidth=0.5, zorder=0) m.drawcoastlines(zorder=1) m.drawcountries(linewidth=1.5, zorder=1) m.drawstates() m.drawrivers(color='lightblue', zorder=1) return m
def render(a, cmap=default_cmap, land_mask=None, angle=270): if land_mask is None: land_mask = np.ones_like(a) ls = LightSource(azdeg=angle, altdeg=30) land = ls.shade( a, cmap=cmap, vert_exag=10.0, blend_mode='overlay')[:, :, :3] water = np.tile((0.25, 0.35, 0.55), a.shape + (1, )) return lerp(water, land, land_mask[:, :, np.newaxis])
def _plot_surface(ax, x, y, z, cmap=None, **kwargs): """ Args: ax: x: y: z: cmap: **kwargs: """ if cmap is None: cmap = cm.gist_earth ls = LightSource(270, 45) # To use a custom hillshading mode, override the built-in shading and pass # in the rgb colors of the shaded surface calculated from "shade". rgb = ls.shade(z, cmap=cm.get_cmap(cmap), vert_exag=0.1, blend_mode="soft") surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False, shade=False, **kwargs) return surf
def plot(self, shading=True, ve=1, cmap=plt.cm.gist_earth, vmin=-5000, vmax=0, **kwargs): # Illuminate the scene from the northwest Zplot = 1 * self.Z if self.y[0] < self.y[-1]: Zplot = Zplot[::-1, :] if shading: Zplot[np.isnan(Zplot)] = 0. ls = LightSource(azdeg=315, altdeg=25) rgb = ls.shade(Zplot, cmap=cmap, vert_exag=ve, blend_mode='overlay',\ vmin=vmin, vmax=vmax) #h= plt.figure(figsize=(9,8)) #h.imshow(np.flipud(self.Z),extent=[bbox[0],bbox[1],bbox[3],bbox[2]]) h = plt.imshow(rgb, extent=[self.x0, self.x1, self.y0, self.y1], **kwargs) else: h = plt.imshow(Zplot, extent=[self.x0,self.x1,self.y0,self.y1],\ vmin=vmin, vmax=vmax, cmap=cmap, **kwargs) plt.colorbar(h)
def show_topography(img, chnl, br=0, ve=0.5, cm=0): cmaps = [plt.cm.nipy_spectral, plt.cm.terrain, plt.cm.gist_earth] filtered = None if 0 != br: blured = img.filter(ImageFilter.GaussianBlur(br)) filtered = np.asarray(blured.getchannel(chnl)) imgc = np.asarray(img.getchannel(chnl)) title = 'Unknown' if chnl is 'R': title = 'Red ' elif chnl is 'G': title = 'Green ' elif chnl is 'B': title = 'Blue ' else: pass ls = LightSource(azdeg=45, altdeg=45) fig, axes = plt.subplots(1, 2, figsize=(9.0, 4.0)) # fig.tight_layout() fig.canvas.set_window_title(title + ' Channel Topography - ' + img.filename) axes[0].axis('off') axes[0].set_title(title + ' Channel') axes[0].imshow(imgc, cmap='gray') axes[1].axis('off') axes[1].set_title(title + ' Channel Topography [BR:' + (str(br) if filtered is not None else 'None') + ', VE:' + str(ve) + ']') elevated = ls.shade((filtered if filtered is not None else imgc), cmap=cmaps[cm], blend_mode='overlay', vert_exag=ve) axes[1].imshow(elevated)
def _generateDEMPlot(X, Y, z, title): """Generates 3d DEM plot, use this to style the plot""" plt.figure(figsize=(10, 10)) ax = plt.axes(projection='3d') ls = LightSource(270, 45) # To use a custom hillshading mode, override the built-in shading and pass # in the rgb colors of the shaded surface calculated from "shade". rgb = ls.shade(z, cmap=cm.viridis, vert_exag=0.1, blend_mode='soft') surf = ax.plot_surface(X, Y, z, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False, shade=False) # These are other options to plot in 3d in case another look is needed # ax.contour(X, Y, z, 20, linewidth=3, colors="g", linestyles="solid") # ax.plot_wireframe(X, Y, z, rstride=100, cstride=100,lw=1) # ax.plot_surface(X, Y, z, cmap=plt.cm.viridis, # linewidth=0, antialiased=False) ax.set_title('DEM: %s' % title) ax.set_xlabel('x [m]') ax.set_ylabel('y [m]') ax.set_zlabel('elevation (m)') return ax
def draw_terrain3d(file, category): logging.info("3d plot " + category + " is running") df = getfov_draw_data(file) X = [int(i) - 1 for i in df['Row'][30:]] Y = [int(i) - 1 for i in df['Row'][30:]] Z = [float(i) for i in df[category][30:]] xpos_arr = np.array(X).reshape(40, 40) ypos_arr = np.array(Y).reshape(40, 40) zpos_arr = np.array(Z).reshape(40, 40) fig = plt.figure() ax = fig.gca(projection='3d') ls = LightSource(270, 45) rgb = ls.shade(zpos_arr, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft') # ax.plot_surface(xpos_arr , ypos_arr, zpos_arr, cmap='autumn', # rstride = 1, cstride = 1, facecolors = rgb, # linewidth = 0, antialiased = False, shade = False # ) ax.plot_surface(xpos_arr, ypos_arr, zpos_arr, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False, shade=False) ax.set_xlabel("X label") ax.set_ylabel("Y label") ax.set_zlabel("Z label") plt.show()
def hillshade( raster_obj, figsize=None, azdeg=315, altdeg=45, vert_exag=1, cmap=None, blend_mode='overlay', alpha=1, relocate=False, scale_ratio=1, ): """ Draw a hillshade map """ array = raster_obj.array + 0 if 'NODATA_value' in raster_obj.header: array[array == raster_obj.header['NODATA_value']] = np.nan array[np.isnan(array)] = np.nanmax(array) ls = LightSource(azdeg=azdeg, altdeg=altdeg) if cmap is None: cmap = plt.cm.gist_earth else: cmap = plt.get_cmap(cmap) fig, ax = plt.subplots(figsize=figsize) rgb = ls.shade(array, cmap=cmap, blend_mode=blend_mode, vert_exag=vert_exag) ax.imshow(rgb, extent=raster_obj.extent, alpha=alpha) _adjust_axis_tick(ax, relocate, scale_ratio) return fig, ax
def plot_custom_shaded_3d_surface(): # 还没有搞清楚这个代码的意思。 from mpl_toolkits.mplot3d import Axes3D from matplotlib import cbook from matplotlib import cm from matplotlib.colors import LightSource filename = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False) with np.load(filename) as dem: z = dem['elevation'] nrows, ncols = z.shape x = np.linspace(dem['xmin'], dem['xmax'], ncols) y = np.linspace(dem['ymin'], dem['ymax'], nrows) x, y = np.meshgrid(x, y) region = np.s_[5:50, 5:50] x, y, z = x[region], y[region], z[region] fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) ls = LightSource(270, 45) rgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft') surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False, shade=False)
def createLatLonTimeAverageMap(res, meta, startTime=None, endTime=None): latSeries = [m[0]['lat'] for m in res][::-1] lonSeries = [m['lon'] for m in res[0]] data = np.zeros((len(latSeries), len(lonSeries))) for t in range(0, len(latSeries)): latSet = res[t] for l in range(0, len(lonSeries)): data[len(latSeries) - t - 1][l] = latSet[l]['avg'] def yFormatter(y, pos): if y < len(latSeries): return '%s $^\circ$' % (int(latSeries[int(y)] * 100.0) / 100.) else: return "" def xFormatter(x, pos): if x < len(lonSeries): return "%s $^\circ$" % (int(lonSeries[int(x)] * 100.0) / 100.) else: return "" data[data == 0.0] = np.nan fig, ax = plt.subplots() fig.set_size_inches(11.0, 8.5) cmap = cm.coolwarm ls = LightSource(315, 45) masked_array = np.ma.array(data, mask=np.isnan(data)) rgb = ls.shade(masked_array, cmap) cax = ax.imshow(rgb, interpolation='nearest', cmap=cmap) ax.yaxis.set_major_formatter(FuncFormatter(yFormatter)) ax.xaxis.set_major_formatter(FuncFormatter(xFormatter)) title = meta['title'] source = meta['source'] if startTime is not None and endTime is not None: if type(startTime) is not datetime.datetime: startTime = datetime.datetime.fromtimestamp(startTime / 1000) if type(endTime) is not datetime.datetime: endTime = datetime.datetime.fromtimestamp(endTime / 1000) dateRange = "%s - %s" % (startTime.strftime('%b %Y'), endTime.strftime('%b %Y')) else: dateRange = "" ax.set_title("%s\n%s\n%s" % (title, source, dateRange)) ax.set_ylabel('Latitude') ax.set_xlabel('Longitude') fig.colorbar(cax) fig.autofmt_xdate() sio = StringIO() plt.savefig(sio, format='png') return sio.getvalue()
def heat_map(self, X, Y, Z, x, y): """ modifies heat_figure (declared at init) and produces a heat map of the given x,y,z data :param X: X component of numpy meshgrid :param Y: Y component of numpy meshgrid :param Z: Z component of scipy griddata/Rbf interpolation :param x: data points in the x axis (longitude) :param y: data points in the y axis (latitude) :return: N/A """ self.heat_figure.clear() # create an axis self.heatMap_ax = self.heat_figure.add_subplot(111, sharex=self.contour_ax, sharey=self.contour_ax) self.heatMap_ax.set_facecolor('lightsteelblue') # discards the old graph self.heatMap_ax.clear() # light source colormap = cm.get_cmap(self.colormap) ls = LightSource(azdeg=315, altdeg=25) rgb = ls.shade(np.flipud(Z), colormap, vert_exag=1, blend_mode='overlay') # generate contours ct = self.heatMap_ax.contour(X, Y, Z, 16, colors='black', linestyles='solid') self.heatMap_ax.clabel(ct, inline=1, fontsize=8) self.heatMap_ax.imshow( rgb, cmap=self.colormap, extent=[np.min(x), np.max(x), np.min(y), np.max(y)], aspect='auto') # cax = ax.pcolormesh(X, Y, Z, cmap=self.colormap) # color bar self.heat_figure.colorbar(self.cax1, orientation='horizontal') self.heatMap_ax.spines['top'].set_color('ghostwhite') self.heatMap_ax.spines['right'].set_color('ghostwhite') self.heatMap_ax.spines['bottom'].set_color('ghostwhite') self.heatMap_ax.spines['left'].set_color('ghostwhite') self.heatMap_ax.tick_params(color='white') self.heatMap_ax.grid(True, color='ghostwhite', linestyle='-', linewidth=0.3) self.heat_canvas.draw()
def _get_image_object(self): # TODO: Documentation vmin, vmax = self._get_range() # TODO: Allow hillshading configuration ls = LightSource(azdeg=315, altdeg=45) rgb = ls.shade(self.dem.dem_z_masked, cmap=self._cmap, blend_mode="soft", vmin=vmin, vmax=vmax, vert_exag=10, dx=self.dem.cfg.resolution, dy=self.dem.cfg.resolution) return rgb
def cal_lambda(fliename1, fliename2, nbnd, nks, dos, outdata_name): thz2ry = 0.00030428427852 cm2thz = 0.02998 kpoint_array1, linewidth_array = extract_linewidth(fliename1, nbnd, nks) #unit = GHz kpoint_array2, freq_array = extract_linewidth(fliename2, nbnd, nks) # unit = THz lamb_mode = (linewidth_array * 0.001 * thz2ry) / (dos * pi) / (freq_array*cm2thz*thz2ry) / (freq_array*cm2thz*thz2ry) #lamb_mode = [] #print freq_array[2] #for i in range(len(freq_array)): # if freq_array[i] < 20: # cutoff = 20cm-1 # lamb_mode.append(0.0) # else: # temp = (linewidth_array[i] * 0.001 * thz2ry) / (dos * pi) / (freq_array[i]*cm2thz*thz2ry) / (freq_array[i]*cm2thz*thz2ry) # lamb_mode.append(temp) #print linewidth_array #lamb_mode = np.array(lamb_mode) lamb = [] for i in range(len(lamb_mode)): find_cutoff_freq = np.where(freq_array[i] < 20.0)[0] if len(find_cutoff_freq) != 0: #print zfind_zero_freq for j in range(len(find_cutoff_freq)): #print lamb_mode[i] lamb_mode[i][j] = 0.0 temp = np.sum(lamb_mode[i]) lamb.append(temp) lamb = np.array(lamb) #print kpoint_array1[5100] #print kpoint_array2[5100] #print linewidth_array[5100] #print freq_array[5100] #print lamb[5100] #print lamb[5101] print 'max lambda is ', max(lamb), 'min lambda is ', min(lamb) print 'All sum of lambda = ', np.sum(lamb)/len(freq_array) #print len(kpoint_array1)#.reshape((101,101)) z = lamb.reshape((101,101)).T #print lamb[101] #print kpoint_array1[3] #print z[1][0] cmap = plt.cm.gist_earth ls = LightSource(315, 45) rgb = ls.shade(z, cmap, vmin=0.0, vmax=7) fig, ax = plt.subplots(figsize=(8, 7)) ax.imshow(rgb, interpolation='gaussian', aspect="auto") ax1 = fig.add_axes([0.05, 0.05, 0.9, 0.05]) cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, orientation='horizontal') plt.show() np.save(outdata_name+'_kpoint', kpoint_array1) np.save(outdata_name+'_lambda', lamb) return kpoint_array1, lamb
def apply(self): from mpl_toolkits.basemap import shiftgrid, cm common.ShowQuestion display = self.VpyartDisplay.value if (isinstance(display, pyart.graph.RadarMapDisplay) or isinstance(display, pyart.graph.GridMapDisplay)): pass elif (isinstance(display, pyart.graph.RadarDisplay) or isinstance(display, pyart.graph.AirborneRadarDisplay)): common.ShowWarning( "Topography require a MapDisplay, be sure to " "check the 'use MapDisplay' box in the 'Display Options' Menu") return else: common.ShowWarning( "Need a pyart display instance, be sure to " "link this components (%s), to a radar or grid display" % self.name) return filename = str(self.lineEdit.text()) if filename != self.current_open: if filename.startswith("http"): resp = common.ShowQuestion( "Loading a file from the internet may take long." + " Are you sure you want to continue?") if resp != QtWidgets.QMessageBox.Ok: return self.etopodata = Dataset(filename) self.current_open = filename topoin = np.maximum(0, self.etopodata.variables['ROSE'][:]) lons = self.etopodata.variables['ETOPO05_X'][:] lats = self.etopodata.variables['ETOPO05_Y'][:] # shift data so lons go from -180 to 180 instead of 20 to 380. topoin, lons = shiftgrid(180., topoin, lons, start=False) # plot topography/bathymetry as an image. # create the figure and axes instances. # setup of basemap ('lcc' = lambert conformal conic). # use major and minor sphere radii from WGS84 ellipsoid. m = self.VpyartDisplay.value.basemap # transform to nx x ny regularly spaced 5km native projection grid nx = int((m.xmax - m.xmin) / 500.) + 1 ny = int((m.ymax - m.ymin) / 500.) + 1 topodat = m.transform_scalar(topoin, lons, lats, nx, ny) # plot image over map with imshow. # draw coastlines and political boundaries. ls = LightSource(azdeg=90, altdeg=20) # convert data to rgb array including shading from light source. # (must specify color map) rgb = ls.shade(topodat, cm.GMT_relief) im = m.imshow(rgb) self.VpyartDisplay.update(strong=False)
def apply(self): from mpl_toolkits.basemap import shiftgrid, cm common.ShowQuestion display = self.VpyartDisplay.value if (isinstance(display, pyart.graph.RadarMapDisplay) or isinstance(display, pyart.graph.GridMapDisplay)): pass elif (isinstance(display, pyart.graph.RadarDisplay) or isinstance(display, pyart.graph.AirborneRadarDisplay)): common.ShowWarning( "Topography require a MapDisplay, be sure to " "check the 'use MapDisplay' box in the 'Display Options' Menu") return else: common.ShowWarning( "Need a pyart display instance, be sure to " "link this components (%s), to a radar or grid display" % self.name) return filename = str(self.lineEdit.text()) if filename != self.current_open: if filename.startswith("http"): resp = common.ShowQuestion( "Loading a file from the internet may take long." + " Are you sure you want to continue?") if resp != QtWidgets.QMessageBox.Ok: return self.etopodata = Dataset(filename) self.current_open = filename topoin = np.maximum(0, self.etopodata.variables['ROSE'][:]) lons = self.etopodata.variables['ETOPO05_X'][:] lats = self.etopodata.variables['ETOPO05_Y'][:] # shift data so lons go from -180 to 180 instead of 20 to 380. topoin, lons = shiftgrid(180., topoin, lons, start=False) # plot topography/bathymetry as an image. # create the figure and axes instances. # setup of basemap ('lcc' = lambert conformal conic). # use major and minor sphere radii from WGS84 ellipsoid. m = self.VpyartDisplay.value.basemap # transform to nx x ny regularly spaced 5km native projection grid nx = int((m.xmax - m.xmin)/500.) + 1 ny = int((m.ymax - m.ymin)/500.) + 1 topodat = m.transform_scalar(topoin, lons, lats, nx, ny) # plot image over map with imshow. # draw coastlines and political boundaries. ls = LightSource(azdeg=90, altdeg=20) # convert data to rgb array including shading from light source. # (must specify color map) rgb = ls.shade(topodat, cm.GMT_relief) im = m.imshow(rgb) self.VpyartDisplay.update(strong=False)
def plot_matrix2(g): plt.figure(figsize=(15, 5)) #plt.suptitle("Ga: "+str(round(max(g.G2,g.G1,g.G3),3)),fontsize=18) azimuth = 137 altitude = 40 mat = g.mat plt.axis('off') ax = plt.subplot(131, projection='3d') #plt.title("3D") light = LightSource(90, 45) green = np.array([0, 1.0, 0]) X, Y = np.meshgrid([m for m in range(len(mat))], [n for n in range(len(mat))]) z = np.array(mat) ax.view_init(altitude, azimuth) illuminated_surface = light.shade(z, cmap=cm.coolwarm) rgb = np.ones((z.shape[0], z.shape[1], 3)) green_surface = light.shade_rgb(rgb * green, z) ax.plot_surface(X, Y, z, rstride=1, cstride=1, linewidth=0, antialiased=True, facecolors=illuminated_surface) # ax.plot_wireframe(X,Y,z) #plt.axis('off') ax.set_zticks([]) ax.grid(False) sbplt = plt.subplot(132) #plt.title("Contour") plt.contour(g.mat, cmap=plt.get_cmap('gray'), origin='lower') # plotting the asymmetric gradient field plt.subplot(133) plt.quiver(g.gradient_asymmetric_dx, g.gradient_asymmetric_dy, scale=1.0 / 0.1) #plt.title("Asymmetric Gradient Field") #plt.title("C",fontsize=20) # plotting the triangulation #if g.n_edges > 0: # plt.subplot(133) #plt.xlim(0,len(g.mat[0])) #plt.ylim(0,len(g.mat)) # plt.triplot(g.triangulation_points[:,0], g.triangulation_points[:,1], g.triangles.simplices.copy()) # plt.title("Triangulation") #plt.title("D",fontsize=20) plt.tight_layout() plt.show()
def show_landscape(adata, Xgrid, Ygrid, Zgrid, basis='trimap'): """Plot the quasi-potential landscape. Parameters ---------- adata: :class:`~anndata.AnnData` AnnData object that contains Xgrid, Ygrid and Zgrid data for visualizing potential landscape. Xgrid: `numpy.ndarray` x-coordinates of the Grid produced from the meshgrid function. Ygrid: `numpy.ndarray` y-coordinates of the Grid produced from the meshgrid function. Zgrid: `numpy.ndarray` z-coordinates or potential at each of the x/y coordinate. basis: `str` (default: trimap) The method of dimension reduction. By default it is trimap. Currently it is not checked with Xgrid and Ygrid. Returns ------- A 3D plot showing the quasi-potential of each cell state. """ if 'grid_Pot_' + basis in adata.uns.keys(): Xgrid_, Ygrid_, Zgrid_ = adata.uns['grid_Pot_' + basis]['Xgrid'], adata.uns['grid_Pot_' + basis]['Ygrid'], adata.uns['grid_Pot_' + basis]['Zgrid'] Xgrid = Xgrid_ if Xgrid is None else Xgrid Ygrid = Ygrid_ if Ygrid is None else Ygrid Zgrid = Zgrid_ if Zgrid is None else Zgrid from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib.colors import LightSource fig = plt.figure() ax = fig.gca(projection='3d') # Plot the surface. ls = LightSource(azdeg=0, altdeg=65) # Shade data, creating an rgb array. rgb = ls.shade(Zgrid, plt.cm.RdYlBu) surf = ax.plot_surface(Xgrid, Ygrid, Zgrid, cmap=cm.coolwarm, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False) # Customize the z axis. ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # Add a color bar which maps values to colors. # fig.colorbar(surf, shrink=0.5, aspect=5) ax.set_xlabel(basis + '_1') ax.set_ylabel(basis + '_2') ax.set_zlabel('U') plt.show()
def animate3D(u,v,h,H,dt): print('Saving 3D figures...') # specify max and min contours minh, maxh = np.amin(h),np.amax(h) norm_h = colors.TwoSlopeNorm(vmin=minh, vcenter=H, vmax=maxh) # colormap cmap = 'cmo.deep' # add light for shadings ls = LightSource(azdeg=315, altdeg=45) # loop to animate for t in range(round(tmax/frecplot)+1): # fig params fig = plt.figure(figsize=(20, 10)) # 3D plot ax = fig.add_subplot(1, 2, 1, projection='3d') ax.set_zlim(minh, maxh) # view zimuth and angle ax.view_init(50, 260) # labels in km ax.set_xlabel('X (km)', fontweight='bold') ax.set_ylabel('Y (km)', fontweight='bold') ax.set_zlabel('Height (m)', fontweight='bold') # plot surface z = h[t] rgb = ls.shade(z, cmap=cmo.deep, vert_exag=0.1, blend_mode='soft') ax.plot_surface(lonsh/1e3,latsh/1e3, z, rstride=1, cstride=1, facecolors=rgb, cmap = cmap, linewidth=0, antialiased=False, shade=False, norm=norm_h) ax.set_title('Surface elevation h(x,y,t) after t ='\ +str(round(t*dt*frecplot/60/60/24,2))+'d, '+ \ str(round(t*dt/60/60,2))+'h') # plot vectors ax = fig.add_subplot(1, 2, 2) u_mean = (u[t][:,:-1]+u[t][:,1:])/2 v_mean = (v[t][:-1]+v[t][1:])/2 ax.quiver(lonsh[::5]/1e3,latsh[::5]/1e3, u_mean[::5],v_mean[::5],scale=0.5) ax.set_title('Velocity field u(x,y,t) after t ='\ +str(round(t*dt*frecplot/60/60/24,2))+'d, '+ \ str(round(t*dt/60/60,2))+'h') print('animating timestep = '+str(t)) pl.savefig('./3Dfigs/'+str(t)+'.png')
def background_map(self, ax): llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon, lat_ts = (31, 44, -126, -113, 37.5) m = Basemap(projection='merc', llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, lat_ts=lat_ts, resolution='i', ax=ax) m.drawmapboundary(fill_color='lightblue', zorder=0) m.fillcontinents(zorder=0) etopofn = '/home/behry/uni/data/etopo1_central_europe_gmt.grd' etopodata = Dataset(etopofn, 'r') z = etopodata.variables['z'][:] x_range = etopodata.variables['x_range'][:] y_range = etopodata.variables['y_range'][:] spc = etopodata.variables['spacing'][:] lats = np.arange(y_range[0], y_range[1], spc[1]) lons = np.arange(x_range[0], x_range[1], spc[0]) topoin = z.reshape(lats.size, lons.size, order='C') # transform to nx x ny regularly spaced 5km native projection grid nx = int((m.xmax - m.xmin) / 5000.) + 1 ny = int((m.ymax - m.ymin) / 5000.) + 1 topodat, x, y = m.transform_scalar(np.flipud(topoin), lons, lats, nx, ny, returnxy=True) ls = LightSource(azdeg=300, altdeg=15, hsv_min_sat=0.2, hsv_max_sat=0.3, hsv_min_val=0.2, hsv_max_val=0.3) # shade data, creating an rgb array. rgb = ls.shade(np.ma.masked_less(topodat / 1000.0, 0.0), cm.gist_gray_r) m.imshow(rgb) m.drawmeridians(np.arange(6, 12, 2), labels=[0, 0, 0, 1], color='white', linewidth=0.5, zorder=0) m.drawparallels(np.arange(44, 50, 2), labels=[1, 0, 0, 0], color='white', linewidth=0.5, zorder=0) m.drawcoastlines(zorder=1) m.drawcountries(linewidth=1.5, zorder=1) m.drawstates() m.drawrivers(color='lightblue', zorder=1) return m
def avoid_outliers(): """Use a custom norm to control the displayed z-range of a shaded plot.""" y, x = np.mgrid[-4:2:200j, -4:2:200j] z = 10 * np.cos(x**2 + y**2) # Add some outliers... z[100, 105] = 2000 z[120, 110] = -9000 ls = LightSource(315, 45) fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4.5)) rgb = ls.shade(z, plt.cm.copper) ax1.imshow(rgb) ax1.set_title('Full range of data') rgb = ls.shade(z, plt.cm.copper, vmin=-10, vmax=10) ax2.imshow(rgb) ax2.set_title('Manually set range') fig.suptitle('Avoiding Outliers in Shaded Plots', size='x-large')
def plotRainbow(self): self.setUp() ls = LightSource(270, 45) # To use a custom hillshading mode, override the built-in shading and pass # in the rgb colors of the shaded surface calculated from "shade". rgb = ls.shade(self.Z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft') self.ax.plot_surface(self.X, self.Y, self.Z, facecolors=rgb) self.setLabels() plt.show()
def getTopoRGB(topogrid): topotmp = topogrid.getData().copy() # make a masked array topotmp = np.ma.array(topotmp) topodat = np.ma.masked_where(np.isnan(topotmp), topotmp) cy = topogrid.geodict["ymin"] + (topogrid.geodict["ymax"] - topogrid.geodict["ymin"]) / 2.0 # flag the regions where topography is less than 0 (we'll color this ocean later) i = np.where(topodat == SEA_LEVEL) # do shaded relief stuff # keys are latitude values # values are multiplication factor zdict = { 0: 0.00000898, 10: 0.00000912, 20: 0.00000956, 30: 0.00001036, 40: 0.00001171, 50: 0.00001395, 60: 0.00001792, 70: 0.00002619, 80: 0.00005156, } # find the mean latitude of the map we're making, and use that to come up with a zfactor mlat = abs(int(round(cy / 10) * 10)) zfactor = zdict[mlat] ls = LightSource(azdeg=AZDEFAULT, altdeg=ALTDEFAULT) # draw the ocean in light blue water_color = [0.47, 0.60, 0.81] palette1 = copy.deepcopy(cm.binary) # draw the light shaded-topography rgbdata = topodat * zfactor # apply the latitude specific zfactor correction rgb = ls.shade(rgbdata, cmap=palette1) # apply the light shading to our corrected topography # this is an rgb data set now, so masking the pixels won't work, but explicitly setting all of the # "bad" pixels to our water color will red = rgb[:, :, 0] green = rgb[:, :, 1] blue = rgb[:, :, 2] red[i] = water_color[0] green[i] = water_color[1] blue[i] = water_color[2] rgb[:, :, 0] = red rgb[:, :, 1] = green rgb[:, :, 2] = blue rgb = np.flipud(rgb) return (rgb, palette1)
def compare(z, cmap, ve=1): # Create subplots and hide ticks fig, axes = plt.subplots(ncols=2, nrows=2) for ax in axes.flat: ax.set(xticks=[], yticks=[]) # Illuminate the scene from the northwest ls = LightSource(azdeg=315, altdeg=45) axes[0, 0].imshow(z, cmap=cmap) axes[0, 0].set(xlabel='Colormapped Data') axes[0, 1].imshow(ls.hillshade(z, vert_exag=ve), cmap='gray') axes[0, 1].set(xlabel='Illumination Intensity') rgb = ls.shade(z, cmap=cmap, vert_exag=ve, blend_mode='hsv') axes[1, 0].imshow(rgb) axes[1, 0].set(xlabel='Blend Mode: "hsv" (default)') rgb = ls.shade(z, cmap=cmap, vert_exag=ve, blend_mode='overlay') axes[1, 1].imshow(rgb) axes[1, 1].set(xlabel='Blend Mode: "overlay"') return fig
def display_depth_matplotlib(z): """ Same as above but using matplotlib instead. """ from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import LightSource m, n = z.shape x, y = np.mgrid[0:m, 0:n] fig = plt.figure() ax = fig.gca(projection='3d') ls = LightSource(azdeg=0, altdeg=65) greyvals = ls.shade(z, plt.cm.Greys) ax.plot_surface(x, y, z, rstride=1, cstride=1, linewidth=0, antialiased=False, facecolors=greyvals) plt.axis('off') plt.axis('equal') plt.show()
def display_colorbar(): """Display a correct numeric colorbar for a shaded plot.""" y, x = np.mgrid[-4:2:200j, -4:2:200j] z = 10 * np.cos(x**2 + y**2) cmap = plt.cm.copper ls = LightSource(315, 45) rgb = ls.shade(z, cmap) fig, ax = plt.subplots() ax.imshow(rgb) # Use a proxy artist for the colorbar... im = ax.imshow(z, cmap=cmap) im.remove() fig.colorbar(im) ax.set_title('Using a colorbar with a shaded plot', size='x-large')
def main3(): ax = plt.axes(projection=ccrs.PlateCarree()) elev, crs, extent = io_srtm.srtm_composite(-5, 52, 2, 2) elev = np.ma.masked_less_equal(elev, 0, copy=False) use_mpl_light_source = False if use_mpl_light_source: from matplotlib.colors import LightSource ls = LightSource(azdeg=90, altdeg=80, hsv_min_val=0.6, hsv_min_sat=0.9, hsv_max_val=0.8, hsv_max_sat=1, ) rgb = ls.shade(elev, plt.get_cmap('Greens', 3)) else: import matplotlib.colors as mcolors rgb = set_shade(elev, cmap=mcolors.ListedColormap([plt.get_cmap('Greens', 3)(0.5)]) ) ax.imshow(rgb, extent=extent, transform=crs ) x = np.linspace(extent[0], extent[1], elev.shape[0]) y = np.linspace(extent[2], extent[3], elev.shape[1]) # # ax.contour(x, y, elev, 100, # linestyles='-', # colors='blue', # linewidths=0.3, # alpha=0.4, # transform=crs, # ) plt.show()
def mapwithtopo(p,ax=[],cutdepth=[],aspect=2.5,cmap=[],dlon=30,dlat=10,smooth=False): import popy,os from netCDF4 import Dataset from mpl_toolkits.basemap import shiftgrid from matplotlib.colors import LightSource import pylab as plt import numpy as np etopofn='/net/mazdata2/jinbo/mdata5-jinbo/obs/ETOPO/ETOPO1_Bed_g_gmt4.grd' etopo = Dataset(etopofn,'r').variables x,y,z=etopo['x'][1:],etopo['y'][1:],etopo['z'][1:,1:] dx,dy=5,5 x=x.reshape(-1,dx).mean(axis=-1) y=y.reshape(-1,dx).mean(axis=-1) z=z.reshape(y.size,dx,x.size,dx).mean(axis=-1).mean(axis=1) if smooth: z=popy.utils.smooth2d(z,window_len=3) if cutdepth!=[]: z[z<cutdepth]=cutdepth if ax==[]: fig=plt.figure() ax=fig.add_subplot() if cmap==[]: cmap=plt.cm.Greys z,x = shiftgrid(p[0],z,x,start=True) lon,lat,z = popy.utils.subtractsubdomain(x,y,p,z) m = setmap(p=p,dlon=dlon,dlat=dlat) x, y = m(*np.meshgrid(lon, lat)) ls = LightSource(azdeg=90, altdeg=45) rgb = ls.shade(z, cmap=cmap) m.imshow(rgb, aspect=aspect) plt.savefig('/tmp/tmp.png') os.popen('eog /tmp/tmp.png') return etopo
def draw_3d(self): """ Draw various 3D plots """ self.init_axes() bb = fb.fil[0]['ba'][0] aa = fb.fil[0]['ba'][1] zz = np.array(fb.fil[0]['zpk'][0]) pp = np.array(fb.fil[0]['zpk'][1]) wholeF = fb.fil[0]['freqSpecsRangeType'] != 'half' # not used f_S = fb.fil[0]['f_S'] N_FFT = params['N_FFT'] alpha = self.diaAlpha.value()/10. cmap = cm.get_cmap(str(self.cmbColormap.currentText())) # Number of Lines /step size for H(f) stride, mesh, contour3d: stride = 10 - self.diaHatch.value() NL = 3 * self.diaHatch.value() + 5 surf_enabled = qget_cmb_box(self.cmbMode3D, data=False) in {'Surf', 'Contour'} self.cmbColormap.setEnabled(surf_enabled) self.chkColormap_r.setEnabled(surf_enabled) self.chkLighting.setEnabled(surf_enabled) self.chkColBar.setEnabled(surf_enabled) self.diaAlpha.setEnabled(surf_enabled or self.chkContour2D.isChecked()) #cNorm = colors.Normalize(vmin=0, vmax=values[-1]) #scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) #----------------------------------------------------------------------------- # Calculate H(w) along the upper half of unity circle #----------------------------------------------------------------------------- [w, H] = sig.freqz(bb, aa, worN=N_FFT, whole=True) H = np.nan_to_num(H) # replace nans and inf by finite numbers H_abs = abs(H) H_max = max(H_abs) H_min = min(H_abs) #f = w / (2 * pi) * f_S # translate w to absolute frequencies #F_min = f[np.argmin(H_abs)] plevel_rel = 1.05 # height of plotted pole position relative to zmax zlevel_rel = 0.1 # height of plotted zero position relative to zmax if self.chkLog.isChecked(): # logarithmic scale bottom = np.floor(max(self.zmin_dB, 20*log10(H_min)) / 10) * 10 top = self.zmax_dB top_bottom = top - bottom zlevel = bottom - top_bottom * zlevel_rel if self.cmbMode3D.currentText() == 'None': # "Poleposition" for H(f) plot only plevel_top = 2 * bottom - zlevel # height of displayed pole position plevel_btm = bottom else: plevel_top = top + top_bottom * (plevel_rel - 1) plevel_btm = top else: # linear scale bottom = max(self.zmin, H_min) # min. display value top = self.zmax # max. display value top_bottom = top - bottom # top = zmax_rel * H_max # calculate display top from max. of H(f) zlevel = bottom + top_bottom * zlevel_rel # height of displayed zero position if self.cmbMode3D.currentText() == 'None': # "Poleposition" for H(f) plot only #H_max = np.clip(max(H_abs), 0, self.zmax) # make height of displayed poles same to zeros plevel_top = bottom + top_bottom * zlevel_rel plevel_btm = bottom else: plevel_top = plevel_rel * top plevel_btm = top # calculate H(jw)| along the unity circle and |H(z)|, each clipped # between bottom and top H_UC = H_mag(bb, aa, self.xy_UC, top, H_min=bottom, log=self.chkLog.isChecked()) Hmag = H_mag(bb, aa, self.z, top, H_min=bottom, log=self.chkLog.isChecked()) #=============================================================== ## plot Unit Circle (UC) #=============================================================== if self.chkUC.isChecked(): # Plot unit circle and marker at (1,0): self.ax3d.plot(self.xy_UC.real, self.xy_UC.imag, ones(len(self.xy_UC)) * bottom, lw=2, color='k') self.ax3d.plot([0.97, 1.03], [0, 0], [bottom, bottom], lw=2, color='k') #=============================================================== ## plot ||H(f)| along unit circle as 3D-lineplot #=============================================================== if self.chkHf.isChecked(): self.ax3d.plot(self.xy_UC.real, self.xy_UC.imag, H_UC, alpha = 0.5) # draw once more as dashed white line to improve visibility self.ax3d.plot(self.xy_UC.real, self.xy_UC.imag, H_UC, 'w--') if stride < 10: # plot thin vertical line every stride points on the UC for k in range(len(self.xy_UC[::stride])): self.ax3d.plot([self.xy_UC.real[::stride][k], self.xy_UC.real[::stride][k]], [self.xy_UC.imag[::stride][k], self.xy_UC.imag[::stride][k]], [np.ones(len(self.xy_UC[::stride]))[k]*bottom, H_UC[::stride][k]], linewidth=1, color=(0.5, 0.5, 0.5)) #=============================================================== ## plot Poles and Zeros #=============================================================== if self.chkPZ.isChecked(): PN_SIZE = 8 # size of P/N symbols # Plot zero markers at |H(z_i)| = zlevel with "stems": self.ax3d.plot(zz.real, zz.imag, ones(len(zz)) * zlevel, 'o', markersize=PN_SIZE, markeredgecolor='blue', markeredgewidth=2.0, markerfacecolor='none') for k in range(len(zz)): # plot zero "stems" self.ax3d.plot([zz[k].real, zz[k].real], [zz[k].imag, zz[k].imag], [bottom, zlevel], linewidth=1, color='b') # Plot the poles at |H(z_p)| = plevel with "stems": self.ax3d.plot(np.real(pp), np.imag(pp), plevel_top, 'x', markersize=PN_SIZE, markeredgewidth=2.0, markeredgecolor='red') for k in range(len(pp)): # plot pole "stems" self.ax3d.plot([pp[k].real, pp[k].real], [pp[k].imag, pp[k].imag], [plevel_btm, plevel_top], linewidth=1, color='r') #=============================================================== ## 3D-Plots of |H(z)| clipped between |H(z)| = top #=============================================================== m_cb = cm.ScalarMappable(cmap=cmap) # normalized proxy object that is mappable m_cb.set_array(Hmag) # for colorbar #--------------------------------------------------------------- ## 3D-mesh plot #--------------------------------------------------------------- if self.cmbMode3D.currentText() == 'Mesh': # fig_mlab = mlab.figure(fgcolor=(0., 0., 0.), bgcolor=(1, 1, 1)) # self.ax3d.set_zlim(0,2) self.ax3d.plot_wireframe(self.x, self.y, Hmag, rstride=5, cstride=stride, linewidth=1, color='gray') #--------------------------------------------------------------- ## 3D-surface plot #--------------------------------------------------------------- # http://stackoverflow.com/questions/28232879/phong-shading-for-shiny-python-3d-surface-plots elif self.cmbMode3D.currentText() == 'Surf': if MLAB: ## Mayavi surf = mlab.surf(self.x, self.y, H_mag, colormap='RdYlBu', warp_scale='auto') # Change the visualization parameters. surf.actor.property.interpolation = 'phong' surf.actor.property.specular = 0.1 surf.actor.property.specular_power = 5 # s = mlab.contour_surf(self.x, self.y, Hmag, contour_z=0) mlab.show() else: if self.chkLighting.isChecked(): ls = LightSource(azdeg=0, altdeg=65) # Create light source object rgb = ls.shade(Hmag, cmap=cmap) # Shade data, creating an rgb array cmap_surf = None else: rgb = None cmap_surf = cmap # s = self.ax3d.plot_surface(self.x, self.y, Hmag, # alpha=OPT_3D_ALPHA, rstride=1, cstride=1, cmap=cmap, # linewidth=0, antialiased=False, shade=True, facecolors = rgb) # s.set_edgecolor('gray') s = self.ax3d.plot_surface(self.x, self.y, Hmag, alpha=alpha, rstride=1, cstride=1, linewidth=0, antialiased=False, facecolors=rgb, cmap=cmap_surf, shade=True) s.set_edgecolor(None) #--------------------------------------------------------------- ## 3D-Contour plot #--------------------------------------------------------------- elif self.cmbMode3D.currentText() == 'Contour': s = self.ax3d.contourf3D(self.x, self.y, Hmag, NL, alpha=alpha, cmap=cmap) #--------------------------------------------------------------- ## 2D-Contour plot # TODO: 2D contour plots do not plot correctly together with 3D plots in # current matplotlib 1.4.3 -> disable them for now # TODO: zdir = x / y delivers unexpected results -> rather plot max(H) # along the other axis? # TODO: colormap is created depending on the zdir = 'z' contour plot # -> set limits of (all) other plots manually? if self.chkContour2D.isChecked(): # self.ax3d.contourf(x, y, Hmag, 20, zdir='x', offset=xmin, # cmap=cmap, alpha = alpha)#, vmin = bottom)#, vmax = top, vmin = bottom) # self.ax3d.contourf(x, y, Hmag, 20, zdir='y', offset=ymax, # cmap=cmap, alpha = alpha)#, vmin = bottom)#, vmax = top, vmin = bottom) s = self.ax3d.contourf(self.x, self.y, Hmag, NL, zdir='z', offset=bottom - (top - bottom) * 0.05, cmap=cmap, alpha=alpha) # plot colorbar for suitable plot modes if self.chkColBar.isChecked() and (self.chkContour2D.isChecked() or str(self.cmbMode3D.currentText()) in {'Contour', 'Surf'}): self.colb = self.mplwidget.fig.colorbar(m_cb, ax=self.ax3d, shrink=0.8, aspect=20, pad=0.02, fraction=0.08) #---------------------------------------------------------------------- ## Set view limits and labels #---------------------------------------------------------------------- if not self.mplwidget.mplToolbar.a_lk.isChecked(): self.ax3d.set_xlim3d(self.xmin, self.xmax) self.ax3d.set_ylim3d(self.ymin, self.ymax) self.ax3d.set_zlim3d(bottom, top) else: self._restore_axes() self.ax3d.set_xlabel('Re')#(fb.fil[0]['plt_fLabel']) self.ax3d.set_ylabel('Im') #(r'$ \tau_g(\mathrm{e}^{\mathrm{j} \Omega}) / T_S \; \rightarrow $') # self.ax3d.set_zlabel(r'$|H(z)|\; \rightarrow $') self.ax3d.set_title(r'3D-Plot of $|H(\mathrm{e}^{\mathrm{j} \Omega})|$ and $|H(z)|$') self.redraw()
data = values[k] - obs_values cs = ax.imshow(data, cmap=variable.cmap, alpha=alpha, norm=variable.norm, rasterized=rasterized, origin='lower') else: # otherwise just plot data data = values[k] if shaded: from matplotlib.colors import LightSource # create light source object. lightsource = LightSource(azdeg=315, altdeg=30, hsv_min_val=.1, hsv_max_val=.9, hsv_min_sat=.85, hsv_max_sat=.15) # convert data to rgba array including shading from light source. # (must specify color map) data = lightsource.shade(data, variable.cmap) cs = ax.imshow(data, cmap=variable.cmap, alpha=alpha, norm=variable.norm, rasterized=rasterized, origin='lower') else: cs = ax.imshow(data, cmap=variable.cmap, alpha=alpha, norm=variable.norm, rasterized=rasterized, origin='lower') plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) if inner_titles: for ax in range(0, nt): t = ppt.add_inner_title(fig.axes[ax], inner_titles[ax], loc=2) t.patch.set_ec("none") if singlerow:
from mpl_toolkits.mplot3d import Axes3D from matplotlib import cbook from matplotlib import cm from matplotlib.colors import LightSource import matplotlib.pyplot as plt import numpy as np filename = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False) with np.load(filename) as dem: z = dem['elevation'] nrows, ncols = z.shape x = np.linspace(dem['xmin'], dem['xmax'], ncols) y = np.linspace(dem['ymin'], dem['ymax'], nrows) x, y = np.meshgrid(x, y) region = np.s_[5:50, 5:50] x, y, z = x[region], y[region], z[region] fig, ax = plt.subplots(subplot_kw=dict(projection='3d'), figsize=(1.62, 1.38)) ls = LightSource(270, 45) # To use a custom hillshading mode, override the built-in shading and pass # in the rgb colors of the shaded surface calculated from "shade". rgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft') surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False, shade=False) ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) fig.savefig("surface3d_frontpage.png")
def plot_elevation_map(self, ax=None, shaded=True, cmap=None, add_loc=None, colorbar=True, blend_mode='overlay', grid=True, gridcolor='w', altitude_range=[-10,600], contour_lines=None, latdelta=None, londelta=None, homed=None, figsize=None, addrivers=False, add_geoline=None): import os if homed is None: homed = os.path.expanduser('~') ' get elevation model ' if self.source is not None: fname = self.source dtmfile = homed + '/' + fname self.file_name = dtmfile if self.dtm is None: self.get_dem_matfile() else: fname = 'merged_dem_38-39_123-124_extended.tif' dtmfile = homed + '/Github/RadarQC/' + fname self.file_name = dtmfile if self.dtm is None: self.get_elevation() if ax is None: if figsize is None: fig,ax = plt.subplots(figsize=(10,10)) else: fig,ax = plt.subplots(figsize=figsize) ' make map axis ' m = Basemap(projection='merc', llcrnrlat=self.latn, urcrnrlat=self.latx, llcrnrlon=self.lonn, urcrnrlon=self.lonx, resolution='h', ax=ax) vmin, vmax = altitude_range if shaded: ' make hill shaded image ' ls = LightSource(azdeg=15, altdeg=60) rgb = ls.shade(self.dtm, cmap=getattr(plt.cm,cmap), vmin=vmin, vmax=vmax, blend_mode='soft', fraction=0.7) m.imshow(rgb) else: m.imshow(self.dtm, cmap=cmap, vmin=vmin, vmax=vmax) ' add parallels and meridians ' parallels = np.arange(-90, 90, latdelta) meridians = np.arange(-180, 180, londelta) lw = 0 if grid: lw = 1. parallels = m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10, labelstyle='+/-', fmt='%2.1f',linewidth=lw, color=gridcolor) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10, labelstyle='+/-', fmt='%2.1f', linewidth=lw, color=gridcolor) for p in parallels: try: parallels[p][1][0].set_rotation(90) except: pass ' add locations ' if add_loc: fsize = 15 psize = 50 ec = (1.0,0,0,1) fc = (0.5,0,0,1) if isinstance(add_loc,dict): for loc, coord in locations.iteritems(): x, y = m(*coord[::-1]) m.scatter(x, y, psize, color='r') ax.text(x, y, loc, ha='right', va='bottom', color='r',fontsize=fsize,weight='bold') elif isinstance(add_loc,list): for loc in add_loc: coord = locations[loc] x, y = m(*coord[::-1]) m.scatter(x, y, psize, facecolor=fc,edgecolor=ec) ax.text(x, y, loc, ha='right', va='bottom', color='r',fontsize=fsize,weight='bold') ' add section line ' if add_geoline: if isinstance(add_geoline,dict): geolines = list(add_geoline) elif isinstance(add_geoline,list): geolines = add_geoline for line in geolines: x, y = get_line_ini_end(line) self.line_x = x self.line_y = y x, y = m(*[x, y]) if 'color' in line: color = line['color'] else: color='k' m.plot(x, y, color=color, linewidth=2) if 'ndiv' in line: ndiv = line['ndiv'] xp = np.linspace(x[0], x[1], ndiv) yp = np.linspace(y[0], y[1], ndiv) m.plot(xp, yp, marker='s', markersize=5, color=color) if 'label' in line: if 'center' in line: x,y = m(*line['center'][::-1]) ax.text(x,y,line['label']+r'$^\circ$', color=color, weight='bold', fontsize=15, rotation=90-line['az']) ' add rivers ' if addrivers: rivers = get_rivers(mmap=m) ax.add_collection(rivers) ' add colorbar ' if colorbar: im = m.imshow(self.dtm, cmap=cmap, vmin=vmin, vmax=vmax) im.remove() add_colorbar(ax,im,label='Meters') ' add contour line(s) ' if contour_lines is not None: nlats, nlons = self.dtm.shape lons, lats = np.meshgrid( np.linspace(self.lonn, self.lonx, nlons), np.linspace(self.latn, self.latx, nlats)) x, y = m(lons, lats) m.contour(x, y, self.dtm, contour_lines, colors='k') ' add coastline' m.drawcoastlines(color='w')
def _shade_colors_lightsource(self, data, cmap, lightsource): if lightsource is None: lightsource = LightSource(azdeg=135, altdeg=55) return lightsource.shade(data, cmap)
Z = superposition(X,Y,t,trou,theta) # Calcul à part pour la section de coupe. x_trou = np.arange(-trou/2,trou/2,dx) Zcut = (sum([point_source(x,ycut,t,xt,0,theta) for xt in x_trou])/len(x_trou))**2 # Ouverture de la figure et définition des sous-figures plt.figure(figsize=(8,6.9)) ax1= plt.subplot2grid((3,2),(0,0),colspan=2,rowspan=2) plt.title('Diffraction par une ouverture plane, $t={}$'.format(round(t,1))) plt.ylabel('$y$') plt.xlim((xmin,xmax)) plt.ylim((ymin,ymax)) if shading: ls = LightSource(azdeg=20,altdeg=65) # create light source object. rgb = ls.shade(Z,plt.cm.copper) # shade data, creating an rgb array. plt.imshow(rgb,extent=extent) else: plt.imshow(Z,interpolation='bilinear',extent=extent,cmap='jet',vmin=vmin,vmax=vmax) # On rajoute deux barres pour les murs plt.annotate('',xytext=(-ext,0),xy=(-trou/2,0), arrowprops=dict(facecolor='black',width=2,frac=0,headwidth=2)) plt.annotate('',xytext=( ext,0),xy=( trou/2,0), arrowprops=dict(facecolor='black',width=2,headwidth=2,frac=0)) plt.plot([-ext,ext],[ycut,ycut],'--k') # et l'endroit de la section. # La figure du bas ax2= plt.subplot2grid((3,2),(2,0),colspan=2,sharex=ax1) plt.xlabel('$x$')
y = (ny -np.arange(ny)) * dy X, Y = np.meshgrid(x, y) Z = data.reshape(ny, nx) import matplotlib.pyplot as plt import matplotlib fig = plt.figure(0) plt.clf() ax = fig. add_subplot(1,1,1) ax.set_aspect("equal") plt.contourf(X, Y, Z, 100, cmap = matplotlib.cm.terrain) cbar=plt.colorbar() cbar.set_label("Altitude, $z$ [m]") plt.contour(X, Y, Z, 20, colors= "k") plt.grid() plt.xlabel("Position, $x$ [m]") plt.ylabel("Position, $y$ [m]") from matplotlib.colors import LightSource ls= LightSource(aedeg=0, altdeg=65) rgb = ls.shade(Z, plt.cm.terrain) plt.figure(1) plt.imshow(rgb, extent=[0,x.max(),0,y.max()]) cbar = plt.colorbar(grad) cbar.set_label("Altitude, $z$ [m]") plt.xlabel("Position, $x$ [m]") plt.ylabel("Position, $y$ [m]") plt.show()
topoin,lons = shiftgrid(180.,topoin,lons,start=False) # setup of basemap ('lcc' = lambert conformal conic). # use major and minor sphere radii from WGS84 ellipsoid. m = Basemap(llcrnrlon=-145.5,llcrnrlat=1.,urcrnrlon=-2.566,urcrnrlat=46.352,\ rsphere=(6378137.00,6356752.3142),\ resolution='l',area_thresh=1000.,projection='lcc',\ lat_1=50.,lon_0=-107.) # transform to nx x ny regularly spaced native projection grid nx = int((m.xmax-m.xmin)/40000.)+1; ny = int((m.ymax-m.ymin)/40000.)+1 topodat,x,y = m.transform_scalar(topoin,lons,lats,nx,ny,returnxy=True) # create light source object. ls = LightSource(azdeg = 90, altdeg = 20) # convert data to rgb array including shading from light source. # (must specify color map) rgb = ls.shade(topodat, plt.cm.jet) # create the figure. fig=plt.figure(figsize=(8,8)) # plot image over map with imshow (pass rgb values # that include light shading). im = m.imshow(rgb) # draw coastlines and political boundaries. m.drawcoastlines() m.drawcountries() # draw parallels and meridians. # label on left, right and bottom of map. parallels = np.arange(0.,80,20.) m.drawparallels(parallels,labels=[1,1,0,1]) meridians = np.arange(10.,360.,30.) m.drawmeridians(meridians,labels=[1,1,0,1]) # set title.
# label on left and bottom of map. parallels = np.arange(0.,80,20.) m.drawparallels(parallels,labels=[1,0,0,1]) meridians = np.arange(10.,360.,30.) m.drawmeridians(meridians,labels=[1,0,0,1]) # add colorbar #cb = m.colorbar(im,"right", size="5%", pad='2%') ax.set_title('ETOPO5 Topography - Lambert Conformal Conic') fig.savefig('etopo5.png') # make a shaded relief plot. # create new figure, axes instance. fig = pp.figure(figsize=(10,10)) ax = fig.add_axes([0.1,0.1,0.8,0.8]) # attach new axes image to existing Basemap instance. m.ax = ax # create light source object. from matplotlib.colors import LightSource ls = LightSource(azdeg = 90, altdeg = 20) # convert data to rgb array including shading from light source. # (must specify color map) rgb = ls.shade(topodat, cm.GMT_haxby) im = m.imshow(rgb) # draw coastlines and political boundaries. m.drawcoastlines() m.drawcountries() m.drawstates() ax.set_title('Shaded ETOPO5 Topography - Lambert Conformal Conic') fig.savefig('etopo5_shaded.png')
def plot_shaded_map(ax=None, cmap='gist_earth',saveto=None): if ax is None: scale = 0.7 fig,ax = plt.subplots(figsize=(10*scale,10*scale)) # dtmfile = '/home/raul/Github/RadarQC/merged_dem_38-39_123-124_extended.tif' # dtmfile = '/home/raul/Dropbox/NOCAL_DEM/merged_dem_38-39_123-124_extended.tif' dtmfile = '/Users/raulvalenzuela/Dropbox/NOCAL_DEM/merged_dem_38-39_123-124_extended.tif' domain = [-123.4, -122.8, 38.8, 38.1, 8] elev = elevation(file_name=dtmfile, domain=domain) elev.get_elevation() elev_lims = [0,700] ls = LightSource(azdeg=15, altdeg=60) rgb = ls.shade(elev.dtm, cmap=getattr(plt.cm,cmap), vmin=elev_lims[0], vmax=elev_lims[1], blend_mode='soft', fraction=0.7) ax.imshow(rgb) " interpolate latlon to cartesian coords" nrows, ncols = elev.dtm.shape flat = interp1d(np.linspace(domain[3],domain[2],nrows), range(nrows)) flon = interp1d(np.linspace(domain[0], domain[1], ncols), range(ncols)) lat, lon = locations['FRS'] ax.scatter(flon(lon), flat(lat), color='r',s=50) lat, lon = locations['BBY'] ax.scatter(flon(lon), flat(lat), color='r',s=50) lat, lon = locations['CZD'] ax.scatter(flon(lon), flat(lat), color='r',s=50) 'Use a proxy artist for the colorbar' im = ax.imshow(elev.dtm, cmap=cmap, vmin=elev_lims[0], vmax=elev_lims[1], origin='lower', ) im.remove() add_colorbar(ax,im,label='Meters') ax.set_xticklabels('') ax.set_yticklabels('') plt.tight_layout() if saveto is not None: fname = 'shaded_terrain.png' plt.savefig(saveto + fname, dpi=300, format='png', papertype='letter', bbox_inches='tight')
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LightSource # example showing how to make shaded relief plots # like mathematica # (http://reference.wolfram.com/mathematica/ref/ReliefPlot.html ) # or Generic Mapping Tools # (http://gmt.soest.hawaii.edu/gmt/doc/gmt/html/GMT_Docs/node145.html) # test data X,Y=np.mgrid[-5:5:0.05,-5:5:0.05] Z=np.sqrt(X**2+Y**2)+np.sin(X**2+Y**2) # creat light source object. ls = LightSource(azdeg=0,altdeg=65) # shade data, creating an rgb array. rgb = ls.shade(Z,plt.cm.copper) # plot un-shaded and shaded images. plt.figure(figsize=(12,5)) plt.subplot(121) plt.imshow(Z,cmap=plt.cm.copper) plt.title('imshow') plt.xticks([]); plt.yticks([]) plt.subplot(122) plt.imshow(rgb) plt.title('imshow with shading') plt.xticks([]); plt.yticks([]) plt.show()
import ds dem = ds.diamondSquare(100, 100, 100, .8) ls = LightSource(azdeg=315, altdeg=45) # extrac cellsize from raster cellsize = 1 # extract pixel size from raster # set the wind direction and the maximum search distance in_wind = -90 dmax = 100 #m # execute the algorithm Sx_max = winstral.winstralSX(dem, cellsize, dmax, in_wind) # Plot the results plt.figure() plt.subplot(121) cmap = plt.cm.gist_earth plt.imshow(ls.shade(dem,cmap=plt.cm.terrain, vert_exag=.1, blend_mode='soft')) plt.title('Dem sample') plt.subplot(122) plt.imshow(Sx_max) plt.colorbar() plt.title('Sx_max, Dmax='+str(dmax)) plt.show()
else: booti_av = resample(zz_av_comp) booti_var = resample(zz_var_comp) zz_av_comp_boots.append(booti_av) zz_var_comp_boots.append(booti_var) zz_av_comp_boots = np.array(zz_av_comp_boots) zz_var_comp_boots = np.array(zz_var_comp_boots) zz_av_unc = np.apply_along_axis(np.var,0,zz_av_comp_boots) zz_var_unc = np.apply_along_axis(np.var,0,zz_var_comp_boots) # Plotting (see http://matplotlib.org/examples/mplot3d/custom_shaded_3d_surface.html): fg, ax = plt.subplots(subplot_kw=dict(projection='3d')) ls = LightSource(270, 45) rgb = ls.shade(zz_avcheck, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft') #rgbm = ls.shade(zz_avm, cmap=cm.jet, vert_exag=0.1, blend_mode='soft') #heatmap = ax.pcolor(zz_av, cmap=rgb) #plt.colorbar(mappable=heatmap) # put the major ticks at the middle of each cell surf = ax.plot_surface(xxm, yym, zz_avcheck, rstride=1, cstride=1, facecolors=rgb, linewidth=0, antialiased=False, shade=False) #surf1 = ax.plot_surface(xxm, yym, zz_avm, rstride=1, cstride=1, facecolors=rgbm, # linewidth=0, antialiased=False, shade=False) ax.set_xlabel('Bonded force constant - (kcal/mol/A^2)') ax.set_ylabel('Equilibrium bond length - (A)') ax.set_zlabel('Average of bond length distribution - (A)') #ax.plot3D(x_av, y_av, z_av, "o",label="Simulation data") ax.plot3D(x_avm,y_avm,z_avm,"o",label="MBAR data") #ax.set_xlim([x_avm.min(),x_avm.max()]) #ax.set_ylim([y_avm.min(),y_avm.max()]) #ax.set_zlim([z_avm.min(),z_avm.max()])
# Shade from the northwest, with the sun 45 degrees from horizontal ls = LightSource(azdeg=315, altdeg=45) cmap = plt.cm.gist_earth fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(8, 9)) plt.setp(axes.flat, xticks=[], yticks=[]) # Vary vertical exaggeration and blend mode and plot all combinations for col, ve in zip(axes.T, [0.1, 1, 10]): # Show the hillshade intensity image in the first row col[0].imshow(ls.hillshade(z, vert_exag=ve, dx=dx, dy=dy), cmap='gray') # Place hillshaded plots with different blend modes in the rest of the rows for ax, mode in zip(col[1:], ['hsv', 'overlay', 'soft']): rgb = ls.shade(z, cmap=cmap, blend_mode=mode, vert_exag=ve, dx=dx, dy=dy) ax.imshow(rgb) # Label rows and columns for ax, ve in zip(axes[0], [0.1, 1, 10]): ax.set_title('{}'.format(ve), size=18) for ax, mode in zip(axes[:, 0], ['Hillshade', 'hsv', 'overlay', 'soft']): ax.set_ylabel(mode, size=18) # Group labels... axes[0, 1].annotate('Vertical Exaggeration', (0.5, 1), xytext=(0, 30), textcoords='offset points', xycoords='axes fraction', ha='center', va='bottom', size=20) axes[2, 0].annotate('Blend Mode', (0, 0.5), xytext=(-30, 0), textcoords='offset points', xycoords='axes fraction', ha='right', va='center', size=20, rotation=90)
def animate_interactive(data, t = [], dimOrder = (0,1,2), fps = 10.0, title = '', xlabel = 'x', ylabel = 'y', fontsize = 24, cBar = 0, sloppy = True, rangeMin = [], rangeMax = [], extent = [-1,1,-1,1], shade = False, azdeg = 0, altdeg = 65, arrowsX = np.array(0), arrowsY = np.array(0), arrowsRes = 10, arrowsPivot = 'mid', arrowsWidth = 0.002, arrowsScale = 5, arrowsColor = 'black', plotArrowsGrid = False, movieFile = '', bitrate = 1800, keepImages = False, figsize = (8, 7), dpi = None, **kwimshow): """ Assemble a 2D animation from a 3D array. call signature:: animate_interactive(data, t = [], dimOrder = (0,1,2), fps = 10.0, title = '', xlabel = 'x', ylabel = 'y', fontsize = 24, cBar = 0, sloppy = True, rangeMin = [], rangeMax = [], extent = [-1,1,-1,1], shade = False, azdeg = 0, altdeg = 65, arrowsX = np.array(0), arrowsY = np.array(0), arrowsRes = 10, arrowsPivot = 'mid', arrowsWidth = 0.002, arrowsScale = 5, arrowsColor = 'black', plotArrowsGrid = False, movieFile = '', bitrate = 1800, keepImages = False, figsize = (8, 7), dpi = None, **kwimshow) Assemble a 2D animation from a 3D array. *data* has to be a 3D array who's time index has the same dimension as *t*. The time index of *data* as well as its x and y indices can be changed via *dimOrder*. Keyword arguments: *dimOrder*: [ (i,j,k) ] Ordering of the dimensions in the data array (t,x,y). *fps*: Frames per second of the animation. *title*: Title of the plot. *xlabel*: Label of the x-axis. *ylabel*: Label of the y-axis. *fontsize*: Font size of the title, x and y label. The size of the x- and y-ticks is 0.7*fontsize and the colorbar ticks's font size is 0.5*fontsize. *cBar*: [ 0 | 1 | 2 ] Determines how the colorbar changes: (0 - no cahnge; 1 - keep extreme values constant; 2 - change extreme values). *sloppy*: [ True | False ] If True the update of the plot lags one frame behind. This speeds up the plotting. *rangeMin*, *rangeMax*: Range of the colortable. *extent*: [ None | scalars (left, right, bottom, top) ] Data limits for the axes. The default assigns zero-based row, column indices to the *x*, *y* centers of the pixels. *shade*: [ False | True ] If True plot a shaded relief plot instead of the usual colormap. Note that with this option cmap has to be specified like cmap = plt.cm.hot instead of cmap = 'hot'. Shading cannot be used with the cBar = 0 option. *azdeg*, *altdeg*: Azimuth and altitude of the light source for the shading. *arrowsX*: Data containing the x-component of the arrows. *arrowsy*: Data containing the y-component of the arrows. *arrowsRes*: Plot every arrowRes arrow. *arrowsPivot*: [ 'tail' | 'middle' | 'tip' ] The part of the arrow that is at the grid point; the arrow rotates about this point. *arrowsWidth*: Width of the arrows. *arrowsScale*: Scaling of the arrows. *arrowsColor*: Color of the arrows. *plotArrowsGrid*: [ False | True ] If 'True' the grid where the arrows are aligned to is shown. *movieFile*: [ None | string ] The movie file where the animation should be saved to. If 'None' no movie file is written. Requires 'mencoder' to be installed. *bitrate*: Bitrate of the movie file. Set to higher value for higher quality. *keepImages*: [ False | True ] If 'True' the images for the movie creation are not deleted. *figsize*: Size of the figure in inches. *dpi*: Dots per inch of the frame. **kwimshow: Remaining arguments are identical to those of pylab.imshow. Refer to that help. """ global tStep, sliderTime, pause # plot the current frame def plotFrame(): global tStep, sliderTime if movieFile: ax.set_title(title+r'$\quad$'+r'$t={0}$'.format(t[tStep]), fontsize = fontsize) if shade == False: image.set_data(data[tStep,:,:]) else: image.set_data(rgb[tStep,:,:,:]) if (cBar == 0): pass if (cBar == 1): colorbar.set_clim(vmin=data[tStep,:,:].min(), vmax=data[tStep,:,:].max()) if (cBar == 2): colorbar.set_clim(vmin=data[tStep,:,:].min(), vmax=data[tStep,:,:].max()) colorbar.update_bruteforce(data[tStep,:,:]) if plotArrows: arrows.set_UVC(U = arrowsX[tStep,::arrowsRes,::arrowsRes], V = arrowsY[tStep,::arrowsRes,::arrowsRes]) if (sloppy == False) or (movieFile): manager.canvas.draw() # play the movie def play(threadName): global tStep, sliderTime, pause pause = False while (tStep < nT) & (pause == False): # write the image files for the movie if movieFile: plotFrame() frameName = movieFile + '%06d.png'%tStep fig.savefig(frameName, dpi = dpi) movieFiles.append(frameName) else: start = time.clock() # time slider sliderTime.set_val(t[tStep]) # wait for the next frame (fps) while (time.clock() - start < 1.0/fps): pass # do nothing tStep += 1 tStep -= 1 # call the play function as a separate thread (for GUI) def play_thread(event): global pause if pause == True: try: thread.start_new_thread(play, ("playThread", )) except: print "Error: unable to start play thread" def pausing(event): global pause pause = True def reverse(event): global tStep, sliderTime tStep -= 1 if tStep < 0: tStep = 0 # plot the frame and update the time slider sliderTime.set_val(t[tStep]) def forward(event): global tStep, sliderTime tStep += 1 if tStep > len(t)-1: tStep = len(t)-1 # plot the frame and update the time slider sliderTime.set_val(t[tStep]) pause = True plotArrows = False # check if the data has the right dimensions if (len(data.shape) != 3 and len(data.shape) != 4): print 'error: data dimensions are invalid: {0} instead of 3'.format(len(data.shape)) return -1 # transpose the data according to dimOrder unOrdered = data data = np.transpose(unOrdered, dimOrder) unOrdered = [] # check if arrows should be plotted if len(arrowsX.shape) == 3: # transpose the data according to dimOrder unOrdered = arrowsX arrowsX = np.transpose(unOrdered, dimOrder) unOrdered = [] if len(arrowsY.shape) == 3: # transpose the data according to dimOrder unOrdered = arrowsY arrowsY = np.transpose(unOrdered, dimOrder) unOrdered = [] # check if the dimensions of the arrow arrays match each other if ((len(arrowsX[:,0,0]) != len(arrowsY[:,0,0])) or (len(arrowsX[0,:,0]) != len(arrowsY[0,:,0])) or (len(arrowsX[0,0,:]) != len(arrowsY[0,0,:]))): print 'error: dimensions of arrowX do not match with dimensions of arrowY' return -1 else: plotArrows = True # check if time array has the right length nT = len(t) if (nT != len(data[:,0,0])): print 'error: length of time array doesn\'t match length of data array' return -1 if plotArrows: if (nT != len(arrowX[:,0,0]) or nT != len(arrowX[:,0,0])): print 'error: length of time array doesn\'t match length of arrows array' return -1 # check if fps is positive if (fps < 0.0): print 'error: fps is not positive, fps = {0}'.format(fps) return -1 # determine the size of the array nX = len(data[0,:,0]) nY = len(data[0,0,:]) # determine the minimum and maximum values of the data set if not(rangeMin): rangeMin = np.min(data) if not(rangeMax): rangeMax = np.max(data) # setup the plot if movieFile: width = figsize[0] height = figsize[1] plt.rc("figure.subplot", bottom=0.15) plt.rc("figure.subplot", top=0.95) plt.rc("figure.subplot", right=0.95) plt.rc("figure.subplot", left=0.15) fig = plt.figure(figsize = figsize) ax = plt.axes([0.1, 0.1, .90, .85]) else: width = figsize[0] height = figsize[1] plt.rc("figure.subplot", bottom=0.05) plt.rc("figure.subplot", top=0.95) plt.rc("figure.subplot", right=0.95) plt.rc("figure.subplot", left=0.15) fig = plt.figure(figsize = figsize) ax = plt.axes([0.1, 0.25, .85, .70]) ax.set_title(title, fontsize = fontsize) ax.set_xlabel(xlabel, fontsize = fontsize) ax.set_ylabel(ylabel, fontsize = fontsize) plt.xticks(fontsize = 0.7*fontsize) plt.yticks(fontsize = 0.7*fontsize) if shade: plane = np.zeros((nX,nY,3)) else: plane = np.zeros((nX,nY)) # apply shading if True if shade: ls = LightSource(azdeg = azdeg, altdeg = altdeg) rgb = [] # shading can be only used with cBar = 1 or cBar = 2 at the moment if cBar == 0: cBar = 1 # check if colormap is set, if not set it to 'copper' if kwimshow.has_key('cmap') == False: kwimshow['cmap'] = plt.cm.copper for i in range(len(data[:,0,0])): tmp = ls.shade(data[i,:,:], kwimshow['cmap']) rgb.append(tmp.tolist()) rgb = np.array(rgb) tmp = [] # calibrate the displayed colors for the data range image = ax.imshow(plane, vmin=rangeMin, vmax=rangeMax, origin='lower', extent = extent, **kwimshow) colorbar = fig.colorbar(image) # change the font size of the colorbar's ytickslabels cbytick_obj = plt.getp(colorbar.ax.axes, 'yticklabels') plt.setp(cbytick_obj, fontsize = 0.5*fontsize) # plot the arrows # TODO: add some more options if plotArrows: # prepare the mash grid where the arrows will be drawn arrowGridX, arrowGridY = np.meshgrid(np.arange(extent[0], extent[1], float(extent[1]-extent[0])*arrowsRes/len(data[0,:,0])), np.arange(extent[2], extent[3], float(extent[3]-extent[2])*arrowsRes/len(data[0,0,:]))) arrows = ax.quiver(arrowGridX, arrowGridY, arrowsX[0,::arrowsRes,::arrowsRes], arrowsY[0,::arrowsRes,::arrowsRes], units = 'width', pivot = arrowsPivot, width = arrowsWidth, scale = arrowsScale, color = arrowsColor) # plot the grid for the arrows if plotArrowsGrid == True: ax.plot(arrowGridX, arrowGridY, 'k.') # for real-time image display if (sloppy == False) or (movieFile): manager = plt.get_current_fig_manager() manager.show() tStep = 0 if movieFile: movieFiles = [] # start the animation play('noThread') # write the movie file mencodeCommand = "mencoder 'mf://"+movieFile+"*.png' -mf type=png:fps="+np.str(fps)+" -ovc lavc -lavcopts vcodec=mpeg4:vhq:vbitrate="+np.str(bitrate)+" -ffourcc MP4S -oac copy -o "+movieFile+".mpg" os.system(mencodeCommand) # clean up the image files if (keepImages == False): print 'cleaning up files' for fname in movieFiles: os.remove(fname) else: # set up the gui plt.ion() axPlay = plt.axes([0.1, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonPlay = plt.Button(axPlay, 'play', color='lightgoldenrodyellow', hovercolor='0.975') buttonPlay.on_clicked(play_thread) axPause = plt.axes([0.3, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonPause = plt.Button(axPause, 'pause', color='lightgoldenrodyellow', hovercolor='0.975') buttonPause.on_clicked(pausing) axReverse = plt.axes([0.5, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonReverse = plt.Button(axReverse, 'reverse', color='lightgoldenrodyellow', hovercolor='0.975') buttonReverse.on_clicked(reverse) axForward = plt.axes([0.7, 0.05, 0.15, 0.05], axisbg='lightgoldenrodyellow') buttonForward = plt.Button(axForward, 'forward', color='lightgoldenrodyellow', hovercolor='0.975') buttonForward.on_clicked(forward) # create the time slider fig.subplots_adjust(bottom=0.2) sliderTimeAxes = plt.axes([0.2, 0.12, 0.6, 0.03], axisbg='lightgoldenrodyellow') sliderTime = plt.Slider(sliderTimeAxes, 'time', t[0], t[-1], valinit = 0.0) def update(val): global tStep # find the closest time step to the slider time value for i in range(len(t)): if t[i] < sliderTime.val: tStep = i if (tStep != len(t)-1): if (t[tStep+1] - sliderTime.val) < (sliderTime.val - t[tStep]): tStep += 1 plotFrame() sliderTime.on_changed(update) plt.show() print 'done'