def __init__(self, colors, N, stops=None): # store stops self.stops = stops # set colors self.set_color(colors) # initialize Colormap.__init__(self, "test", N)
def __init__(self, colors: Sequence, N: int, stops=None): """ initialize with the given colors and stops """ # store stops self.stops = stops # set colors self.set_color(colors) # initialize Colormap.__init__(self, "test", N)
def plot_energy_error_heatmap(ax, data_set, struct_types=struct_types, dyn_types=dyn_types, bad_data_traj_list=[], xbin_size=None, ybin_size=None, use_meV_y=False, use_meV_x=False, cmap=cm.get_cmap('plasma')): scalex = 1 scaley = 1 if use_meV_x: scalex = 1000 if use_meV_y: scaley = 1000 def pick_bins(abin_size, A): if abin_size is None: abins = np.linspace(A.min(), A.max(), 100) else: abins = np.arange(A.min(), A.max(), abin_size) return abins #from matplotlib.ticker import MultipleLocator #ax.yaxis.set_major_locator(MultipleLocator(base=30)) #ax.yaxis.set_minor_locator(MultipleLocator(base=5)) import copy cmap_tweaked = copy.copy(cmap) from matplotlib.colors import Colormap Colormap.set_under(cmap_tweaked, color=(1, 1, 1, 0)) Colormap.set_over(cmap_tweaked, color=(1, 1, 1, 0)) fname = data_set[0] data_name = data_set[1] image_pairs = read_evaluation_data(filename=fname, struct_types=struct_types, dyn_types=dyn_types, bad_data_traj_list=bad_data_traj_list) cache_energy, data_energy = get_energy_lists(image_pairs) energy_error = cache_energy - data_energy error_rmse = np.sqrt(np.mean(energy_error**2)) * scaley error_mae = np.mean(np.absolute(energy_error)) * scaley X = data_energy * scalex Y = energy_error * scaley xbins = pick_bins(xbin_size, X) ybins = pick_bins(ybin_size, Y) ax.hist2d(X, Y, bins=(xbins, ybins), vmin=1, cmap=cmap_tweaked) ax.set_title(data_name, fontsize=8) ax.minorticks_on() return error_rmse, error_mae
def plot_force_angle_heatmaps(axes, data_sets, struct_types=struct_types, dyn_types=dyn_types, struct_colors=struct_colors, dyn_markers=dyn_markers, bad_data_traj_list=[], cmap=cm.get_cmap('plasma')): deg = 180 / np.pi bin_size = 2 my_bins = np.arange(0, 180 + bin_size / 2, bin_size) ylims = (0, 180) from matplotlib.ticker import MultipleLocator import copy cmap_tweaked = copy.copy(cmap) from matplotlib.colors import Colormap Colormap.set_under(cmap_tweaked, color=(1, 1, 1, 0)) Colormap.set_over(cmap_tweaked, color=(1, 1, 1, 0)) for di, data_set in enumerate(data_sets): fname = data_set[0] data_name = data_set[1] #color = np.array(get_color(data_set[2])) #lightness = data_set[3] #zorder = zorders[di] image_pairs = read_evaluation_data(filename=fname, struct_types=struct_types, dyn_types=dyn_types) cache_forces, data_forces = get_force_list(image_pairs) force_cosines_by_atom = compute_force_cosines_by_atom( cache_forces, data_forces) data_force_norms_by_atom = compute_force_norms_by_atom(data_forces) X = collapse_sub_lists(data_force_norms_by_atom) Y = deg * np.arccos(collapse_sub_lists(force_cosines_by_atom)) xbins = np.linspace(0, X.max(), 100) axes[di].hist2d(X, Y, bins=(xbins, my_bins), vmin=1, cmap=cmap_tweaked) #label = data_name + '\nMean: %.2f°\nRMS: %.2f°'%(mean_force_angles, rms_force_angles) axes[di].set_title(data_name, fontsize=8) axes[di].set_ylim(ylims) #ax2.legend(fontsize = 8, handletextpad = 0.3, borderpad = 0.1) axes[di].minorticks_on() axes[di].yaxis.set_major_locator(MultipleLocator(base=30)) axes[di].yaxis.set_minor_locator(MultipleLocator(base=5)) if di == 0: axes[di].set_ylabel('Force Angle, ' + formula_angle + ' (°)') axes[di].set_xlabel('DFT Force (eV/Å)')
def __init__(self, accels, max_accel=None, min_accel=None): self.accels = accels self.points = len(self.accels) if min_accel is not None: self.min_accel = min_accel else: self.min_accel = np.min(accels) if max_accel is not None: self.max_accel = max_accel else: self.max_accel = np.max(accels) Colormap.__init__(self, None, 255)
def __init__(self, source, name='Variable'): self.name = None # new VariableColormap object self.bad_set = False self.set_source(source) self.monochrome = False Colormap.__init__(self, name, self.worklut.shape[0]-3) self.canvases = {} self.frames = set() self.slope = 1.0 self.shift = 0.0 self.invrt = 1.0 self.scale = 'LINEAR' self.auto = True
def __init__(self, cmap): """ Make a colormap dynamic with respect to a hinge point. Dynamic colormaps are stretched to the ``[vmin, vmax]`` range, by separately scaling the lower part of the colormap (v < ``hinge``) and the upper part (v > ``hinge``). For instance, a colormap with v range `[-1, 1]` and hinge at `0` with `min_color` at `-1`, `hinge_color` and the ``hinge``, and `max_color` at `1`, can be dynamically scaled to ``[-10, 5]`` with `min_color` at `-10`, `hinge_color` and the ``hinge``, and `max_color` at `5`:: <|min_color-----------hinge_color-----------max_color|> -1 0 1 \ \ \ \ <|min_color-----------------hinge_color-----max_color|> -10 0 5 See Also -------- DynamicColormap.set_range Scale the colormap to a new range, keeping, or overriding the hinge point. """ self.monochrome = False Colormap.__init__(self, cmap.name, cmap.N) try: self.values = cmap.values except AttributeError: self.values = np.linspace(-1, 1, self.N) self._vmin = self.values[0] try: self._hinge = cmap.hinge except AttributeError: self._hinge = 0 self._vmax = self.values[-1] try: self.colors = cmap.colors except AttributeError: self.colors = cmap(self.values) self.set_range(self.vmin, self.vmax, self.hinge) self._lut = cmap._lut self._isinit = True self._set_extremes()
def __init__(self, source, name='Variable'): self.name = None # new VariableColormap object self.bad_set = False self.set_source(source) self.monochrome = False Colormap.__init__(self, name, self.worklut.shape[0]-3) self.canvases = {} self.frames = set() self.slope = 1.0 self.shift = 0.0 self.invrt = 1.0 self.scale = 'LINEAR' self.auto = True self.callback = None
def _matplotlib_color(colormap: Colormap, data: float) -> str: (r, g, b, a) = colormap.__call__(data) r = round(255 * r) g = round(255 * g) b = round(255 * b) return _rgb_color((r, g, b))
def test_wcs_having_no_naxis(self): w2 = astropy_wcs.WCS(header={ 'WCSAXES': 2, # Number of coordinate axes 'CRPIX1': 1000.0, # Pixel coordinate of reference point 'CRPIX2': 500.0, # Pixel coordinate of reference point 'CDELT1': -0.18, # [deg] Coordinate increment at reference point 'CDELT2': 0.18, # [deg] Coordinate increment at reference point 'CUNIT1': 'deg', # Units of coordinate increment and value 'CUNIT2': 'deg', # Units of coordinate increment and value 'CTYPE1': 'GLON-MOL', # galactic longitude, Mollweide's projection 'CTYPE2': 'GLAT-MOL', # galactic latitude, Mollweide's projection 'CRVAL1': 0.0, # [deg] Coordinate value at reference point 'CRVAL2': 0.0, # [deg] Coordinate value at reference point }) with pytest.raises(AttributeError): result = hips2fits.query_with_wcs( hips=self.hips, wcs=w2, get_query_payload=False, format='jpg', min_cut=0.5, max_cut=99.5, cmap=Colormap('viridis'), )
def test_query_jpg_no_wcs(self): from astropy.coordinates import Longitude from astropy.coordinates import Latitude from astropy.coordinates import Angle import astropy.units as u result = hips2fits.query( hips=self.hips, width=1000, height=500, fov=Angle(20 * u.deg), ra=Longitude(0 * u.deg), dec=Latitude(20 * u.deg), projection="TAN", get_query_payload=False, format='jpg', min_cut=0.5, max_cut=99.5, cmap=Colormap('viridis'), ) # import matplotlib.cm as cm # import matplotlib.pyplot as plt # im = plt.imshow(result) # plt.show(im) # We must get a numpy array with 3 dimensions, and the last one should be of size 3 (RGB) assert isinstance(result, np.ndarray) and result.shape[2] == 3
def __call__(self, value, *args, **kwargs): # get the color result = Colormap.__call__(self, value, *args, **kwargs) # add meta values to it result = CmapColor(result) result.setMeta(value, self) # return the color return result
def __call__(self, value: float, *args, **kwargs): """ get the color associated with the given value from the colormap """ # get the color result = Colormap.__call__(self, value, *args, **kwargs) # add meta values to it result = CmapColor(result) result.setMeta(value, self) # return the color return result
def test_bad_strech(self): with pytest.raises(AttributeError): result = hips2fits.query_with_wcs( hips=self.hips, wcs=self.w, get_query_payload=False, format='jpg', stretch="azs", min_cut=0.5, max_cut=99.5, cmap=Colormap('viridis'), )
def test_query_jpg(self): result = hips2fits.query_with_wcs( hips=self.hips, wcs=self.w, get_query_payload=True, format='jpg', min_cut=0.5, max_cut=99.5, cmap=Colormap('viridis'), ) # We must get a numpy array with 3 dimensions, and the last one should be of size 3 (RGB) assert result["format"] == 'jpg' and result["hips"] == "CDS/P/DSS2/red"
def set_colormap(self, colormap, bad_data='grey', update=True): """Sets a colormap. Args: colormap (str): A color scheme for plotting. bad_data (str): The color to use for bad data values. Needs to be a matplotlib color name. update (bool): Set to True to update the plot. """ if isinstance(colormap, str): colormap = Colormap(colormap) self.cmap = colormap if bad_data: self.cmap.set_bad(color=bad_data) if update: self.update()
def test_query_no_wcs_fits(self): result = hips2fits.query( hips=self.hips, get_query_payload=True, width=1000, height=500, fov=Angle(20 * u.deg), ra=Longitude(0 * u.deg), dec=Latitude(20 * u.deg), projection="TAN", min_cut=0.5, max_cut=99.5, cmap=Colormap('viridis'), ) # We must get a numpy array with 3 dimensions, and the last one should be of size 3 (RGB) assert result["format"] == 'fits' and result["hips"] == "CDS/P/DSS2/red"
def test_query_jpg(self): result = hips2fits.query_with_wcs( hips=self.hips, wcs=self.w, get_query_payload=False, format='jpg', min_cut=0.5, max_cut=99.5, cmap=Colormap('viridis'), ) # import matplotlib.cm as cm # import matplotlib.pyplot as plt # im = plt.imshow(result) # plt.show(im) # We must get a numpy array with 3 dimensions, and the last one should be of size 3 (RGB) assert isinstance(result, np.ndarray) and result.shape[2] == 3
landNAN[:] = np.nan land = np.hstack((landXY,landNAN)) # Data we want to read and interpolate data = glob.glob(path+'*.npy') data.sort() print data # Colormap Chl de ref # COULEUR norm_chl=mpl.colors.LogNorm(vmin=0.01, vmax=20) colors = [(0.33,0.33,0.33)] + [(plt.cm.jet(i)) for i in xrange(1,256)] new_map_chl = mpl.colors.LinearSegmentedColormap.from_list('new_map_chl', colors, N=256) new_map_chl._init(); new_map_chl._lut[0,:] = new_map_chl._lut[1,:] # Replace lowest value of colormap (which is gray) with the one before (dark blue) Colormap.set_under(new_map_chl,color=new_map_chl._lut[0,:]) # Set color for values outside colormap to be the lowest of the colormap (dark blue) ##Colormap.set_over(new_map_chl,color=(0.0, 0.0, 0.517825311942959, 1.0)) ## to get rgba from colormap for a specific value : new_map_chl(specificvalue for example ex : 0.2) # BLACK AND WHITE grays = [(0.33,0.33,0.33)] + [(plt.cm.gray(i)) for i in xrange(1,256)] new_map_gray_chl = mpl.colors.LinearSegmentedColormap.from_list('new_map_gray_chl', grays, N=256) # Colormap (avec borne grise) #norm_chl=mpl.colors.LogNorm(vmin=0.01, vmax=20) #colors = [(0.33,0.33,0.33)] + [(plt.cm.jet(i)) for i in xrange(1,256)] #new_map_chl = mpl.colors.LinearSegmentedColormap.from_list('new_map_chl', colors, N=256) #colors = [(0.33,0.33,0.33)] + [(plt.cm.gray(i)) for i in xrange(1,256)] #new_map_gray_chl = mpl.colors.LinearSegmentedColormap.from_list('new_map_gray_chl', colors, N=256) #==============================================================================
# |_____/|_|_| |_| |_| |_| \_\___|\__,_|\__,_|\___|\__|_|\___/|_| |_| # ################### Reduce dimensions ######################## off_f_red = LLE(n_neighbors=50, n_components=3).fit_transform(np.transpose(all_off_f)) #off_f_red = LLE(n_neighbors = 50,n_components=3).fit_transform(np.transpose(off_firing[0])) #off_f_red = TSNE(n_components=3).fit_transform(np.transpose(all_off_f)) ## 3D Plot for single trajectory for i in range(4): fig = plt.figure() ax = Axes3D(fig) trial_len = int((tot_time - window_size) / step_size) - 1 ran_inds = np.arange((trial_len * i), (trial_len * (i + 1))) this_cmap = Colormap('hsv') p = ax.scatter(off_f_red[ran_inds, 0], off_f_red[ran_inds, 1], off_f_red[ran_inds, 2], c=np.linspace(1, 255, len(ran_inds)), cmap='hsv') ax.plot(off_f_red[ran_inds, 0], off_f_red[ran_inds, 1], off_f_red[ran_inds, 2]) fig.colorbar(p) ## 2D animated scatter plot ########################### fig, ax = plt.subplots() x, y = off_f_red[:, 0], off_f_red[:, 1] sc = ax.scatter([], []) plt.xlim(min(x), max(x))
def plot_force_error_heatmap(ax, data_set, struct_types=struct_types, dyn_types=dyn_types, bad_data_traj_list=[], xbin_size=None, ybin_size=None, use_meV_y=False, use_meV_x=False, by_atom=False, cmap=cm.get_cmap('viridis')): scalex = 1 scaley = 1 if use_meV_x: scalex = 1000 if use_meV_y: scaley = 1000 def pick_bins(abin_size, A): if abin_size is None: abins = np.linspace(A.min(), A.max(), 100) else: abins = np.arange(A.min(), A.max(), abin_size) return abins #from matplotlib.ticker import MultipleLocator #ax.yaxis.set_major_locator(MultipleLocator(base=30)) #ax.yaxis.set_minor_locator(MultipleLocator(base=5)) import copy cmap_tweaked = copy.copy(cmap) from matplotlib.colors import Colormap Colormap.set_under(cmap_tweaked, color=(1, 1, 1, 0)) Colormap.set_over(cmap_tweaked, color=(1, 1, 1, 0)) fname = data_set[0] data_name = data_set[1] image_pairs = read_evaluation_data(filename=fname, struct_types=struct_types, dyn_types=dyn_types) cache_forces, data_forces = get_force_list(image_pairs) force_error_list = compute_force_error_list(cache_forces, data_forces) if by_atom: atom_force_norms = compute_atom_force_norms(data_forces) rms_force_error_by_atom = compute_rms_force_error_by_atom( cache_forces, data_forces) net_rms_force_error_by_atom = np.sqrt( np.mean(collapse_sub_lists(rms_force_error_by_atom)**2)) X = scalex * atom_force_norms Y = scaley * rms_force_error_by_atom error_rmse = scaley * net_rms_force_error_by_atom else: image_force_norms = compute_force_norms_by_image( data_forces) / np.sqrt(3) rms_force_error_by_image = compute_rms_force_error_by_image( cache_forces, data_forces) / np.sqrt(3) net_rms_force_error_by_image = np.sqrt( np.mean((rms_force_error_by_image)**2)) X = scalex * image_force_norms Y = scaley * rms_force_error_by_image error_rmse = scaley * net_rms_force_error_by_image xbins = pick_bins(xbin_size, X) ybins = pick_bins(ybin_size, Y) ax.hist2d(X, Y, bins=(xbins, ybins), vmin=1, cmap=cmap_tweaked) ax.set_title(data_name, fontsize=8) ax.minorticks_on() return error_rmse
def __init__(self, name, color, min_alpha = 0.0, max_alpha = 1.0, N=256): Colormap.__init__(self, name, N) self._color = color self._min_alpha = min_alpha self._max_alpha = max_alpha
} return pd.DataFrame(d) init_data() raw = row_data() cols = 3 rows = len(data) / cols + (1 if len(data) % cols != 0 else 0) colorFrom = '' colorTo = '' # with open('color.txt', 'r') as fin: # colorFrom, colorTo = fin.readline().split(' ') cmap = Colormap('current') # cmap.set_over(color=colorFrom) # cmap.set_under(color=colorTo) figure = plt.figure() def xy_by_plot(x, y): col = int(x + 0.5) row = int(y + 0.5) return col, row for i, key in enumerate(data): vals = data[key]
def plot_map(self, argv): self.geo = Geometry(model='load') (Lx, Ly) = self.geo.get_repeated_size(argv) Sx = 8 Sy = Sx * Ly / Lx fig = figure(num=' ', figsize=(Sx, Sy), dpi=80, facecolor='w', edgecolor='k') axes([0, 0, 1.0, 1.0]) #fig = figure(num=' ', figsize=(8*Lx/Ly, 8), dpi=80, facecolor='w', edgecolor='k') #axes([0,0,0.5,1.0]) #axes([0,0,1.0,1.0]) #data += 1.0 plt.set_cmap(Colormap('hot')) (data, nodes, triangulation) = self.get_data(argv) vmin = argv.setdefault('vmin', min(data)) vmax = argv.setdefault('vmax', max(data)) tripcolor(triangulation, np.array(data), shading='gouraud', norm=mpl.colors.Normalize(vmin=vmin, vmax=vmax), zorder=1) #colorbar(norm=mpl.colors.Normalize(vmin=min(data),vmax=max(data))) #Contour----- if argv.setdefault('iso_values', False): t = tricontour(triangulation, data, levels=np.linspace(vmin, vmax, 10), colors='black', linewidths=1.5) if argv.setdefault( 'streamlines', False ): # and (variable == 'fourier_flux' or variable == 'flux' ): n_lines = argv.setdefault( 'n_lines', 10) * self.Ny #assuming transport across x xi = np.linspace(-Lx * 0.5, Lx * 0.5, 300 * self.Nx) yi = np.linspace(-Ly * 0.5, Ly * 0.5, 300 * self.Ny) x = np.array(nodes)[:, 0] y = np.array(nodes)[:, 1] z = np.array(data).T[0] Fx = griddata((x, y), z, (xi[None, :], yi[:, None]), method='cubic') z = np.array(data).T[1] Fy = griddata((x, y), z, (xi[None, :], yi[:, None]), method='cubic') seed_points = np.array([ -Lx * 0.5 * 0.99 * np.ones(n_lines), np.linspace(-Ly * 0.5 * 0.98, Ly * 0.5 * 0.98, n_lines) ]) ss = streamplot(xi, yi, Fx, Fy, maxlength=1e8, start_points=seed_points.T, integration_direction='both', color='r', minlength=0.95, linewidth=1) if argv.setdefault('plot_interfaces', False): pp = self.geo.get_interface_point_couples(argv) axis('off') gca().invert_yaxis() xlim([-Lx * 0.5, Lx * 0.5]) ylim([-Ly * 0.5, Ly * 0.5]) gca().margins(x=0, y=0) axis('tight') axis('equal') savefig('fig.png', dpi=200) show()
def plot_force_angle_polar_heatmap( ax, data_set, struct_types=struct_types, dyn_types=dyn_types, bad_data_traj_list=[], theta_zero_location="S", xbin_size=None, ybin_size=None, use_meV_y=False, #use_meV_x = False, by_atom=True, cmap=cm.get_cmap('plasma')): scalex = 1 scaley = 1 #if use_meV_x: scalex = 1000 if use_meV_y: scaley = 1000 deg = 180 / np.pi def pick_bins(abin_size, A): if abin_size is None: abins = np.linspace(np.min(A), np.max(A), 100) else: abins = np.arange(np.min(A), np.max(A), abin_size) return abins if xbin_size is None: xbin_size = 2 xbins = np.arange(0, 180, xbin_size) from matplotlib.ticker import MultipleLocator #ax.yaxis.set_major_locator(MultipleLocator(base=30)) #ax.yaxis.set_minor_locator(MultipleLocator(base=5)) import copy cmap_tweaked = copy.copy(cmap) from matplotlib.colors import Colormap Colormap.set_under(cmap_tweaked, color=(1, 1, 1, 0)) Colormap.set_over(cmap_tweaked, color=(1, 1, 1, 0)) fname = data_set[0] data_name = data_set[1] image_pairs = read_evaluation_data(filename=fname, struct_types=struct_types, dyn_types=dyn_types) cache_forces, data_forces = get_force_list(image_pairs) force_error_list = compute_force_error_list(cache_forces, data_forces) if by_atom: force_norms_by_atom = compute_force_norms_by_atom(data_forces) rms_force_error_by_atom = compute_rms_force_error_by_atom( cache_forces, data_forces) #net_rms_force_error_by_atom = np.sqrt(np.mean( collapse_sub_lists(rms_force_error_by_atom)**2)) force_cosines_by_atom = compute_force_cosines_by_atom( cache_forces, data_forces) force_angles_by_atom = deg * np.arccos( collapse_sub_lists(force_cosines_by_atom)) mean_force_angles = np.mean(force_angles_by_atom) rms_force_angles = np.sqrt(np.mean((force_angles_by_atom)**2)) X = scalex * force_angles_by_atom Y = scaley * collapse_sub_lists(rms_force_error_by_atom) error_rmse = scaley * rms_force_angles error_mae = scaley * mean_force_angles else: image_force_norms = compute_force_norms_by_image( data_forces) / np.sqrt(3) rms_force_error_by_image = compute_rms_force_error_by_image( cache_forces, data_forces) / np.sqrt(3) net_rms_force_error_by_image = np.sqrt( np.mean((rms_force_error_by_image)**2)) X = scalex * image_force_norms Y = scaley * rms_force_error_by_image error_rmse = scaley * net_rms_force_error_by_image #xbins = pick_bins(xbin_size, X) ybins = pick_bins(ybin_size, Y) ax.hist2d(X / deg, Y, bins=(xbins / deg, ybins), vmin=1, cmap=cmap_tweaked) ax.set_title(data_name, fontsize=8) #ax_force_polar.legend(fontsize = 8) ax.set_thetamin(0) ax.set_thetamax(180) ax.set_theta_zero_location(theta_zero_location) ax.xaxis.set_major_locator(MultipleLocator(base=45 / deg)) #ax.xaxis.set_minor_locator(MultipleLocator(base=15/deg)) dtheta = 15 theta_grid = np.arange(0, 180 + dtheta / 2, dtheta) for theta in theta_grid: ax.axvline(theta / deg, color='grey', lw=0.8, zorder=-1) #ax.set_thetagrids() #ax.minorticks_on() return error_rmse, error_mae
def __call__(self, X, alpha=1.0, bytes=False): if self.bad_set: if not isinstance(X, numpy.ma.masked_array): X = numpy.ma.asarray(X) X.mask = ma.make_mask(~numpy.isfinite(X)) return Colormap.__call__(self, X, alpha, bytes)
def __init__(self, name, color, min_alpha=0.0, max_alpha=1.0, N=256): Colormap.__init__(self, name, N) self._color = color self._min_alpha = min_alpha self._max_alpha = max_alpha
def __init__(self, cmap, vmin=0, vmax=1): if not has_mpl: raise ImportError("Could not import all matplotlib dependencies!") if isinstance(cmap, str): Colormap.__init__(self, cmap, vmin, vmax) cmap = mpl_get_cmap(cmap) else: try: name = str(cmap.name) except: raise ValueError("The argument 'cmap' is of wrong type!") Colormap.__init__(self, name, vmin, vmax) # Obtain table to convert to .cpt: if 'colors' in cmap.__dict__.keys(): if isinstance(cmap.colors, list): N = len(cmap.colors) elif isinstance(cmap.colors, np.ndarray): N = cmap.colors.shape[0] else: raise ValueError("Data type not understood: " + str(type(cmap.colors))) self.cpt_table = np.zeros((N, 4)) self.cpt_table[:, 1:4] = cmap.colors self.cpt_table[:, 0] = np.linspace(0, 1, N) elif '_segmentdata' in cmap.__dict__.keys(): # Obtain the segments for all three colors: segs = [ np.array(cmap._segmentdata['red']), np.array(cmap._segmentdata['green']), np.array(cmap._segmentdata['blue']) ] changes = set([seg[0] for seg in segs[0]]) \ | set([seg[0] for seg in segs[1]]) \ | set([seg[0] for seg in segs[2]]) changes = np.sort(np.array(list(changes)))[1:] colors = [] colors += [[0, segs[0][0, 1], segs[1][0, 1], segs[2][0, 1]]] for x in changes: c0 = [0, 0, 0] c1 = [0, 0, 0] for k in range(3): id_ = np.argwhere(segs[k][:, 0] < x)[-1] if id_ < len(segs[k]): if segs[k][id_ + 1, 0] == x: # Red value changes at x: c0[k] = segs[k][id_ + 1, 1][0] c1[k] = segs[k][id_ + 1, 2][0] else: # Red value does not change at x. Interpolate linearly: x0 = segs[k][id_, 0][0] v0 = segs[k][id_, 2][0] x1 = segs[k][id_ + 1, 0][0] v1 = segs[k][id_ + 1, 1][0] c0[k] = (x - x0) / (x1 - x0) * v0 + (x1 - x) / ( x1 - x0) * v1 c1[k] = c0[k] colors += [[x, c0[0], c0[1], c0[2]]] if c0[0] != c1[0] or c0[0] != c1[0] or c0[0] != c1[0]: colors += [[x, c1[0], c1[1], c1[2]]] self.cpt_table = np.array(colors)
def plot_choropleth(fig, axg, gdf, column, cmap=cmap_turbo, vmin=None, vmax=None, norm=None, cticks=None, discrete=False, plot_kwargs={}, cbar_kwargs={}, cbar_pos={}): # colormap dmin, dmax = np.nanmin(gdf.loc[:, column].values), np.nanmax( gdf.loc[:, column].values) vmin = vmin if (vmin is not None) else dmin vmax = vmax if (vmax is not None) else dmax if cticks is None: k = cbar_kwargs.get('k', 10) cticks = np.linspace(vmin, vmax, k).tolist() if discrete: #only linear norm = BoundaryNorm(cticks, cmap.N) elif norm is None: norm = Normalize(vmin=vmin, vmax=vmax) if isinstance(cmap, str): cmap = Colormap(cmap) # add choropleth layer to fig gdf.plot(ax=axg, column=column, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax, **plot_kwargs) # plot colorbar cax = None if cbar_kwargs: # fig = plt.gcf() location = cbar_kwargs.pop('location', 'bottom') clabel = cbar_kwargs.pop('label', '') extend = cbar_kwargs.pop('extend', None) pad = cbar_pos.get('pad', 0.05) fraction = cbar_pos.get('fraction', 0.02) shrink = cbar_pos.get('shrink', 1) if extend == 'both' or (extend is None and ((dmax > vmax) and (dmin < vmin))): cbar_kwargs.update(extend='both', ticks=cticks, boundaries=[dmin] + cticks + [dmax] if discrete else None) elif extend == 'max' or (extend is None and dmax > vmax): cbar_kwargs.update(extend='max', ticks=cticks, boundaries=cticks + [dmax] if discrete else None) elif extend == 'min' or (extend is None and dmin < vmin): cbar_kwargs.update(extend='min', ticks=cticks, boundaries=[dmin] + cticks if discrete else None) else: cbar_kwargs.update(ticks=cticks, boundaries=cticks if discrete else None) gpos = axg.get_position() if location == 'right': cax = fig.add_axes([ gpos.x1 + pad, gpos.y0 + gpos.height * (1 - shrink) / 2., gpos.width * fraction, gpos.height * shrink ]) # new ax cbar = mpl.colorbar.Colorbar( cax, mpl.cm.ScalarMappable(cmap=cmap, norm=norm), **cbar_kwargs) cbar.ax.set_ylabel(clabel, rotation='vertical') elif location == 'bottom': cax = fig.add_axes([ gpos.x0 + gpos.width * (1 - shrink) / 2., gpos.y0 - pad, gpos.width * shrink, gpos.height * fraction ]) # new ax cbar = mpl.colorbar.Colorbar(cax, mpl.cm.ScalarMappable(cmap=cmap, norm=norm), orientation='horizontal', **cbar_kwargs) cbar.ax.set_xlabel(clabel) else: raise ValueError('unknown value for "location"') return cax
def set_bad(self, color='k', alpha = 1.0): self.bad_set = True self.bad_val = (color, alpha) Colormap.set_bad(self, color, alpha) if self.auto: self.update()
def __init__(self, name, color, N=256): Colormap.__init__(self, name, N) self.color = colorConverter.to_rgb(color)