def _register_cmap_clip(name, original_cmap, alpha): """Create a color map with "over" and "under" values.""" from matplotlib.colors import LinearSegmentedColormap cdict = plt.cm.datad[original_cmap] cmap = LinearSegmentedColormap(name, cdict) cmap.set_over([alpha * c + 1 - alpha for c in cmap(1.0)[:3]]) cmap.set_under([alpha * c + 1 - alpha for c in cmap(0.0)[:3]]) plt.cm.register_cmap(cmap=cmap)
def _register_cmap_clip(name, original_cmap, alpha): """Create a color map with "over" and "under" values.""" from matplotlib.colors import LinearSegmentedColormap cdata = _plt.cm.datad[original_cmap] if isinstance(cdata, dict): cmap = LinearSegmentedColormap(name, cdata) else: cmap = LinearSegmentedColormap.from_list(name, cdata) cmap.set_over([alpha * c + 1 - alpha for c in cmap(1.0)[:3]]) cmap.set_under([alpha * c + 1 - alpha for c in cmap(0.0)[:3]]) _plt.cm.register_cmap(cmap=cmap)
def _register_cmap_clip(name, original_cmap, alpha): """Create a color map with "over" and "under" values.""" from matplotlib.colors import LinearSegmentedColormap cdata = _plt.cm.datad[original_cmap] if isinstance(cdata, dict): cmap = LinearSegmentedColormap(name, cdata) else: cmap = LinearSegmentedColormap.from_list(name, cdata) cmap.set_over([alpha * c + 1 - alpha for c in cmap(1.0)[:3]]) cmap.set_under([alpha * c + 1 - alpha for c in cmap(0.0)[:3]]) _plt.cm.register_cmap(cmap=cmap)
def get_color_map(color): '''Generate a LinearSegmentedColormap with a single color and varying transparency. Bad values and values below the lower limit are set to be completely transparent. Parameters ---------- color: string or array-like with shape (3,) The color to use when overlaying the survey footprint. Either a string that can be input to colorConverter.to_rgb() or rgb triplet. Returns ------- colormap1: LinearSegmentedColormap A color map that is a single color but varies its opacity from 0.5 to 1. Bad values and values below the minimum are completely transparent. ''' from matplotlib.colors import LinearSegmentedColormap from matplotlib.colors import colorConverter # if the type is a string it is assumed to be an input to allow us # to get an rgb value. If it is not a string and length is 3, it is # assumed to be an actual rgb value if isinstance(color, str): rgb = colorConverter.to_rgb(color) elif len(color) == 3: rgb = color else: raise ValueError('Bad color input') cdict = {'red': [(0, rgb[0], rgb[0]), (1, rgb[0], rgb[0])], 'green': [(0, rgb[1], rgb[1]), (1, rgb[1], rgb[1])], 'blue': [(0, rgb[2], rgb[2]), (1, rgb[2], rgb[2])], 'alpha': [(0, 0.5, 0.5), (1, 1, 1)]} colormap1 = LinearSegmentedColormap('FootprintCM', cdict) colormap1.set_bad(alpha=0.0) colormap1.set_under(alpha=0.0) return colormap1
def build_cmap(stops): # {{{ from matplotlib.colors import LinearSegmentedColormap ct = dict(red=[], blue=[], green=[]) for s in stops: if 'r2' in s: ct['red'].append((s['s'], s['r'], s['r2'])) ct['green'].append((s['s'], s['g'], s['g2'])) ct['blue'].append((s['s'], s['b'], s['b2'])) else: ct['red'].append((s['s'], s['r'], s['r'])) ct['green'].append((s['s'], s['g'], s['g'])) ct['blue'].append((s['s'], s['b'], s['b'])) cm = LinearSegmentedColormap('loaded_colourmap', ct, 256) cm.set_under((stops[ 0]['r'], stops[ 0]['g'], stops[ 0]['b'])) cm.set_over ((stops[-1]['r'], stops[-1]['g'], stops[-1]['b'])) return cm
def get_color_map(color): '''Generate a LinearSegmentedColormap with a single color and varying transparency. Bad values and values below the lower limit are set to be completely transparent. Parameters ---------- color: string or array-like with shape (3,) The color to use when overlaying the survey footprint. Either a string that can be input to colorConverter.to_rgb() or rgb triplet. Returns ------- colormap1: LinearSegmentedColormap A color map that is a single color but varies its opacity from 0.5 to 1. Bad values and values below the minimum are completely transparent. ''' from matplotlib.colors import LinearSegmentedColormap from matplotlib.colors import colorConverter # if the type is a string it is assumed to be an input to allow us # to get an rgb value. If it is not a string and length is 3, it is # assumed to be an actual rgb value if isinstance(color, str): rgb = colorConverter.to_rgb(color) elif len(color) == 3: rgb = color else: raise ValueError('Bad color input') cdict = { 'red': [(0, rgb[0], rgb[0]), (1, rgb[0], rgb[0])], 'green': [(0, rgb[1], rgb[1]), (1, rgb[1], rgb[1])], 'blue': [(0, rgb[2], rgb[2]), (1, rgb[2], rgb[2])], 'alpha': [(0, 0.5, 0.5), (1, 1, 1)] } colormap1 = LinearSegmentedColormap('FootprintCM', cdict) colormap1.set_bad(alpha=0.0) colormap1.set_under(alpha=0.0) return colormap1
def get_ctable(self, under=None, over=None): """カラーマップを作成する Parameters: ---------- under: str 下限を下回った場合の色 over: str 上限を上回った場合の色 ---------- Returns: ---------- cmap カラーマップ ---------- """ # カラーマップ作成 cmap = LinearSegmentedColormap('colormap_name', self._segment_data) if under is not None: cmap.set_under(under) # 下限を下回った場合の色を指定 if over is not None: cmap.set_over(over) # 上限を超えた場合の色を指定 return cmap
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)
(0.964705882352941,0.76896484375,0.76896484375), (0.968627450980392,0.78075390625,0.78075390625), (0.972549019607843,0.79254296875,0.79254296875), (0.976470588235294,0.80433203125,0.80433203125), (0.980392156862745,0.81612109375,0.81612109375), (0.984313725490196,0.82791015625,0.82791015625), (0.988235294117647,0.839703125,0.839703125), (0.992156862745098,0.8514921875,0.8514921875), (0.996078431372549,0.86328125,0.86328125), (1,0,0)), } califa = LinearSegmentedColormap('CALIFA', cdict) califa.set_bad(color='navy') califa.set_under(color='navy') califa.set_over(color='navy') register_cmap(cmap=califa) #plt.xkcd() hdus = fits.open('NGC4047.p_e.rad_SFR_lum_Mass.fits.gz') img = hdus[0].data fig=plt.figure() ax1 = fig.add_subplot(111) #img_mask= np.power(10, img) img_masked= img where_are_NaNs = np.isnan(img_masked) img_masked[where_are_NaNs] = 0
rgb = lch2rgb(lch) reds.append((pos, rgb[0], rgb[0])) greens.append((pos, rgb[1], rgb[1])) blues.append((pos, rgb[2], rgb[2])) alphas.append((pos, 1.0, 1.0)) red_blue = LinearSegmentedColormap('red_blue', { "red": reds, "green": greens, "blue": blues, "alpha": alphas }) red_blue.set_bad(gray_rgb, 1.0) red_blue.set_over(gray_rgb, 1.0) red_blue.set_under( gray_rgb, 1.0 ) # "under" is incorrectly used instead of "bad" in the scatter plot red_blue_no_bounds = LinearSegmentedColormap('red_blue_no_bounds', { "red": reds, "green": greens, "blue": blues, "alpha": alphas }) red_blue_transparent = LinearSegmentedColormap( 'red_blue_no_bounds', { "red": reds, "green": greens, "blue": blues, "alpha": [(a[0], 0.5, 0.5) for a in alphas]
# 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 = 'jet' # Constrain the colorbar P_min = np.min( P[P>0.].cgs.value ) # Minimum (non-empty) value of sigma P_max = np.max( P.cgs.value ) # Maximum value of sigma levels = np.linspace( np.floor(np.log10(P_min)), np.ceil(np.log10(P_max)), 100 ) # Levels of colorbar cbar_ticks = np.arange( np.floor(np.log10(P_min)), np.ceil(np.log10(P_max))+0.1, 0.5 ) # Ticks of colorbar # Create plot fig, ax = plt.subplots(subplot_kw=dict(projection='polar')) # Use polar coordinate system plt.subplots_adjust(bottom=0.25) # Create space at the bottom for the slider plot = ax.contourf(theta_cen, R_cen.to(u.AU), np.log10(P[ :, :].cgs.value), cmap=colormap, levels=levels, extend='both' ) # Filled contour plot collections_list = plot.collections[:] # Collect the collections....lol
fig, ax = plt.subplots(1, figsize=(6, 6)) ax.set_aspect(1) ax.set_xlim(-1.1, 1.1) ax.set_ylim(-1.1, 1.1) ax.axis("off") b = 0.25 theta = 0 # Illumination cdict = { "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]], } cmap = LinearSegmentedColormap("testCmap", segmentdata=cdict, N=256) cmap.set_under("k") x0, y0 = np.meshgrid(np.linspace(-1, 1, 3000), np.linspace(-1, 1, 3000)) x = x0 * np.cos(theta) + y0 * np.sin(theta) y = -x0 * np.sin(theta) + y0 * np.cos(theta) z = np.sqrt(1 - x**2 - y**2) I = np.sqrt(1 - b**2) * y - b * z I[I < 0] = 0 ax.imshow( I, extent=(-1, 1, -1, 1), origin="lower", vmin=1e-8, vmax=1, cmap=cmap, alpha=0.75, zorder=-1,
lch = [l, c, h] rgb = lch2rgb(lch) reds.append((pos, rgb[0], rgb[0])) greens.append((pos, rgb[1], rgb[1])) blues.append((pos, rgb[2], rgb[2])) alphas.append((pos, 1.0, 1.0)) red_blue = LinearSegmentedColormap('red_blue', { "red": reds, "green": greens, "blue": blues, "alpha": alphas }) red_blue.set_bad(gray_rgb, 1.0) red_blue.set_over(gray_rgb, 1.0) red_blue.set_under(gray_rgb, 1.0) red_green = red_blue #LinearSegmentedColormap('red_blue', cdict2)#.reversed() def summary_plot(shap_values, id, features=None, feature_names=None, max_display=None, plot_type="dot", color=None, axis_color="#333333", title=None, alpha=1, show=True,
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
def create_cmap(start, end, mid=None, N=256, extend='neither', over=None, under=None, normalize=None): """ Function that creates matplotlib colormaps. Note that input colors must be RGB tuples within [0,1]. Parameters ---------- start : 3-tuple RGB-Tuple defining the start color of the color map. end : 3-tuple RGB-Tuple defining the end color of the color map. mid : list (optional, default = None) List of tuples (pos, col) specifying any colors in between start and end. In this context, 0. < pos < 1. specifiies the position of col (passed as RGB tuple) within the color map range. N : int (optional, default = 256) The number of rgb quantization levels. extend : string (optional, one of {*'neither'*, 'both', 'max', 'min'}) Extend the colorbar and indicate this by triangles at the respective ends. See eg. here: http://matplotlib.org/examples/pylab_examples/contourf_demo.html over : 3-tuple (optional, default = None) Color definition for everything out of the upper range of the colormap. This is only meaningful if you set the ``extend`` option correctly. Uses ``end`` by default. under : 3-tuple (optional, default = None) Same as ``over`` but for the lower limit. Uses ``start`` by default. Returns ------- cmap : LinearSegmentedColormap instance color map, ready to be used with matplotlib. Examples -------- If you want a colormap ranging from tumblue over white to tumorange, you call this function via >>> cmap = create_cmap(start = tumcolors['tumblue'], end = tumcolors['tumorange'], mid = [(0.5, tumcolors['white'])] ) You can also go straight from tumblue to tumorange: >>> cmap = create_cmap(start = tumcolors['tumblue'], end = tumcolors['tumorange']) Or you can add several colors in between: >>> cmap = create_cmap(start = tumcolors['tumblue'], end = tumcolors['tumorange'], mid = [(0.3, tumcolors['white']), (0.7, tumcolors['black'])] ) """ from matplotlib.colors import LinearSegmentedColormap cdict = dict() for i, channel in enumerate(['red', 'green', 'blue']): cdict_content = [[0.0, start[i], start[i]]] if mid is not None: try: for pos, col in mid: cdict_content.append([pos, col[i], col[i]]) except TypeError: pos, col = mid cdict_content.append([pos, col[i], col[i]]) cdict_content.append([1.0, end[i], end[i]]) cdict[channel] = cdict_content cmap = LinearSegmentedColormap('custom_cmap', cdict, N) # extend cmap.colorbar_extend = extend if under is None: under = start if over is None: over = end cmap.set_over(over) cmap.set_under(under) return cmap
#red_blue.set_bad("#777777") red_blue_solid = LinearSegmentedColormap( 'red_blue_solid', { 'red': ((0.0, 30. / 255, 30. / 255), (1.0, 255. / 255, 255. / 255)), 'green': ((0.0, 136. / 255, 136. / 255), (1.0, 13. / 255, 13. / 255)), 'blue': ((0.0, 229. / 255, 229. / 255), (1.0, 87. / 255, 87. / 255)), 'alpha': ((0.0, 1, 1), (0.5, 1, 1), (1.0, 1, 1)) }) red_blue_solid.set_bad("#777777", 1.0) red_blue_solid.set_over("#777777", 1.0) red_blue_solid.set_under( "#777777", 1.0 ) # "under" is incorrectly used instead of "bad" in the scatter plot colors = [] for l in np.linspace(1, 0, 100): colors.append((30. / 255, 136. / 255, 229. / 255, l)) for l in np.linspace(0, 1, 100): colors.append((255. / 255, 13. / 255, 87. / 255, l)) red_transparent_blue = LinearSegmentedColormap.from_list( "red_transparent_blue", colors) colors = [] for l in np.linspace(0, 1, 100): colors.append((30. / 255, 136. / 255, 229. / 255, l)) transparent_blue = LinearSegmentedColormap.from_list( "transparent_blue", colors)
def generate_plot(self): # Get label label = self.generate_label() # Check all inputs if len(self.master.master.input_keys) == 0: messagebox.showerror( "No Input Data Sets", "No input data sets were found. Either there is no database " + "selected, or the selected database has no valid data. " + "You should really do something about that.") arr_name = self.arr_name.combox_input.get() if self.include_ll: ll_name = self.ll_name.combox_input.get() else: ll_name = None if arr_name == "" or ll_name == "": messagebox.showerror( "Missing Input", "Make sure all enabled output plots have a selected input.") # Get data from database analysis_db = AnalysisDatabase(self.db_path) z = analysis_db.get_val(self.input_key, arr_name) if z.shape[1] == 2: messagebox.showwarning( "Data Looks Weird", "The shape of this data makes it look like you may have " + "selected a histogram. Are you sure you didn't?") if self.include_ll: leak = analysis_db.get_val(self.input_key, ll_name) # Get noise threshold for heatmap by sampling outer edge of data noise_sample = np.concatenate( (z[0, :], z[-1, :], z[:, 0][1:-1], z[:, -1][1:-1])) noise_threshold = np.average(noise_sample) + 6 * np.std(noise_sample) # Setup heatmap x = np.arange(np.shape(z)[1]) y = np.arange(np.shape(z)[0]) z = z[:-1, :-1] if self.title == "Dominant Wavelength Heatmap": cmap = LinearSegmentedColormap('Spectrum', spec_dict_wl) max_val = 830 min_val = 380 cmap.set_under('white') cmap.set_over('gray') else: cmap = LinearSegmentedColormap('Rainbow', spec_dict_rb) max_val = np.max(z) min_val = noise_threshold plt.register_cmap(cmap=cmap) fig, (ax0) = plt.subplots(nrows=1) im = ax0.pcolormesh(x, y, z, cmap=cmap, norm=Normalize(vmin=min_val, vmax=max_val)) cbar = fig.colorbar(im, ax=ax0) if self.title == "Luminance Heatmap" or \ self.title == "Light Leakage Heatmap": cbar.set_label('Luminance [cd/m^2]', rotation=270, labelpad=15) elif self.title == "Uniformity Heatmap": cbar.set_label('Uniformity [cd/m^2/mm]', rotation=270, labelpad=15) elif self.title == "Dominant Wavelength Heatmap": cbar.set_label('Wavelength [nm]', rotation=270, labelpad=15) ax0.set_title(self.title + " - " + label) if self.include_ll: plt.text(int(z.shape[1] / 10), int(z.shape[0] / 10), "Leakage Ratio: " + str(leak)) fig.tight_layout() if self.return_fig: return fig
# 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 = 'RdPu' # Constrain the colorbar P_min = np.min( P[P>0.].cgs.value ) # Minimum (non-empty) value of sigma P_max = np.max( P.cgs.value ) # Maximum value of sigma #P_min = 10**(np.ceil( np.log10( np.max( P.cgs.value ) ) ) - 4.0 ) levels = np.linspace( np.floor(np.log10(P_min)), np.ceil(np.log10(P_max)), 100 ) # Levels of colorbar cbar_ticks = np.arange( np.floor(np.log10(P_min)), np.ceil(np.log10(P_max))+0.1, 0.5 ) # Ticks of colorbar # Create plot fig, ax = plt.subplots(subplot_kw=dict(projection='polar')) # Use polar coordinate system plt.subplots_adjust(bottom=0.25) # Create space at the bottom for the slider plot = ax.contourf(theta_cen, R_cen.to(u.AU), np.log10(P[ :, :].cgs.value), cmap=colormap, levels=levels, extend='both' ) # Filled contour plot
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)
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. ''' import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap 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) plt.register_cmap(cmap=newcmap) return newcmap
ax3.set_xlabel('Density', fontsize=22, fontweight='bold') ax3.set_ylabel('Depth (m)', fontsize=22, fontweight='bold') # T-S Diagrams (Panel 4) cs = ax4.contour(Sg, Tg, sigma_theta, colors='grey', linestyles='dashed') cl = plt.clabel(cs, inline=1, fontsize=20, fmt='%0.1f') N = 19 cmap = cmocean.cm.dense colors = cmap(np.linspace(.1, 1, 19)) cmap = c.LinearSegmentedColormap.from_list('mycmap', colors) cmdict = cmocean.tools.get_dict(cmap, N=19) cmap = LinearSegmentedColormap(cmap, segmentdata=cmdict, N=N) cmap.set_under('black') # define the bins and normalize bounds = np.linspace(0, 150, 6) norm = c.BoundaryNorm(bounds, cmap.N) if not prev.empty: sc = ax4.scatter(prev['salinity'], prev['temperature'], c=prev['depth'], cmap=cmap, s=100, norm=norm) sc = ax4.scatter(group[1]['salinity'], group[1]['temperature'], c=group[1]['depth'], cmap=cmap, s=100, norm=norm, edgecolor='black' ) cb = plt.colorbar(sc, aspect=50, extend='max') # axs[1, 1].set_xlim(ts_xlim) ax4.set_xlim(salinity_xlim) ax4.set_ylim(temp_xlim) ax4.set_xlabel('Salinity', fontsize=22, fontweight='bold')