def _shiftedColorMap(self, cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Taken from https://github.com/olgabot/prettyplotlib/blob/master/prettyplotlib/colors.py which makes beautiful plots by the way Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap's dynamic range to be at zero Input ----- cmap : The matplotlib colormap to be altered start : Offset from lowest point in the colormap's range. Defaults to 0.0 (no lower ofset). Should be between 0.0 and `midpoint`. midpoint : The new center of the colormap. Defaults to 0.5 (no shift). Should be between 0.0 and 1.0. In general, this should be 1 - vmax/(vmax + abs(vmin)) For example if your data range from -15.0 to +5.0 and you want the center of the colormap at 0.0, `midpoint` should be set to 1 - 5/(5 + 15)) or 0.75 stop : Offset from highets point in the colormap's range. Defaults to 1.0 (no upper ofset). Should be between `midpoint` and 1.0. ''' from matplotlib.colors import LinearSegmentedColormap from matplotlib import cm cdict = { 'red': [], 'green': [], 'blue': [], 'alpha': [] } # regular index to compute the colors reg_index = np.linspace(start, stop, 257) # shifted index to match the data shift_index = np.hstack([ np.linspace(0.0, midpoint, 128, endpoint=False), np.linspace(midpoint, 1.0, 129, endpoint=True) ]) for ri, si in zip(reg_index, shift_index): r, g, b, a = cmap(ri) cdict['red'].append((si, r, r)) cdict['green'].append((si, g, g)) cdict['blue'].append((si, b, b)) cdict['alpha'].append((si, a, a)) newcmap = LinearSegmentedColormap(name, cdict) # add some overunders newcmap.set_bad(color='g', alpha=0.75) newcmap.set_over(color='m', alpha=0.75) newcmap.set_under(color='c', alpha=0.75) cm.register_cmap(cmap=newcmap) return newcmap
q.set_UVC(inst.velo[:, :, 1], inst.velo[:, :, 0]) print(f"Density sum: {inst.density.sum()}") im.autoscale() fig = plt.figure() # We create new colormap cmapRGB = { 'red': [(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)], 'green': [(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)], 'blue': [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)] } # We register new colormap plt.register_cmap(cmap=LinearSegmentedColormap('cmap', cmapRGB)) # plot density im = plt.imshow(inst.density, cmap="cmap", vmax=100, interpolation='bilinear') # plot vector field q = plt.quiver(inst.velo[:, :, 1], inst.velo[:, :, 0], scale=10, angles='xy') anim = animation.FuncAnimation(fig, update_im, interval=1,
} # This is the structured data file hierarchy. Replace as appropriate (do not go the Yaouen way and fully automatize ...) basefolder = '/home/silke/Documents/CurrentProjects/Rastko/Runs/' outfolder = '/home/silke/Documents/CurrentProjects/Rastko/analysis/' baseFlat = '/home/silke/Documents/CurrentProjects/Rastko/analysis/data/SilkefFlat/' outfolder = '/home/silke/Documents/CurrentProjects/Rastko/analysis/data/SilkeJ1/' #vList=['0.1','0.2','0.5','1'] #vList=['0.5'] #JList=['1'] JList = ['10', '1', '0.1', '0.01'] #vList=[0.005,0.05,0.1,0.2,0.5,1.0] vList = ['0.005', '0.01', '0.02', '0.05', '0.1', '0.2', '0.5', '1.0'] #testmap=LinearSegmentedColormap('test',cdict,N=len(vList)) testmap2 = LinearSegmentedColormap('test', cdict, N=len(JList)) plt.figure(figsize=(10, 7), linewidth=2.0) usecolumn = 4 colval = np.zeros((len(vList), )) colval0 = np.zeros((len(JList), )) dcolval = np.zeros((len(vList), )) vval = np.zeros((len(vList), )) for i in range(len(vList)): profiles = np.zeros((11, 180)) for j in range(len(JList)): print vList[i], JList[j] ax = plt.gca() outfile = outfolder + 'profilesV_v0' + vList[i] + '_j' + JList[ j] + '.dat' outfile2 = outfolder + 'axisV_v0' + vList[i] + '_j' + JList[j] + '.dat' # header='theta rho vel energy pressure alpha alpha_v'
dRAthetadR[0, :] = dRAthetadR[1, :] dRAthetadR[-1, :] = dRAthetadR[-2, :] return dRAthetadR - dArdtheta ##### PLOTTING ##################################################################################################################### # Create amber-teal colormap color_dict = { 'red': ((0.00, 0.10, 0.10), (0.33, 0.10, 0.10), (0.67, 1.00, 1.00), (1.00, 1.00, 1.00)), 'green': ((0.00, 0.10, 0.10), (0.33, 0.10, 0.10), (0.67, 0.50, 0.50), (1.00, 1.00, 1.00)), 'blue': ((0.00, 0.10, 0.10), (0.33, 0.50, 0.50), (0.67, 0.10, 0.10), (1.00, 1.00, 1.00)) } amber_teal = LinearSegmentedColormap('OrangeTeal1', color_dict) amber_teal.set_under('#191919') amber_teal.set_over('#FFFFFF') colormap = 'PiYG' # Compute Vortensity vort = computeVorticity(vrad, vtheta) # Constrain the colorbar vort_min = np.min( vort[vort > 0.].cgs.value) # Minimum (non-empty) value of sigma vort_max = np.max(vort.cgs.value) # Maximum value of sigma base = 10.**(np.ceil(np.log10(vort_max)) - 2.) cbar_ticks = np.arange(-base, 1.01 * base, 0.1 * base) # Ticks of colorbar levels = np.linspace(-base, base, 100, endpoint=True) # Levels of colorbar
def main(): fig, ax = plt.subplots(1, 1, figsize=(6, 4)) #fig = plt.figure(figsize=(15,10)) for l, (g, title) in enumerate([(g_cs, "Computer Science")]): # Vertices are ordered by prestige in the dataset adj = nx.to_numpy_matrix(g, dtype=int) # Scale adjacency matrix by a vertex's outdegree. # Edges i -> j are from row_i -> col_j groups = np.linspace(0, 100, 11) grouped_by_row = [] for i, row in enumerate(adj): in_edges = [] for rank, edges in enumerate(row[0].tolist()[0]): for j in range(int(edges)): in_edges.append(rank) grouped_row, _ = np.histogram(in_edges, groups) grouped_by_row.append(grouped_row) grouped = [np.zeros(len(groups)-1) for i in range(len(groups)-1)] for i, row in enumerate(grouped_by_row): for j in range(len(groups)-1): if i <= groups[j+1]: for k, elem in enumerate(row): grouped[j][k] += elem break #ax = fig.add_subplot(111) from matplotlib.colors import LinearSegmentedColormap, ListedColormap colors = iter(cm.rainbow(np.linspace(0, 1, 3))) #print(colors, next(colors)) r,g,b = next(colors)[:3] # Unpack RGB vals (0. to 1., not 0 to 255). cdict = {'red': ((0.0, 1.0, 1.0), (1.0, r, r)), 'green': ((0.0, 1.0, 1.0), (1.0, g, g)), 'blue': ((0.0, 1.0, 1.0), (1.0, b, b))} custom_cmap = LinearSegmentedColormap('custom_cmap', cdict) cax = ax.matshow(grouped, cmap=custom_cmap) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) labels = ['%.0f' % group for group in groups] ax.set_xticklabels(labels, fontsize=12) ax.set_yticklabels(labels, fontsize=12) if l == 0: ax.set_ylabel(r"Prestige of PhD Institution, $\pi$", fontsize=16) ax.set_xlabel(r"Prestige of Hiring Institution, $\pi$", fontsize=16) #ax.xaxis.set_label_coords(0.5, -.10) #ax.set_title(title, y=1.15, fontsize=16) plot_utils.finalize(ax) #fig.colorbar(cax) plt.tight_layout() plt.savefig("results/grouped_adjacency.eps", format='eps', dpi=1000) #bbox_inches='tight')
imgint = earth.render(theta=theta, res=res) fint = illum.render(xs=xs_int, ys=ys_int, zs=zs, res=res) fint /= np.nanmax(fint) earth.obl = obl_greens imggreens = earth.render(theta=theta, res=res) fgreens = illum.render(xs=xs_greens, ys=ys_greens, zs=zs, res=res) fgreens /= np.nanmax(fgreens) # Figure setup fig = plt.figure(figsize=(16, 5)) axes = [] cmape = LinearSegmentedColormap( "cmape", segmentdata={ "red": [[0.0, 0.0, 0.122], [1.0, 1.0, 1.0]], "green": [[0.0, 0.0, 0.467], [1.0, 1.0, 1.0]], "blue": [[0.0, 0.0, 0.706], [1.0, 1.0, 1.0]], }, N=256, ) cmapf = LinearSegmentedColormap.from_list("cmapf", ["k", "k"], 256) cmapf._init() alphas = np.linspace(1.0, 0.0, cmapf.N + 3) cmapf._lut[:, -1] = alphas img_kw = dict( origin="lower", extent=(-1, 1, -1, 1), vmin=1e-8, cmap=cmape, interpolation="none", zorder=-2,
from scipy.sparse import bsr_matrix from scipy.sparse import linalg import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap import matplotlib.animation as animation ### Define a custom cmap cdict = { 'red': ((0.0, 1.0, 1.0), (0.3, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 1.0, 1.0), (0.3, 0.0, 0.0), (0.75, 0.0, 0.0), (1.0, 0.8, 0.8)), 'blue': ((0.0, 1.0, 1.0), (0.3, 0.5, 0.5), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)) } mycmap = LinearSegmentedColormap('mycmap', cdict) ### Square lattice # Assume square MxM cell of unit length # M: number of nodes along one direction # R: radius of the pillar (relative to the cell length) # Returns: complex potential in the range [0,1] def U_Square(M, R, Uin, Uout): assert M % 2 == 0 Mhalf = round(M / 2) dr = 1. / M Rbound = (R / dr)**2 U = Uout * np.ones((M, M), dtype=np.complex128) for i in range(M):
def processing(pathData, pathScripts): """ Generates images from NetCDF files pathData: direcotry with NetCDF files pathScripts: directory with scripts and auxiliary files Output: .png image file """ # Getting information from the file name ============================================================ # Search for the GOES-16 channel in the file name INPE_Band_ID = (pathData[pathData.find("S10635") + 6:pathData.find("_")]) # print(INPE_Band_ID) # Get the band number subtracting the value by 332 Band = int(INPE_Band_ID) - 332 Band = Band - 1 # Create a GOES-16 Bands string array Wavelenghts = [ '[]', '[0.47 μm]', '[0.64 μm]', '[0.865 μm]', '[1.378 μm]', '[1.61 μm]', '[2.25 μm]', '[3.90 μm]', '[6.19 μm]', '[6.95 μm]', '[7.34 μm]', '[8.50 μm]', '[9.61 μm]', '[10.35 μm]', '[11.20 μm]', '[12.30 μm]', '[13.30 μm]' ] Band_Wavelenght = Wavelenghts[int(Band)] # Search for the Scan start in the file name Start = (pathData[pathData.find(INPE_Band_ID + "_") + 4:pathData.find(".nc")]) # Getting the date from the file name year = Start[0:4] month = Start[4:6] day = Start[6:8] date = day + "-" + month + "-" + year time = Start[8:10] + ":" + Start[ 10:12] + " UTC" # Time of the Start of the Scan # Get the unit based on the channel. If channels 1 trough 6 is Albedo. If channels 7 to 16 is BT. Unit = "Brightness Temperature [°C]" # Choose a title for the plot Title = " GOES-16 ABI CMI Band " + str( Band) + " " + Band_Wavelenght + " " + Unit + " " + date + " " + time # Insert the institution name Institution = "CEPAGRI - UNICAMP" # Required libraries ================================================================================ # Open the file using the NetCDF4 library nc = Dataset(pathData) # Choose the visualization extent (min lon, min lat, max lon, max lat) extent = [-115.98, -55.98, -25.01, 34.98] min_lon = extent[0] max_lon = extent[2] min_lat = extent[1] max_lat = extent[3] # Get the latitudes lats = nc.variables['lat'][:] # Get the longitudes lons = nc.variables['lon'][:] # print (lats) # print (lons) # latitude lower and upper index latli = np.argmin(np.abs(lats - extent[1])) latui = np.argmin(np.abs(lats - extent[3])) # longitude lower and upper index lonli = np.argmin(np.abs(lons - extent[0])) lonui = np.argmin(np.abs(lons - extent[2])) # Extract the Brightness Temperature / Reflectance values from the NetCDF data = nc.variables['Band1'][latli:latui, lonli:lonui] # Flip the y axis, divede by 100 and subtract 273.15 to convert to celcius data = (np.flipud(data) / 100) - 273.15 # Define the size of the saved picture ============================================================== DPI = 150 ax = plt.figure(figsize=(2000 / float(DPI), 2000 / float(DPI)), frameon=True, dpi=DPI) #==================================================================================================== # Plot the Data ===================================================================================== # Create the basemap reference for the Rectangular Projection bmap = Basemap(llcrnrlon=extent[0], llcrnrlat=extent[1], urcrnrlon=extent[2], urcrnrlat=extent[3], epsg=4326) # Draw the countries and Brazilian states shapefiles bmap.readshapefile(pathScripts + '/Shapefiles/BRA_adm1', 'BRA_adm1', linewidth=0.50, color='cyan') bmap.readshapefile(pathScripts + '/Shapefiles/ne_10m_admin_0_countries', 'ne_10m_admin_0_countries', linewidth=0.50, color='cyan') # Draw parallels and meridians bmap.drawparallels(np.arange(-90.0, 90.0, 5.0), linewidth=0.3, dashes=[4, 4], color='white', labels=[False, False, False, False], fmt='%g', labelstyle="+/-", xoffset=-0.80, yoffset=-1.00, size=7) bmap.drawmeridians(np.arange(0.0, 360.0, 5.0), linewidth=0.3, dashes=[4, 4], color='white', labels=[False, False, False, False], fmt='%g', labelstyle="+/-", xoffset=-0.80, yoffset=-1.00, size=7) # Converts a CPT file to be used in Python cpt = loadCPT(pathScripts + '/Colortables/IR4AVHRR6.cpt') # Makes a linear interpolation cpt_convert = LinearSegmentedColormap('cpt', cpt) # Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference) bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=-103, vmax=84) # Insert the colorbar at the bottom cb = bmap.colorbar(location='bottom', size='2%', pad='-3.5%') cb.outline.set_visible(False) # Remove the colorbar outline cb.ax.tick_params(width=0) # Remove the colorbar ticks cb.ax.xaxis.set_tick_params( pad=-14.5) # Put the colobar labels inside the colorbar cb.ax.tick_params( axis='x', colors='black', labelsize=8) # Change the color and size of the colorbar labels # Add a black rectangle in the bottom to insert the image description lon_difference = (extent[2] - extent[0]) # Max Lon - Min Lon currentAxis = plt.gca() currentAxis.add_patch( Rectangle((extent[0], extent[1]), lon_difference, lon_difference * 0.015, alpha=1, zorder=3, facecolor='black')) # Add the image description inside the black rectangle lat_difference = (extent[3] - extent[1]) # Max lat - Min lat plt.text(extent[0], extent[1] + lat_difference * 0.003, Title, horizontalalignment='left', color='white', size=10) plt.text(extent[2], extent[1] + lat_difference * 0.003, Institution, horizontalalignment='right', color='yellow', size=10) # Add logos / images to the plot logo_GNC = plt.imread(pathScripts + '/Logos/GNC_Logo.png') logo_INPE = plt.imread(pathScripts + '/Logos/INPE_Logo.png') logo_NOAA = plt.imread(pathScripts + '/Logos/NOAA_Logo.png') logo_GOES = plt.imread(pathScripts + '/Logos/GOES_Logo.png') logo_cepagri = plt.imread(pathScripts + '/Logos/Logo_CEPAGRI.png') ax.figimage(logo_GNC, 20, 70, zorder=3, alpha=1, origin='upper') ax.figimage(logo_INPE, 90, 70, zorder=3, alpha=1, origin='upper') ax.figimage(logo_NOAA, 165, 70, zorder=3, alpha=1, origin='upper') ax.figimage(logo_GOES, 228, 70, zorder=3, alpha=1, origin='upper') ax.figimage(logo_cepagri, 326, 70, zorder=3, alpha=1, origin='upper') # Save the result # print('/Scripts/GEONETCast/Output/' + path[12:18] + '/INPE_G16_CH' + str(Band) + '_' + Start + '.png') plt.savefig(pathScripts + '/Output/Band15/INPE_G16_CH' + str(Band) + '_' + Start + '.png', dpi=DPI, bbox_inches='tight', pad_inches=0)
def plot_linearmap(cdict): newcmp = LinearSegmentedColormap('testCmap', segmentdata=cdict, N=256) rgba = newcmp(np.linspace(0, 1, 256)) fig, ax = plt.subplots(figsize=(4, 3), constrained_layout=True) col = ['r', 'g', 'b'] xs = [0, 0.25, 0.5, 0.75, 1] for xx in xs: ax.axvline(xx, color='0.7', linestyle='--') for i in range(3): ax.plot(np.arange(256) / 256, rgba[:, i], color=col[i], lw=3) ax.set_xticks(xs) ax.set_xlabel('Index') ax.set_ylabel('RGB') plt.show() plot_linearmap(cdict) fig, ax = plt.subplots(figsize=(6, 1)) fig.subplots_adjust(bottom=0.5) cmap = LinearSegmentedColormap('testCmap', segmentdata=cdict, N=256) norm = mpl.colors.Normalize(vmin=0, vmax=1) cb = mpl.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, orientation='horizontal') cb.set_label('Discontinued LinearSegmentedColormap') fig.show()
def test_problem_16(self): """ Schittkowski problem #16 """ cost = Problem16_Cost() problem = roboptim.core.PyProblem(cost) problem.startingPoint = numpy.array([ -2, 1., ]) problem.argumentBounds = numpy.array([[-2., 0.5], [-float("inf"), 1.]]) g1 = Problem16_G1() problem.addConstraint(g1, [ 0., float("inf"), ]) g2 = Problem16_G2() problem.addConstraint(g2, [ 0., float("inf"), ]) # Check starting value numpy.testing.assert_almost_equal(cost(problem.startingPoint)[0], 909.) # Initialize callback callback = IterCallback(problem) # Let the test fail if the solver does not exist. try: # Create solver log_dir = "/tmp/roboptim-core-python/problem_16" solver = roboptim.core.PySolver("ipopt", problem, log_dir=log_dir) # Add callback solver.addIterationCallback(callback) print(solver) solver.solve() r = solver.minimum() print(r) # Plot results plotter = Plotter2D([-2.1, 0.6], [0, 1.1]) plotter.x_res = 100 plotter.y_res = 100 plotter.plot(cost, plot_style=PlotStyle2D.PColorMesh, vmax=10, norm=LogNorm()) # Set up a colormap: cdict = { 'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'alpha': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)) } cstr_cmap = LinearSegmentedColormap('Mask', cdict) cstr_cmap.set_under('r', alpha=0) cstr_cmap.set_over('w', alpha=0) cstr_cmap.set_bad('g', alpha=0) plotter.plot(g1, plot_style=PlotStyle2D.Contourf, linewidth=10, alpha=None, cmap=cstr_cmap, vmax=0, fontsize=20) plotter.plot(g1, plot_style=PlotStyle2D.Contour, linewidth=10, alpha=None, levels=[0], vmax=0, fontsize=20, colors="k") plotter.plot(g2, plot_style=PlotStyle2D.Contourf, linewidth=10, alpha=None, cmap=cstr_cmap, vmax=0) # Print iterations X = zip(*callback.x)[0] Y = zip(*callback.x)[1] # Show evolution plotter.add_marker(X, Y, color="white", marker=".", markersize=5) # First point plotter.add_marker(X[0], Y[0], color="white", marker="o", markersize=10, markeredgewidth=2) # Final result plotter.add_marker(X[-1], Y[-1], color="white", marker="s", markersize=10, markeredgewidth=2) # Print actual global minimum plotter.add_marker(0.5, 0.25, color="black", marker="x", markersize=14, markeredgewidth=6) plotter.add_marker(0.5, 0.25, color="white", marker="x", markersize=10, markeredgewidth=3) plotter.show() except Exception as e: print("Error: %s" % e)
intensityConv = intensity print ' ...Done.' ##### PLOTTING ##################################################################################################################### print '' print 'Plotting...' # Defining amber-teal colormap color_dict = { 'red': ((0.00, 0.10, 0.10), (0.33, 0.10, 0.10), (0.67, 1.00, 1.00), (1.00, 1.00, 1.00)), 'green': ((0.00, 0.10, 0.10), (0.33, 0.10, 0.10), (0.67, 0.50, 0.50), (1.00, 1.00, 1.00)), 'blue': ((0.00, 0.10, 0.10), (0.33, 0.50, 0.50), (0.67, 0.10, 0.10), (1.00, 1.00, 1.00)) } amber_teal = LinearSegmentedColormap('AmberTeal1', color_dict) amber_teal.set_under('#191919') amber_teal.set_over('#FFFFFF') cmap = 'hot' # Get global limits margin = 6. intMax = np.max(intensity.cgs.value) intMin = 10.**(np.ceil(np.log10(intMax)) - margin) levelsInt = np.linspace(np.floor(np.log10(intMin)), np.ceil(np.log10(intMax)), 100) # Levels of intensity colorbar cbarTicks = np.arange(np.floor(np.log10(intMin)), np.ceil(np.log10(intMax)) + 0.1, 1.) # Ticks of colorbar # Plotting fig = plt.figure()
(1.0, 0.75, 0.75)), 'blue': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 1.0, 1.0), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)), # 'alpha': ((0.0, 1.0, 1.0), # (0.4, 1.0, 1.0), # (0.5, 0.0, 0.0), # (0.6, 1.0, 1.0), # (1.0, 1.0, 1.0)) } CUSTOM_RWG = LinearSegmentedColormap('CUSTOM_RWG', dict_custom) """ Define All Functions Here """ def ensure_dir(this_dir): if this_dir[0] == "/": test_dir = "/" else: test_dir = "" all_dir = this_dir.strip().split("/") for thing in all_dir: test_dir += thing if os.path.isdir(test_dir): pass
def FORCinel_colormap(Z): #setup initial colormap assuming that negative range does not require extension cdict = {'red': ((0.0, 127/255, 127/255), (0.1387, 255/255, 255/255), (0.1597, 255/255, 255/255), (0.1807, 255/255, 255/255), (0.3193, 102/255, 102/255), (0.563, 204/255, 204/255), (0.6975, 204/255, 204/255), (0.8319, 153/255, 153/255), (0.9748, 76/255, 76/255), (1.0, 76/255, 76/255)), 'green': ((0.0, 127/255, 127/255), (0.1387, 255/255, 255/255), (0.1597, 255/255, 255/255), (0.1807, 255/255, 255/255), (0.3193, 178/255, 178/255), (0.563, 204/255, 204/255), (0.6975, 76/255, 76/255), (0.8319, 102/255, 102/255), (0.9748, 25/255, 25/255), (1.0, 25/255, 25/255)), 'blue': ((0.0, 255/255, 255/255), (0.1387, 255/255, 255/255), (0.1597, 255/255, 255/255), (0.1807, 255/255, 255/255), (0.3193, 102/255, 102/255), (0.563, 76/255, 76/255), (0.6975, 76/255, 76/255), (0.8319, 153/255, 153/255), (0.9748, 76/255, 76/255), (1.0, 76/255, 76/255))} if np.abs(np.min(Z))<=np.max(Z)*0.19: #negative extension is not required #cmap = LinearSegmentedColormap('forc_cmap', cdict) vmin = -np.max(Z)*0.19 vmax = np.max(Z) else: #negative extension is required vmin=np.min(Z) vmax=np.max(Z) anchors = np.zeros(10) anchors[1]=(-0.025*vmax-vmin)/(vmax-vmin) anchors[2]=(-0.005*vmax-vmin)/(vmax-vmin) anchors[3]=(0.025*vmax-vmin)/(vmax-vmin) anchors[4]=(0.19*vmax-vmin)/(vmax-vmin) anchors[5]=(0.48*vmax-vmin)/(vmax-vmin) anchors[6]=(0.64*vmax-vmin)/(vmax-vmin) anchors[7]=(0.80*vmax-vmin)/(vmax-vmin) anchors[8]=(0.97*vmax-vmin)/(vmax-vmin) anchors[9]=1.0 Rlst = list(cdict['red']) Glst = list(cdict['green']) Blst = list(cdict['blue']) for i in range(9): Rlst[i] = tuple((anchors[i],Rlst[i][1],Rlst[i][2])) Glst[i] = tuple((anchors[i],Glst[i][1],Glst[i][2])) Blst[i] = tuple((anchors[i],Blst[i][1],Blst[i][2])) cdict['red'] = tuple(Rlst) cdict['green'] = tuple(Glst) cdict['blue'] = tuple(Blst) cmap = LinearSegmentedColormap('forc_cmap', cdict) return cmap, vmin, vmax
def __init__(self, imageData=None, fileName=None, dpi=300, size=(5, 5), xaxis='off', yaxis='off', xlabel='', ylabel='', nxlabels=0, nylabels=0, colorbar=None, title='', interpolation='nearest', colormap=None, linlogcolormap='linear', origin='lower', contour='off', contourlabels='on', contourlabelformat='%.3f', contourlevels=10, contourlinewidth=10, xorigin=0.0, yorigin=0.0, xpixelsize=1.0, ypixelsize=1.0, xlimits=None, ylimits=None, vlimits=None, extent=None): self.figure = Figure(figsize=size) #in inches self.canvas = FigureCanvas(self.figure) self.imageData = imageData self.pixmapImage = None self.config={'xaxis':xaxis, 'yaxis':yaxis, 'title':title, 'xlabel':xlabel, 'ylabel':ylabel, 'nxlabels':nxlabels, 'nylabels':nylabels, 'colorbar':colorbar, 'colormap':colormap, 'linlogcolormap':linlogcolormap, 'interpolation':interpolation, 'origin':origin, 'contour':contour, 'contourlabels':contourlabels, 'contourlabelformat':contourlabelformat, 'contourlevels':contourlevels, 'contourlinewidth':contourlinewidth, 'xpixelsize':xpixelsize, 'ypixelsize':ypixelsize, 'xorigin':xorigin, 'yorigin':yorigin, 'zoomxmin':None, 'zoomxmax':None, 'zoomymin':None, 'zoomymax':None, 'valuemin':None, 'valuemax':None, 'xlimits':xlimits, 'ylimits':ylimits, 'vlimits':vlimits, 'extent':extent} #generate own colormaps cdict = {'red': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0))} self.__redCmap = LinearSegmentedColormap('red',cdict,256) cdict = {'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0))} self.__greenCmap = LinearSegmentedColormap('green',cdict,256) cdict = {'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0))} self.__blueCmap = LinearSegmentedColormap('blue',cdict,256) # Temperature as defined in spslut cdict = {'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.25, 1.0, 1.0), (0.75, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0))} #Do I really need as many colors? self.__temperatureCmap = LinearSegmentedColormap('temperature', cdict, 65536) #reversed gray cdict = {'red': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0))} self.__reversedGrayCmap = LinearSegmentedColormap('yerg', cdict, 256) if fileName is not None: self.saveImage(fileName)
from matplotlib import cm, _cm from matplotlib.colors import LinearSegmentedColormap def generate_cmap_flame(): clrs = [(1, 1, 1), (0, 0.3, 1), (0, 1, 1), (0, 1, 0.3), (1, 1, 0), (1, 0.5, 0), (1, 0, 0), (0.5, 0, 0)] flame = LinearSegmentedColormap.from_list('flame', clrs) #flame.set_bad(flame(0)) # set nan's and inf's to white flame.set_bad('0.75') # set nan's and inf's to light gray return flame flame = generate_cmap_flame() cubehelix = LinearSegmentedColormap('cubehelix', cm.revcmap(_cm.cubehelix(1, 0, 1, 2.5))) cubehelix.set_bad(cubehelix(0)) def cmap_powerlaw_adjust(cmap, a): ''' returns a new colormap based on the one given but adjusted via power-law: newcmap = oldcmap**a ''' if a < 0.: return cmap cdict = copy(cmap._segmentdata) def fn(x):
def write(): st.set_option('deprecation.showPyplotGlobalUse', False) dataset_len = 180 dlen = int(dataset_len / 2) X_11 = pd.Series(np.random.normal(100, 2, dlen)) X_12 = pd.Series(np.random.normal(90, 2, dlen)) X_1 = pd.concat([X_11, X_12]).reset_index(drop=True) X_21 = pd.Series(np.random.normal(10, 30, dlen)) X_22 = pd.Series(np.random.normal(7, 30, dlen)) X_2 = pd.concat([X_21, X_22]).reset_index(drop=True) X_31 = pd.Series(np.random.normal(22, 74, dlen)) X_32 = pd.Series(np.random.normal(52, 52, dlen)) X_3 = pd.concat([X_31, X_32]).reset_index(drop=True) Y_1 = pd.Series(np.random.normal(40, 3, dlen)) Y_2 = pd.Series(np.random.normal(82, 7, dlen)) Y = pd.concat([Y_1, Y_2]).reset_index(drop=True) df = pd.concat([X_1, X_2, X_3, Y], axis=1) df.columns = [ 'Advertisement Spent', 'Brand Equity Score', 'Market Share', 'Sales' ] X = df.drop(['Sales'], axis=1) #.values Y = df['Sales'] X_Train, X_Test, Y_Train, Y_Test = train_test_split(X, Y, test_size=0.30, random_state=101) regr = RandomForestRegressor(max_depth=2, random_state=0, n_estimators=100) regr.fit(X_Train, Y_Train) st.title('Business Insights') st.subheader('Sales Prediction -Financial Analysis') st.write( 'Welcome to our business dashboard, here you can analyse how' 'changing one our 3 model parameters can affect will affect the predicted sales.' ) ads = st.text_input('Advertisement Spent') brand = st.text_input('Brand Equity Score') market = st.text_input('Market Share') ads = list(map(float, ads.split())) brand = list(map(float, brand.split())) market = list(map(float, market.split())) if (ads and brand and market) and len(ads) == len(brand) == len(market): st.write("Thanks for adding input source") X_Test = np.array([ads, brand, market]) # X_Test = np.array(list(map(list, zip(*X_Test)))) X_Test = { 'Advertisement Spent': ads, 'Brand Equity Score': brand, 'Market Share': market } X_Test = pd.DataFrame(data=X_Test) else: X_Test = X_Test st.write(df.head()) st.subheader('Feature Importance') figure(num=None, figsize=(20, 22), dpi=80, facecolor='w', edgecolor='k') feat_importances = pd.Series(regr.feature_importances_, index=df.drop(['Sales'], axis=1).columns) feat_importances.nlargest(10).plot(kind='barh') plt.xticks(size=15) plt.yticks(size=15) st.pyplot() #st.write(feat_importances.nlargest(10).index[0]) pred = regr.predict(X_Test) st.subheader('Shapley (SHAP) Values') explainerRF = shap.TreeExplainer(regr) shap_values_RF_test = explainerRF.shap_values(X_Test) shap_values_RF_train = explainerRF.shap_values(X_Train) df_shap_RF_train = pd.DataFrame(shap_values_RF_train, columns=X_Train.columns.values) # if a feature has 10 or less unique values then treat it as categorical categorical_features = np.argwhere( np.array([ len(set(X_Train.values[:, x])) for x in range(X_Train.values.shape[1]) ]) <= 10).flatten() # LIME has one explainer for all models explainer = lime.lime_tabular.LimeTabularExplainer( X_Train.values, feature_names=X_Train.columns.values.tolist(), class_names=['price'], categorical_features=categorical_features, verbose=True, mode='regression') # j will be the record we explain j = 0 # initialize js for SHAP if X_Test.shape[0] >= 3: lim = 3 else: lim = X_Test.shape[0] for j in range(0, lim): shap.initjs() num = X.columns.values st.write(num[j]) shap.force_plot(explainerRF.expected_value, shap_values_RF_test[j], X_Test.iloc[[j]], matplotlib=True) # plt.gcf().set_size_inches(14, 14) st.pyplot() shp_plt = shap.dependence_plot("Advertisement Spent", shap_values_RF_train, X_Train) st.pyplot() shp_plt = shap.dependence_plot("Brand Equity Score", shap_values_RF_train, X_Train) st.pyplot() shp_plt = shap.dependence_plot("Market Share", shap_values_RF_train, X_Train) st.pyplot() # st.subheader('Local Surrogate (LIME)') # for j in range(0, lim): # num = X.columns.values # exp= explainer.explain_instance(X_Test.values[j], regr.predict, num_features=5) # exp.as_pyplot_figure() # plt.gcf().set_size_inches(11, 7) # plt.title(num[j]) # st.pyplot() st.subheader('Bayesian Belief Network') X_Test = X_Test.values X_Train = X_Train.values df2 = pd.DataFrame({ 'from': ['Advertisement \nSpent', 'Brand \nEquity \nScore', 'Market \nShare'], 'to': ['Sales', 'Sales', 'Sales'] }) carac = pd.DataFrame({ 'ID': [ 'Advertisement \nSpent', 'Brand \nEquity \nScore', 'Market \n Share', 'Sales' ], 'values': ['group1', 'group2', 'group3', 'group4'] }) G = nx.from_pandas_edgelist(df2, 'from', 'to', create_using=nx.Graph()) G.nodes() carac = carac.set_index('ID') carac = carac.reindex(G.nodes()) carac['values'] = pd.Categorical(carac['values']) cdict = { 'red': ((0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)) } colours = LinearSegmentedColormap('GYR', cdict) fixed_positions = { 'Advertisement \nSpent': (0, 0), 'Brand \nEquity \nScore': (-1, 2), 'Market \nShare': (1, 2), 'Sales': (0, 1.2) } fixed_nodes = fixed_positions.keys() pos = nx.spring_layout(G, pos=fixed_positions, fixed=fixed_nodes) a = [ int(np.mean(X_Test[:, 0])), int(np.mean(pred)), int(np.mean(X_Test[:, 1])), int(np.mean(X_Test[:, 2])) ] #st.write("Prediction Accuracy: ", regr.score(X_Test, Y_Test)) fig = plt.figure() nx.draw(G, with_labels=True, node_color=carac['values'].cat.codes, cmap=colours, pos=pos, node_size=[v * 200 for v in a], width=3) plt.annotate(str(round(np.mean(X_Test[:, 1]), 3)), xy=(200, 880), xycoords='figure pixels', fontsize=15) plt.annotate(str(round(np.mean(X_Test[:, 0]), 3)), xy=(220, 50), xycoords='figure pixels', fontsize=15) plt.annotate(str(round(np.mean(X_Test[:, 2]), 3)), xy=(880, 900), xycoords='figure pixels', fontsize=15) plt.annotate(str(round(np.mean(pred), 3)), xy=(300, 470), xycoords='figure pixels', fontsize=15) st.pyplot()
(1.0, 0.0, 0.0)], 'green': [(0.0, 0.0, 0.0), (0.25, 0.0, 0.5), (0.5, 1.0, 1.0), (0.75, 0.5, 0.0), (1.0, 0.0, 0.0)], 'blue': [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (0.7, 1.0, 1.0), (1.0, 0.25, 0.25)] } # This is the structured data file hierarchy. Replace as appropriate (do not go the Yaouen way and fully automatize ...) basefolder = '/home/silke/Documents/CurrentProjects/Rastko/nematic/data/defect_data/' #vList=['0.2','0.3','0.5','0.7','1.0','1.5','2.0','3.0','5.0','7.0','10.0'] vList = ['0.2', '0.3', '0.5', '0.7', '1.0', '1.5', '2.0'] #vList=['0.2','1.0','5.0'] #RList=['5.0','6.0','7.0','8.0','9.0','10.0','12.0','14.0','16.0','18.0','20.0','25.0','30.0','40.0'] RList = ['8.0', '16.0', '30.0'] vmap = LinearSegmentedColormap('test', cdict, N=len(vList)) Rmap = LinearSegmentedColormap('test', cdict, N=len(RList)) nsnap = 2020 nskip = 1000 #nskip=500 step = 5000 dt = 0.001 r = 0 vval = np.zeros((len(vList), )) avtot = np.zeros((len(RList), len(vList))) davtot = np.zeros((len(RList), len(vList))) defectmat = np.empty((nsnap - nskip, 4, 3)) angles = np.zeros((nsnap - nskip, 6)) avang = np.zeros((nsnap - nskip))
np.loadtxt("geometry.dat", usecols=(7, 8), delimiter='\t')) triangles = np.loadtxt("triangles.dat") try: phi = np.transpose(np.loadtxt(sys.argv[1])) except: sys.exit("Error: input file does not exist") cdict = { 'red': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)) } red_to_green = LinearSegmentedColormap('BlueRed1', cdict) fig, ax = plt.subplots() ax.scatter(coord2D[0], coord2D[1], c=(phi[0] + 1) / 2, s=30, cmap=red_to_green, vmin=0, vmax=1, edgecolor='') plt.xlim([-3.141592, 3.141592]) plt.ylim([-3.141592 / 2, 3.141592 / 2]) plt.savefig(sys.argv[2], bbox_inches='tight', dpi=200)
# Make a modified version of cdict3 with some transparency # in the middle of the range. cdict4 = cdict3.copy() cdict4['alpha'] = ( (0.0, 1.0, 1.0), # (0.25,1.0, 1.0), (0.5, 0.3, 0.3), # (0.75,1.0, 1.0), (1.0, 1.0, 1.0)) ############################################################################### # Now we will use this example to illustrate 3 ways of # handling custom colormaps. # First, the most direct and explicit: blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1) ############################################################################### # Second, create the map explicitly and register it. # Like the first method, this method works with any kind # of Colormap, not just # a LinearSegmentedColormap: blue_red2 = LinearSegmentedColormap('BlueRed2', cdict2) plt.register_cmap(cmap=blue_red2) ############################################################################### # Third, for LinearSegmentedColormap only, # leave everything to register_cmap: plt.register_cmap(name='BlueRed3', data=cdict3) # optional lut kwarg
save_YZ = 0 # 1 to save the strain in YZ plane save_XZ = 1 # 1 to save the strain in XZ plane save_XY = 1 # 1 to save the strain in XY plane comment = '_iso' + str(support_threshold) # should start with _ comment = comment + "_strainrange_" + str(strain_range) ###################################### # define a colormap cdict = { 'red': ((0.0, 1.0, 1.0), (0.11, 0.0, 0.0), (0.36, 0.0, 0.0), (0.62, 1.0, 1.0), (0.87, 1.0, 1.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 1.0, 1.0), (0.11, 0.0, 0.0), (0.36, 1.0, 1.0), (0.62, 1.0, 1.0), (0.87, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 1.0, 1.0), (0.11, 1.0, 1.0), (0.36, 1.0, 1.0), (0.62, 0.0, 0.0), (0.87, 0.0, 0.0), (1.0, 0.0, 0.0)) } my_cmap = LinearSegmentedColormap('my_colormap', cdict, 256) my_cmap.set_bad(color='0.7') def calc_coordination(mysupport, debugging=0): nbz, nby, nbx = mysupport.shape mykernel = np.ones((3, 3, 3)) mycoord = np.rint(convolve(mysupport, mykernel, mode='same')) mycoord = mycoord.astype(int) if debugging == 1: plt.figure(figsize=(18, 15)) plt.subplot(2, 2, 1) plt.imshow(mycoord[:, :, nbx // 2]) plt.colorbar()
def plot(sistemas_convectivos_nc, glm_nc, local, extent, resolution=2): if (local == 'Brasil'): degrees = 10 label_fontsize = 50 elif (local == 'Sudeste'): degrees = 5 label_fontsize = 8 else: degrees = 2 resolution = 0.8 label_fontsize = 8 g16glm = Dataset(glm_nc, 'r') nc = Dataset(sistemas_convectivos_nc) # Get the latitude and longitude image bounds geo_extent = nc.variables['geospatial_lat_lon_extent'] min_lon = float(geo_extent.geospatial_westbound_longitude) max_lon = float(geo_extent.geospatial_eastbound_longitude) min_lat = float(geo_extent.geospatial_southbound_latitude) max_lat = float(geo_extent.geospatial_northbound_latitude) # Choose the visualization extent (min lon, min lat, max lon, max lat) #extent = [-45.0, -24.5, -39.0, -20.7] # Choose the image resolution (the higher the number the faster the processing is) #resolution = 0.8 #2 # Calculate the image extent required for the reprojection H = nc.variables['goes_imager_projection'].perspective_point_height x1 = nc.variables['x_image_bounds'][0] * H x2 = nc.variables['x_image_bounds'][1] * H y1 = nc.variables['y_image_bounds'][1] * H y2 = nc.variables['y_image_bounds'][0] * H # Call the reprojection funcion grid = remap(sistemas_convectivos_nc, extent, resolution, x1, y1, x2, y2) tipos = ["todos", "event", "group", "flash"] for formato in range(4): glm_variables = [False, False, False, False] glm_variables[formato] = True #print(glm_variables) # Read the data returned by the function ============================================================== # If it is an IR channel subtract 273.15 to convert to ° Celsius data = grid.ReadAsArray() - 273.15 # Make pixels outside the footprint invisible data[data <= -180] = np.nan # Define the size of the saved picture ================================================================= DPI = 150 fig = plt.figure(figsize=(data.shape[1] / float(DPI), data.shape[0] / float(DPI)), frameon=False, dpi=DPI) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax = plt.axis('off') # Plot the Data ======================================================================================= # Create the basemap reference for the Rectangular Projection bmap = Basemap(llcrnrlon=extent[0], llcrnrlat=extent[1], urcrnrlon=extent[2], urcrnrlat=extent[3], epsg=4326) # Draw the countries and Brazilian states shapefiles bmap.readshapefile('/home/cendas/GOES16_WS_Rodrigo/GLM/src/BRA_adm1', 'BRA_adm1', linewidth=0.50, color='#000000') if (local == 'Brasil'): bmap.readshapefile( '/home/cendas/GOES16_WS_Rodrigo/GLM/src/ne_10m_coastline', 'ne_10m_coastline', linewidth=0.50, color='#000000') #ne_10m_coastline # Draw parallels and meridians if (not (local == 'Brasil')): bmap.drawparallels(np.arange(-90.0, 90.0, degrees), linewidth=0.3, dashes=[4, 4], color='white', labels=[True, False, False, True], fmt='%g', labelstyle="+/-", size=8) bmap.drawmeridians(np.arange(0.0, 360.0, degrees), linewidth=0.3, dashes=[4, 4], color='white', labels=[True, False, False, True], fmt='%g', labelstyle="+/-", size=8) else: bmap.drawparallels(np.arange(-90.0, 90.0, degrees), linewidth=0.3, dashes=[4, 4], color='white', labels=[True, False, False, True], fmt='%g', labelstyle="+/-", size=30) bmap.drawmeridians(np.arange(0.0, 360.0, degrees), linewidth=0.3, dashes=[4, 4], color='white', labels=[True, False, False, True], fmt='%g', labelstyle="+/-", size=30) #Split the dataset with temperatures above and below -20°C temp = -80 tempAbove = masked_array(data, data < temp) tempBelow = masked_array(data, data >= temp) # Converts a CPT file to be used in Python cptSquareRoot = loadCPT( '/home/cendas/GOES16_WS_Rodrigo/GLM/src/Square Root Visible Enhancement.cpt' ) # Makes a linear interpolation cpt_convert_SquareRoot = LinearSegmentedColormap('cpt', cptSquareRoot) # Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference) plot_SquareRoot = bmap.imshow(tempAbove, origin='upper', cmap=cpt_convert_SquareRoot, vmin=-80, vmax=100) # ===================== LEGENDA ========================== # Get the unit based on the channel. If channels 1 trough 6 is Albedo. If channels 7 to 16 is BT. Unit = "Cloud Top Temperature [°C]" # Choose a title for the plot Title = " Geostationary Lightning Mapper (GLM) - GOES Satellite" Latitude = "Latitude" Longitude = "Longitude" # Add a black rectangle in the bottom to insert the image description lon_difference = (extent[2] - extent[0]) # Max Lon - Min Lon # Add the image description inside the black rectangle lat_difference = (extent[3] - extent[1]) # Max lat - Min lat if (not (local == 'Brasil')): #Labels and its positions # plt.text(extent[0] + lon_difference * 0.5, extent[3] + lat_difference * 0.035, Title, horizontalalignment='center', color='black', size=9) plt.text(extent[0] + lon_difference * 0.5, extent[3] + lat_difference * 0.065, " ", horizontalalignment='center', color='black', size=10) plt.text(extent[0] + lon_difference * 0.5, extent[1] - lat_difference * 0.11, Longitude, horizontalalignment='center', color='black', size=10) plt.text(extent[0] + lon_difference * 0.5, extent[1] - lat_difference * 0.15, " ", horizontalalignment='center', color='black', size=18) plt.text(extent[0] - lon_difference * 0.15, extent[1] + lat_difference * 0.5, Latitude, verticalalignment='center', rotation="vertical", color='black', size=10) else: plt.text(extent[0] + lon_difference * 0.5, extent[3] + lat_difference * 0.035, Title, horizontalalignment='center', color='black', size=40) plt.text(extent[0] + lon_difference * 0.5, extent[3] + lat_difference * 0.065, " ", horizontalalignment='center', color='black', size=10) plt.text(extent[0] + lon_difference * 0.5, extent[1] - lat_difference * 0.11, Longitude, horizontalalignment='center', color='black', size=40) plt.text(extent[0] + lon_difference * 0.5, extent[1] - lat_difference * 0.15, " ", horizontalalignment='center', color='black', size=18) plt.text(extent[0] - lon_difference * 0.15, extent[1] + lat_difference * 0.5, Latitude, verticalalignment='center', rotation="vertical", color='black', size=40) # ======================================== if (glm_variables[0]): #Todos # Get Events, Group and flash from Glm file event_lat = g16glm.variables['event_lat'][:] event_lon = g16glm.variables['event_lon'][:] group_lat = g16glm.variables['group_lat'][:] group_lon = g16glm.variables['group_lon'][:] flash_lat = g16glm.variables['flash_lat'][:] flash_lon = g16glm.variables['flash_lon'][:] # Plot events as large blue dots event_x, event_y = bmap(event_lon, event_lat) bmap.plot(event_x, event_y, 'bo', markersize=7, label='Events') # Plot groups as medium green dots group_x, group_y = bmap(group_lon, group_lat) bmap.plot(group_x, group_y, 'go', markersize=3, label='Group') # Plot flashes as small red dots flash_x, flash_y = bmap(flash_lon, flash_lat) bmap.plot(flash_x, flash_y, 'ro', markersize=1, label='Flash') plt.legend(fontsize=label_fontsize, loc=4) else: if (glm_variables[1]): # Get Events from Glm file event_lat = g16glm.variables['event_lat'][:] event_lon = g16glm.variables['event_lon'][:] # Plot events as large blue dots event_x, event_y = bmap(event_lon, event_lat) bmap.plot(event_x, event_y, 'bo', markersize=7, label='Events') if (glm_variables[2]): # Get Group from Glm file group_lat = g16glm.variables['group_lat'][:] group_lon = g16glm.variables['group_lon'][:] # Plot groups as medium green dots group_x, group_y = bmap(group_lon, group_lat) bmap.plot(group_x, group_y, 'go', markersize=3, label='Group') if (glm_variables[3]): # Get Flash from Glm file flash_lat = g16glm.variables['flash_lat'][:] flash_lon = g16glm.variables['flash_lon'][:] # Plot flashes as small red dots flash_x, flash_y = bmap(flash_lon, flash_lat) bmap.plot(flash_x, flash_y, 'ro', markersize=1, label='Flash') plt.legend(fontsize=label_fontsize, loc=4) #plt.show() Start = glm_nc[glm_nc.find('_s') + 1:glm_nc.find("_e") - 3] year = int(Start[1:5]) dayjulian = int( Start[5:8]) - 1 # Subtract 1 because the year starts at "0" dayconventional = datetime.datetime(year, 1, 1) + datetime.timedelta( dayjulian) # Convert from julian to conventional month = dayconventional.strftime('%m') day = dayconventional.strftime('%d') hour = int(Start[8:12]) plt.savefig('/home/cendas/GOES16_WS_Rodrigo/GLM/Output/' + local + '/glm_' + str(year) + str(month) + str(day) + '_' + str(hour) + '_' + tipos[formato] + '.png', dpi=DPI, pad_inches=0, transparent=True, bbox_inches='tight') plt.close()
(0.7, 0.7, 0.0), (0.9, 0.0, 0.0), (0.95, 1.0, 1.0), (1.0, 1.0, 1.0), ), "green": ( (0.0, 0.0, 0.7), (0.7, 0.7, 0.0), (0.9, 0.0, 0.0), (0.95, 1.0, 1.0), (1.0, 0.0, 0.0), ), "blue": ((0.0, 0.0, 0.7), (0.7, 0.7, 1.0), (0.95, 1.0, 1.0), (1.0, 0.0, 0.0)), } CMAP_SPBND_BURD = LinearSegmentedColormap("spbnd_BuRd", cdict_spbnd_BuRd) # 1b) Map for species boundaries (95%: 0.95), blue for values at # 0.64 (0.8 * 0.8) or below, red for values at 1.0; white at 0.9. # Also, anything below 0.25 (0.5 * 0.5) is 70% grey cdict_hadamard_BuRd = { "red": ( (0.0, 0.0, 0.7), (0.25, 0.7, 0.0), (0.64, 0.0, 0.0), (0.64, 1.0, 1.0), (1.0, 1.0, 1.0), ), "green": ( (0.0, 0.0, 0.7), (0.25, 0.7, 0.0),
def register_colormaps(): ''' Create custom colormaps and register them ''' obpg = { 'red': [(0.00, 0.56, 0.56), (0.19, 0.00, 0.00), (0.38, 0.00, 0.00), (0.50, 0.00, 0.00), (0.63, 1.00, 1.00), (0.88, 1.00, 1.00), (1.00, 0.40, 0.40)], 'green': [(0.00, 0.00, 0.00), (0.19, 0.00, 0.00), (0.38, 1.00, 1.00), (0.50, 1.00, 1.00), (0.63, 1.00, 1.00), (0.88, 0.00, 0.00), (1.00, 0.00, 0.00)], 'blue': [(0.00, 0.43, 0.43), (0.19, 1.00, 1.00), (0.38, 1.00, 1.00), (0.50, 0.00, 0.00), (0.63, 0.00, 0.00), (0.88, 0.00, 0.00), (1.00, 0.00, 0.00)], } ak01 = { 'red': [( 0, 0.1, 0.1, ), ( 0.1, 0.56, 0.56, ), ( 0.22, 0, 0, ), ( 0.27, 0, 0, ), ( 0.37, 0.3, 0.3, ), ( 0.47, 0, 0, ), ( 0.52, 0, 0, ), ( 0.64, 1, 1, ), ( 0.76, 1, 1, ), ( 0.88, 0.4, 0.4, ), ( 1, 1, 1, )], 'green': [( 0, 0, 0, ), ( 0.1, 0, 0, ), ( 0.22, 0, 0, ), ( 0.27, 0, 0, ), ( 0.37, 0.6, 0.6, ), ( 0.47, 0.6, 0.6, ), ( 0.52, 1, 1, ), ( 0.64, 1, 1, ), ( 0.76, 0, 0, ), ( 0.88, 0, 0, ), ( 1, 0.5, 0.5, )], 'blue': [( 0, 0.1, 0.1, ), ( 0.1, 0.5, 0.5, ), ( 0.22, 0.5, 0.5, ), ( 0.27, 1, 1, ), ( 0.37, 1, 1, ), ( 0.47, 0, 0, ), ( 0.52, 0, 0, ), ( 0.64, 0, 0, ), ( 0.76, 0, 0, ), ( 0.88, 0, 0, ), ( 1, 0.5, 0.5, )], } if MATPLOTLIB_IS_INSTALLED: cm.register_cmap(cmap=LinearSegmentedColormap('obpg', obpg, 256)) cm.register_cmap(cmap=LinearSegmentedColormap('ak01', ak01, 256))
plt.close() ''' if args.weights: import math from matplotlib.colors import LinearSegmentedColormap #Color maps cdict = { 'red': ((0.0, 0.97, 0.97), (0.25, 0.0, 0.0), (0.75, 0.0, 0.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.25, 0.25), (0.25, 0.15, 0.15), (0.75, 0.39, 0.39), (1.0, 0.78, 0.78)), 'blue': ((0.0, 1.0, 1.0), (0.25, 0.65, 0.65), (0.75, 0.02, 0.02), (1.0, 0.0, 0.0)) } myColor = LinearSegmentedColormap('myColorMap', cdict) nLayers = 0 for layer in model.layers: if len(layer.get_weights()) == 0: continue nLayers += 1 maxWeights = 0 figure = plt.figure() figure.suptitle("Weights", fontsize=12) i = 1 nRow = 2 nCol = 3
(value[220], (0.76190476, 0.3968254, 0.07936508)), (value[224], (0.74603175, 0.34920635, 0.0952381)), (value[240], (0.65079365, 0.17460317, 0.0952381)), (value[255], (0.57142857, 0.04761905, 0.11111111))) from matplotlib.colors import LinearSegmentedColormap arcoiris = ((1., 1., 1.), (0.74603175, 0.84126984, 0.96825397), (0.47619048, 0.68253968, 0.92063492), (0.36507937, 0.58730159, 0.87301587), (0.26984127, 0.46031746, 0.77777778), (0.0952381, 0.20634921, 0.6031746), (0.06349206, 0.20634921, 0.50793651), (0.19047619, 0.46031746, 0.50793651), (0.34920635, 0.68253968, 0.44444444), (0.50793651, 0.74603175, 0.34920635), (0.66666667, 0.80952381, 0.26984127), (1., 0.95238095, 0.07936508), (0.92063492, 0.74603175, 0.22222222), (0.84126984, 0.53968254, 0.36507937), (0.82539683, 0.49206349, 0.3968254), (0.82539683, 0.47619048, 0.3015873), (0.80952381, 0.44444444, 0.15873016), (0.76190476, 0.3968254, 0.07936508), (0.74603175, 0.34920635, 0.0952381), (0.65079365, 0.17460317, 0.0952381), (0.57142857, 0.04761905, 0.11111111)) cdict = {'red': arcoiris, 'green': arcoiris, 'blue': arcoiris} cmap_arcoiris = LinearSegmentedColormap('my_colormap', cdict, 256)
density_cancer, _, _ = np.histogram2d(lats_cancer, lons_cancer, [lats_cancer_bin, lons_cancer_bin]) # Turn the lon/lat of the bins into 2 dimensional arrays ready # for conversion into projected coordinates lon_bins_cancer_2d, lat_bin_cancer_2d = np.meshgrid(lons_cancer_bin, lats_cancer_bin) # convert the bin mesh to map coordinates: # will be plotted using pcolormesh xs_cancer, ys_cancer = m(lon_bins_cancer_2d, lat_bin_cancer_2d) cdict = { 'red': ((0.0, 1.0, 1.0), (1.0, 0.9, 1.0)), 'green': ((0.0, 1.0, 1.0), (1.0, 0.03, 0.0)), 'blue': ((0.0, 1.0, 1.0), (1.0, 0.16, 0.0)) } custom_map = LinearSegmentedColormap('custom_map', cdict) plt.register_cmap(cmap=custom_map) density_cancer = np.hstack( (density_cancer, np.zeros((density_cancer.shape[0], 1)))) density_cancer = np.vstack((density_cancer, np.zeros( (density_cancer.shape[1])))) # add histogram squares and a corresponding colorbar to the map: plt.pcolormesh(xs_cancer, ys_cancer, density_cancer, cmap="custom_map", shading='gouraud') cbar = plt.colorbar(orientation='horizontal', shrink=0.625,
__author__ = 'alansanders' from matplotlib.colors import LinearSegmentedColormap _cmap_data = {'red': ((0., 0, 0), (0.25, 0, 0), (0.55, 1, 1), (0.85, 1, 1), (1, 0.6, 0.6)), 'green': ((0., 0.2, 0.2), (0.1, 0.4, 0.4), (0.45, 1, 1), (0.55, 1, 1), # (0.8, 0, 0), (0.85, 0, 0), (1, 0., 0.)), 'blue': ((0., 0.5, 0.5), (0.2, 1, 1), (0.85, 0, 0), (0.85, 0, 0), (1, 0., 0.)) } np_cmap = LinearSegmentedColormap('np_cmap', _cmap_data, 256)
self._map(resdat, resdat) vmin = self._map(vmin) vmax = self._map(vmax) resdat -= vmin resdat /= (vmax - vmin) result = np.ma.array(resdat, mask=result.mask, copy=False) if is_scalar: result = result[0] return result from matplotlib.colors import LinearSegmentedColormap # a colormap that goes from white to black: the opposite of matplotlib.gray() antigray = LinearSegmentedColormap('antigray', {'red': ((0., 1, 1), (1., 0, 0)), 'green': ((0., 1, 1), (1., 0, 0)), 'blue': ((0., 1, 1), (1., 0, 0))}) bluegrayred = LinearSegmentedColormap('bluegrayred', {'red': ((0., -1, 0), (1., 1, -1)), 'green': ((0., -1, 0), (0.5,0.5, 0.5), (1., 0, -1)), 'blue': ((0., -1, 1), (1., 0, -1))}) # x, y0, y1 _redgreen_data = {'red': ((0., -100, 1), #(0.5, 0, 0), #(0.5, 0.1, 0),
def legend(self, bytesio): #pylint: disable=too-many-locals, too-many-statements def custom_label(label, custom_config): prefix = custom_config.get("prefix", "") l = custom_config.get("label", label) suffix = custom_config.get("suffix", "") return f"{prefix}{l}{suffix}" # Create custom cdict for matplotlib colorramp # Matplot lib color dicts must start at 0 and end at 1 # because of this we normalize the values # Also create tick labels based on configuration # ticks are also normalized between 0 - 1.0 # so they are position correctly on the colorbar def create_cdict_ticks(components, cfg): generate = (cfg.get("major_ticks", None) is not None or \ cfg.get("scale_by", None) is not None or \ cfg.get("radix_point", None) is not None) return from_definition(components, cfg, generate) def find_clc(ramp, last=False): l = ramp if not last else reversed(ramp) for index, value in enumerate(l): fwd_index = index if not last else (len(ramp) - (index + 1)) if "legend" in value: return fwd_index return 0 if not last else (len(ramp) - 1) def from_definition(components, cfg, generate): tick_mod = cfg.get("major_ticks", 1) tick_scale = cfg.get("scale_by", 1) places = cfg.get("radix_point", 1) ramp = cfg.get("ramp") start_index = find_clc(ramp) if not generate else 0 stop_index = find_clc( ramp, last=True) if not generate else (len(ramp) - 1) start = ramp[start_index].get("value") stop = ramp[stop_index].get("value") normalize_factor = stop - start ticks = dict() cdict = dict() bands = defaultdict(list) for index, ramp_val in enumerate(ramp): if index < start_index or index > stop_index: continue value = ramp_val.get("value") normalized = (value - start) / normalize_factor custom_legend_cfg = ramp_val.get("legend", None) mod_close = False mod_equal = False if generate: mod_close = isclose( (value * tick_scale) % (tick_mod * tick_scale), 0.0, abs_tol=1e-8) mod_equal = value % tick_mod == 0 if mod_close or mod_equal: label = value * tick_scale label = round(label, places) if places > 0 else int(label) ticks[normalized] = label if custom_legend_cfg is not None: label = custom_label(value, custom_legend_cfg) ticks[normalized] = label for band, intensity in components.items(): bands[band].append( (normalized, intensity[index], intensity[index])) for band, blist in bands.items(): cdict[band] = tuple(blist) if len(ticks) == 0: ticks = None return cdict, ticks combined_cfg = self.legend_cfg combined_cfg["ramp"] = self.color_ramp cdict, ticks = create_cdict_ticks(self.components, combined_cfg) plt.rcdefaults() if combined_cfg.get("rcParams", None) is not None: plt.rcParams.update(combined_cfg.get("rcParams")) fig = plt.figure(figsize=(combined_cfg.get("width", 4), combined_cfg.get("height", 1.25))) ax_pos = combined_cfg.get("axes_position", [0.05, 0.5, 0.9, 0.15]) ax = fig.add_axes(ax_pos) custom_map = LinearSegmentedColormap(self.product.name, cdict) color_bar = matplotlib.colorbar.ColorbarBase(ax, cmap=custom_map, orientation="horizontal") if ticks is not None: color_bar.set_ticks(list(ticks.keys())) color_bar.set_ticklabels([str(l) for l in ticks.values()]) title = self.legend_cfg.get("title", self.title) unit = self.legend_cfg.get("units", "unitless") title = title + "(" + unit + ")" color_bar.set_label(title) plt.savefig(bytesio, format='png')
datad = _cmocean_datad datad.update(_cm_datad) def _rev_cdict(cdict): """Revert a dictionary containing specs for a LinearSegmentedColormap.""" rev_cdict = {} for k, v in cdict.items(): rev_cdict[k] = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(v)] return rev_cdict cmaps = {} for (name, data) in datad.items(): if 'red' in data: cmaps[name] = LinearSegmentedColormap(name, data) cmaps[name + '_r'] = LinearSegmentedColormap(name + '_r', _rev_cdict(data)) else: cmaps[name] = LinearSegmentedColormap.from_list(name, data, N=len(data)) cmaps[name + '_r'] = LinearSegmentedColormap.from_list(name + '_r', data[::-1], N=len(data)) locals().update(cmaps) for name, cm in cmaps.items(): register_cmap(name, cm)