# Order the original colormap lists by name cmaps = [] for cmap_category, cmap_list in omaps: cmaps.append((cmap_category, sorted(cmap_list))) # Add reverse colormaps to the cmaps list cmaps_with_r = [] for cmap_category, cmap_list in cmaps: # Use list() to make copy of cmap_list cmap_list_r = list(cmap_list) cmap_list_r.extend(['{}_r'.format(c) for c in cmap_list]) cmaps_with_r.append((cmap_category, cmap_list_r)) jetplus_clt = readCLT( os.path.join(str(settings.ROOT_DIR.path('static')), 'colormaps', 'jetplus.txt')) def _plot_color_bar(category, cmap): '''Make an image file for each colormap ''' gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) cb_fig = plt.figure(figsize=(2.56, 0.15)) cb_ax = cb_fig.add_axes([0., 0., 1., 1.]) if cmap == 'jetplus': cm_jetplus = colors.ListedColormap(np.array(jetplus_clt)) cb_ax.imshow(gradient, aspect='auto', cmap=cm_jetplus) elif cmap == 'jetplus_r':
def createPNG(self, fileName=None, forGeotiff=False): '''Draw processed data on a map and save it as a .png file ''' if not forGeotiff: fig = plt.figure(figsize=(18, 12)) ax = plt.axes() else: fig = plt.figure() ax = fig.add_axes((0, 0, 1, 1)) if not fileName: fileName = self.args.pngFileName e = self.getExtent() m = Basemap(llcrnrlon=e[0], llcrnrlat=e[1], urcrnrlon=e[2], urcrnrlat=e[3], projection='cyl', resolution='l', ax=ax) if not forGeotiff: m.arcgisimage(server='http://services.arcgisonline.com/ArcGIS', service='Ocean_Basemap') for depth, drift in list(self.adcpDrift.items()): m.plot(drift['lon'], drift['lat'], '-', c='black', linewidth=1) plt.text(drift['lon'][-1], drift['lat'][-1], '%i m' % depth, size='small') for platform, drift in list(self.trackDrift.items()): # Ad hoc coloring of platforms... if platform.startswith('stella'): color = 'yellow' elif platform.startswith('daphne'): color = 'orange' elif platform.startswith('makai'): color = 'magenta' else: color = 'red' m.plot(drift['lon'], drift['lat'], '-', c=color, linewidth=2) plt.text(drift['lon'][-1], drift['lat'][-1], platform, size='small') # Plot each data point with it's own color based on the activity statistics from STOQS coloredDotSize = 30 clt = readCLT( os.path.join(settings.ROOT_DIR('static'), 'colormaps', 'jetplus.txt')) cm_jetplus = matplotlib.colors.ListedColormap(np.array(clt)) for key, drift in list(self.stoqsDrift.items()): min, max = key.split(',')[2:4] ax.scatter(drift['lon'], drift['lat'], c=drift['datavalue'], s=coloredDotSize, cmap=cm_jetplus, lw=0, vmin=min, vmax=max) label = '%s from %s' % tuple(key.split(',')[:2]) plt.text(drift['lon'][-1], drift['lat'][-1], label, size='small') nowLocal = str( pytz.utc.localize(datetime.now()).astimezone( pytz.timezone('America/Los_Angeles'))).split('.')[0] plt.text(0.99, 0.01, 'Created: ' + nowLocal + ' Local', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes) if not forGeotiff: m.drawparallels(np.linspace(e[1], e[3], num=3), labels=[True, False, False, False], linewidth=0) m.drawmeridians(np.linspace(e[0], e[2], num=3), labels=[False, False, False, True], linewidth=0) try: plt.title(self.title) except AttributeError: pass fig.savefig(fileName) print('Wrote file', self.args.pngFileName) else: plt.axis('off') try: plt.text(0.5, 0.95, self.title, horizontalalignment='center', verticalalignment='top', transform=ax.transAxes) except AttributeError: pass fig.savefig(fileName, transparent=True, dpi=300, bbox_inches='tight', pad_inches=0) plt.clf() plt.close()
except AttributeError: pass import matplotlib as mpl mpl.use('Agg') # Force matplotlib to not use any Xwindows backend import cmocean import matplotlib.colors as colors import matplotlib.pyplot as plt import numpy as np from colormaps import cmaps from django.conf import settings from utils.Viz.plotting import readCLT colordots_dir = os.path.join(str(settings.ROOT_DIR.path('static')), 'images', 'colordots') jetplus_clt = readCLT(os.path.join(str(settings.ROOT_DIR.path('static')), 'colormaps', 'jetplus.txt')) def savePPM(r, g, b): ''' Write ASCII netPPM file with 0-1 values for @r, @g, @b. Files will be named with the hex values of abgr, the KML ordering of components. ''' ##print 'r, g, b = %f, %f, %f' % (r, g, b) if r < 0 or r > 1 or g < 0 or g > 1 or b < 0 or b > 1: raise Exception('Illegal color components. Values must be > 0.0 and < 1.0.') ge_color = "ff%02x%02x%02x" % ((round(b * 255), round(g * 255), round(r * 255))) im_color = "%02x%02x%02x" % ((round(r * 255), round(g * 255), round(b * 255))) file_name = os.path.join(colordots_dir, ge_color + '.png') ##print('Creating file_name = {}'.format(file_name)) if os.path.exists(file_name):
def createPNG(self, fileName=None, forGeotiff=False): '''Draw processed data on a map and save it as a .png file ''' if not forGeotiff: fig = plt.figure(figsize=(18, 12)) ax = plt.axes() else: fig = plt.figure() ax = fig.add_axes((0,0,1,1)) if not fileName: fileName = self.args.pngFileName e = self.getExtent() m = Basemap(llcrnrlon=e[0], llcrnrlat=e[1], urcrnrlon=e[2], urcrnrlat=e[3], projection='cyl', resolution='l', ax=ax) if not forGeotiff: m.arcgisimage(server='http://services.arcgisonline.com/ArcGIS', service='Ocean_Basemap') for depth, drift in list(self.adcpDrift.items()): m.plot(drift['lon'], drift['lat'], '-', c='black', linewidth=1) plt.text(drift['lon'][-1], drift['lat'][-1], '%i m' % depth, size='small') for platform, drift in list(self.trackDrift.items()): # Ad hoc coloring of platforms... if platform.startswith('stella'): color = 'yellow' elif platform.startswith('daphne'): color = 'orange' elif platform.startswith('makai'): color = 'magenta' else: color = 'red' m.plot(drift['lon'], drift['lat'], '-', c=color, linewidth=2) plt.text(drift['lon'][-1], drift['lat'][-1], platform, size='small') # Plot each data point with it's own color based on the activity statistics from STOQS coloredDotSize = 30 clt = readCLT(os.path.join(settings.ROOT_DIR('static'), 'colormaps', 'jetplus.txt')) cm_jetplus = matplotlib.colors.ListedColormap(np.array(clt)) for key, drift in list(self.stoqsDrift.items()): min, max = key.split(',')[2:4] ax.scatter(drift['lon'], drift['lat'], c=drift['datavalue'], s=coloredDotSize, cmap=cm_jetplus, lw=0, vmin=min, vmax=max) label = '%s from %s' % tuple(key.split(',')[:2]) plt.text(drift['lon'][-1], drift['lat'][-1], label, size='small') nowLocal = str(pytz.utc.localize(datetime.now()).astimezone(pytz.timezone('America/Los_Angeles'))).split('.')[0] plt.text(0.99, 0.01, 'Created: ' + nowLocal + ' Local', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes) if not forGeotiff: m.drawparallels(np.linspace(e[1],e[3],num=3), labels=[True,False,False,False], linewidth=0) m.drawmeridians(np.linspace(e[0],e[2],num=3), labels=[False,False,False,True], linewidth=0) try: plt.title(self.title) except AttributeError: pass fig.savefig(fileName) print('Wrote file', self.args.pngFileName) else: plt.axis('off') try: plt.text(0.5, 0.95, self.title, horizontalalignment='center', verticalalignment='top', transform=ax.transAxes) except AttributeError: pass fig.savefig(fileName, transparent=True, dpi=300, bbox_inches='tight', pad_inches=0) plt.clf() plt.close()