def loadCSV(self, csvFN): """ attributePainter.loadCSV(csvFN) -- populate the class variables with the information in the csv file. in particular, this sets self.minval, self.norms csvFN: (string) the filename of the csv file containing the attribute you wish to paint on the residues; the file format is like 'chainID ('1,2,3,...Z' -- pymol allowed chain ids), residue number (int), value (float)\\n' lines starting with an octothorpe (#) will be ignored """ chains = {} for i,line in enumerate(open(csvFN).readlines(), 1): if line[0] != '#': cells = line.strip().split(',') chainID = re.sub(r'^\s+', '', cells[0]) try: resnum = int(re.sub(r'^\s+', '', cells[1])) value = float(re.sub(r'^\s+', '', cells[2])) if chainID in self.chains: self.chains[chainID][resnum] = value else: self.chains[chainID] = {resnum: value} except ValueError: print "Line number {} ({}) was rejected -- could not format".format(i, line) ranges = {chainID: (min(chain.values()), max(chain.values())) for chainID, chain in self.chains.iteritems()} self.norms = {chainID: Normalize(r[0], r[1]) for chainID, r in ranges.iteritems()} self.sm = {chainID: ScalarMappable(norm, self.cmap) for chainID, norm in self.norms.iteritems()} self.norms['global'] = Normalize(min([i[0] for i in ranges.values()]), max([i[1] for i in ranges.values()])) self.sm['global'] = ScalarMappable(self.norms['global'], self.cmap)
def frame(t: int): global temp, T_MIN, T_MAX if t >= len(temp): for i in range(len(temp), t + 1): temp = np.vstack((temp, [np.add(temp[-1], comp_gas)])) T_MIN, T_MAX = np.min(temp), np.max(temp) fig = plt.figure(num="Simulation [{0}] (x{1})".format(t, DT)) #* Gas ax_gas = fig.add_subplot(121) ax_gas.set_axis_off() fig_gas = ax_gas.matshow(gas, cmap="GnBu", aspect="equal") cb_gas = fig.colorbar(ScalarMappable(norm=Normalize(vmin=C_MIN, vmax=C_MAX), cmap="GnBu"), ax=ax_gas, cmap="GnBu", orientation="horizontal") ax_gas.set_title("Concentration en gaz [ppm]", weight="bold") #* Temperature ax_temp = fig.add_subplot(122) ax_temp.set_axis_off() fig_temp = ax_temp.matshow(temp[t], cmap="jet", aspect="equal") cb_temp = fig.colorbar(ScalarMappable(norm=Normalize(vmin=T_MIN, vmax=T_MAX), cmap="jet"), ax=ax_temp, cmap="jet", orientation="horizontal") ax_temp.set_title("Température [K]", weight="bold") plt.show()
def stats(): fig = plt.figure(num="Statistiques sur la simulation (x{0})".format(DT)) #* Gas ax_gas = fig.add_subplot(221) ax_gas.set_axis_off() fig_gas = ax_gas.matshow(gas, cmap="GnBu", aspect="equal") cb_gas = fig.colorbar(ScalarMappable(norm=Normalize(vmin=C_MIN, vmax=C_MAX), cmap="GnBu"), ax=ax_gas, cmap="GnBu") ax_gas.set_title("Concentration en gaz [ppm]", weight="bold") #* Temperature difference ax_gas = fig.add_subplot(222) ax_gas.set_axis_off() fig_gas = ax_gas.matshow(comp_gas, cmap="Reds", aspect="equal") cb_gas = fig.colorbar(ScalarMappable(norm=Normalize(vmin=np.min(comp_gas), vmax=np.max(comp_gas)), cmap="Reds"), ax=ax_gas, cmap="Reds") ax_gas.set_title("Différence de température [K]", weight="bold") #* Temperature mean mean_temp = [np.mean(temp[t]) for t in range(len(temp))] ax_temp = fig.add_subplot(212) fig_temp = ax_temp.plot(range(len(temp)), mean_temp, "o-r") ax_temp.grid(which="both") ax_temp.set_xlabel("Frame", weight="bold") ax_temp.set_ylabel("Température [K]", weight="bold") ax_temp.set_title("Température moyenne", weight="bold") plt.show()
def render_movie(self): '''Visualize the volume as a movie''' from matplotlib import animation from matplotlib.cm import ScalarMappable import matplotlib.pyplot as plt # # Some of this is from a recipe # http://jakevdp.github.io/blog/2013/05/12/ # embedding-matplotlib-animations/ # image_target, prob_target, seeds_target, seg_target = list( self.input()) image_volume = image_target.imread() prob_volume = prob_target.imread() seeds_volume = seeds_target.imread() perm = np.random.RandomState(1234).permutation( np.max(seeds_volume) + 1) seg_volume = seg_target.imread() figure = plt.figure(figsize=(self.size_x_inches, self.size_y_inches)) ax = figure.add_subplot(1, 1, 1) sm = ScalarMappable(cmap='jet') sm.set_array(np.unique(seeds_volume)) sm.autoscale() prob_sm = ScalarMappable(cmap='jet') prob_sm.set_array(np.linspace(0, 255, 256)) prob_sm.autoscale() offset = self.first_frame end = self.end_frame if self.end_frame != 0 else image_volume.shape[0] def init_fig(): ax.clear() ax.set_ylim(self.volume.height, 0) ax.set_xlim(0, self.volume.width) def animate(i1): i = i1 - offset rh_logger.logger.report_event("Processing frame %d" % i) ax.imshow(image_volume[i], cmap='gray') sv = sm.to_rgba(perm[seeds_volume[i]]) sv[seeds_volume[i] == 0, 3] = 0 ax.imshow(sv) sv = sm.to_rgba(perm[seg_volume[i]]) sv[seg_volume[i] == 0, 3] = 0 sv[:, :, 3] *= .4 ax.imshow(sv) prob = prob_sm.to_rgba(prob_volume[i]) prob[:, :, 3] *= .4 prob[prob_volume[i] < 128, 3] = 0 ax.imshow(prob) anim = animation.FuncAnimation(figure, animate, init_func=init_fig, frames=end - offset, interval=1) plt.close(figure) anim.save(self.output().path, fps=1, extra_args=['-vcodec', 'libx264'])
def update_plot(data): '''Update plot for animation.''' projections, name, target_position, centroid_position = data projection_xz, projection_yz, projection_xy = projections target_x, target_y, target_z = target_position centroid_x, centroid_y = centroid_position # Update target position and annotation from radar on plots. target_ant_xz.set_position(xy=(target_x, target_z)) target_pt_xz.set_data(target_x, target_z) target_ant_yz.set_position(xy=(target_y, target_z)) target_pt_yz.set_data(target_y, target_z) target_ant_xy.set_position(xy=(target_x, target_y)) target_pt_xy.set_data(target_x, target_y) # Update name and postion annotations of centroid from camera on plots centroid_ant_xz.set_text(s=name) centroid_ant_xz.set_position(xy=(centroid_x, target_z)) centroid_pt_xz.set_data(centroid_x, target_z) centroid_ant_yz.set_text(s=name) centroid_ant_yz.set_position(xy=(centroid_y, target_z)) centroid_pt_yz.set_data(centroid_y, target_z) centroid_ant_xy.set_text(s=name) centroid_ant_xy.set_position(xy=(centroid_x, centroid_y)) centroid_pt_xy.set_data(centroid_x, centroid_y) # Update image colors according to return signal strength on plots. sm = ScalarMappable(cmap='coolwarm') signal_pts_xz.set_color(sm.to_rgba(projection_xz.T.flatten())) sm = ScalarMappable(cmap='coolwarm') signal_pts_yz.set_color(sm.to_rgba(projection_yz.T.flatten())) # Scale xy image data relative to target distance. signal_pts_xy.set_extent( [v * target_z / (zmax - zmin) for v in [xmin, xmax, ymin, ymax]]) # Rotate xy image if radar horizontal since x and y axis are rotated 90 deg CCW. if RADAR_HORIZONTAL: projection_xy = np.rot90(projection_xy) sm = ScalarMappable(cmap='coolwarm') signal_pts_xy.set_data(sm.to_rgba(projection_xy)) return (signal_pts_xz, target_ant_xz, target_pt_xz, centroid_ant_xz, centroid_pt_xz, signal_pts_yz, target_ant_yz, target_pt_yz, centroid_ant_yz, centroid_pt_yz, signal_pts_xy, target_ant_xy, target_pt_xy, centroid_ant_xy, centroid_pt_xy)
def apply(self, data, mask): """ Apply the colorizer to a data/mask set. TODO: Clean this up a bit """ self.rgba = None if len(self.bands) == 1: # Singleband pseudocolor data = data[0, :, :] else: # Multiband RGB. No colorizing to do, just transpose the # data array and add the mask band. Mask may be discarded # later when using jpg as output, for example. self.rgba = np.dstack((np.transpose(data, (1, 2, 0)), mask)) return self.rgba if self.interp == 'linear': norm = Normalize(self.ranges[0], self.ranges[-1]) sm = ScalarMappable(norm=norm, cmap=self.colormap) self.rgba = sm.to_rgba(data, bytes=True) if self.interp == 'discrete': norm = BoundaryNorm(boundaries=self.ranges, ncolors=256) sm = ScalarMappable(norm=norm, cmap=self.colormap) self.rgba = sm.to_rgba(data, bytes=True) if self.interp == 'exact': norm = NoNorm() sm = ScalarMappable(norm=norm, cmap=self.colormap) # Copy and mask the entire array. tmp_data = data.copy() tmp_data.fill(0) tmp_mask = mask.copy() tmp_mask.fill(0) # Reclassify the data for n, r in enumerate(self.ranges): ix = np.logical_and((data == r), (mask == 255)) tmp_data[ix] = n + 1 tmp_mask[ix] = 255 self.rgba = sm.to_rgba(tmp_data, bytes=True) mask = tmp_mask self.rgba[:, :, 3] = mask return self.rgba
def discrete_colorbar(colors, labels=None, ax=None, cax=None): """ Add a discrete colorbar with custom colors to current axes. Parameters: colors: list of RGB tuple labels: list of tick labels assume ticks are at range(len(labels)) """ N = len(colors) vmin = 0 vmax = N - 1 norm = BoundaryNorm(np.arange(-0.5 + vmin, vmax + 1.5, 1), N) s = ScalarMappable(norm=norm, cmap=ListedColormap(colors)) s.set_array(range(N)) cb = plt.colorbar(mappable=s, ticks=range(vmin, vmax + 1), ax=ax, cax=cax) cb.set_norm(norm) plt.clim(-0.5 + vmin, vmax + 0.5) cbticks = plt.getp(cb.ax.axes, 'yticklines') plt.setp(cbticks, visible=False) if (labels is not None): cb.set_ticklabels(labels) return cb
def plot_XCO2(centre): import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from matplotlib.colors import Normalize from matplotlib.cm import ScalarMappable lats = np.loadtxt('../earth_data/XCO2_lats.txt') lons = np.loadtxt('../earth_data/XCO2_lons.txt') xco2 = np.loadtxt('../earth_data/XCO2.txt') lons, lats = np.meshgrid(lons, lats) sm = ScalarMappable(Normalize(vmin=392, vmax=408), cmap='RdYlBu_r') levs = np.linspace(392, 408, 256) clevs = [sm.to_rgba(lev) for lev in levs] projection = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l') projection.drawcoastlines() x, y = projection(lons, lats) ortho_mask = np.ma.masked_greater(x, 1e15).mask xco2_masked = np.ma.array(xco2, mask=ortho_mask) ctr = plt.contourf(x, y, xco2_masked, levs, colors=clevs, extend='both') cbar = plt.colorbar(ctr, orientation='horizontal') cbar.set_label('Xco$_2$ [ppm]') plt.show()
def setup_pattern(self, ax, ax2=None): for a in self.arts: a.remove() del a self.arts.clear() if self.ax is not None: self.ax.clear() ax.axis('equal') ax.axis('off') for xy in self.xys: self.arts.append( ax.fill(xy[:, 0], xy[:, 1], color=self.cmap.colors[0], edgecolor=None)[0]) self.ax = ax if ax2 is not None and ax2 != self.ax2: try: del self.norm self.colorbar.remove() del self.colorbar except Exception: pass self.norm = Normalize(-1, 1) mapb = ScalarMappable(self.norm, self.cmap) self.colorbar = ax.figure.colorbar(mapb, cax=ax2) self.ax2 = ax2 self.ax.figure.canvas.draw()
def calctime(dval, maxtime=50.0): logger = logging.getLogger('dataval') logger.info('Plotting calculation times for photometry...') for cadence in dval.cadences: star_vals = dval.search_database( select=['diagnostics.stamp_resizes', 'diagnostics.elaptime'], search=[ f'cadence={cadence:d}', f'diagnostics.elaptime <= {maxtime:f}' ]) if not star_vals: continue et = np.array([star['elaptime'] for star in star_vals], dtype='float64') resize = np.array([star['stamp_resizes'] for star in star_vals], dtype='int32') maxresize = int(np.max(resize)) fig, ax = plt.subplots(figsize=plt.figaspect(0.5)) norm = Normalize(vmin=-0.5, vmax=maxresize + 0.5) scalarMap = ScalarMappable(norm=norm, cmap=plt.get_cmap('tab10')) # Calculate KDE of full dataset: kde1 = KDE(et) kde1.fit(kernel='gau', gridsize=1024) # Calculate KDEs for different number of stamp resizes: for jj in range(maxresize + 1): kde_data = et[resize == jj] if len(kde_data): kde2 = KDE(kde_data) kde2.fit(kernel='gau', gridsize=1024) rgba_color = scalarMap.to_rgba(jj) ax.fill_between(kde2.support, 0, kde2.density, color=rgba_color, alpha=0.5, label=f'{jj:d} resizes') ax.plot(kde1.support, kde1.density, color='k', lw=2, label='All') ax.set_xlim([0, maxtime]) ax.set_ylim(bottom=0) ax.xaxis.set_major_locator(MultipleLocator(5)) ax.xaxis.set_minor_locator(MultipleLocator(1)) ax.set_xlabel('Calculation time (sec)') ax.legend(loc='upper right') fig.savefig(os.path.join(dval.outfolder, f'calctime_c{cadence:04d}')) if not dval.show: plt.close(fig)
def __setup_plot(self): formatter = ScalarFormatter(useOffset=False) gs = GridSpec(1, 2, width_ratios=[9.5, 0.5]) self.axes = self.figure.add_subplot(gs[0], facecolor=self.settings.background) self.axes.set_xlabel("Frequency (MHz)") self.axes.set_ylabel('Level (dB/Hz)') self.axes.xaxis.set_major_formatter(formatter) self.axes.yaxis.set_major_formatter(formatter) self.axes.xaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.yaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.set_xlim(self.settings.start, self.settings.stop) self.axes.set_ylim(-50, 0) self.bar_ax = self.figure.add_subplot(gs[1]) norm = Normalize(vmin=-50, vmax=0) # self.barBase = ColorbarBase(self.bar_ax, norm=norm) self.scalarMap = ScalarMappable(norm=norm) self.barBase = self.figure.colorbar(self.scalarMap, cax=self.bar_ax) self.set_colourmap_use(self.settings.colourMapUse) self.__setup_measure() self.__setup_overflow() self.hide_measure()
def __setup_plot(self): gs = GridSpec(1, 2, width_ratios=[9.5, 0.5]) self.axes = self.figure.add_subplot(gs[0], facecolor=self.settings.background) self.axes.set_xlabel("Frequency (MHz)") self.axes.set_ylabel('Time') numFormatter = ScalarFormatter(useOffset=False) timeFormatter = DateFormatter("%H:%M:%S") self.axes.xaxis.set_major_formatter(numFormatter) self.axes.yaxis.set_major_formatter(timeFormatter) self.axes.xaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.yaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.set_xlim(self.settings.start, self.settings.stop) now = time.time() self.axes.set_ylim(utc_to_mpl(now), utc_to_mpl(now - 10)) self.bar_ax = self.figure.add_subplot(gs[1]) norm = Normalize(vmin=-50, vmax=0) # self.barBase = ColorbarBase(self.bar, norm=norm, # cmap=cm.get_cmap(self.settings.colourMap)) self.scalarMap = ScalarMappable(norm=norm, cmap=cm.get_cmap( self.settings.colourMap)) self.barBase = self.figure.colorbar(self.scalarMap, cax=self.bar_ax) self.__setup_measure() self.__setup_overflow() self.hide_measure()
def cont_palette(values: np.ndarray) -> Tuple[np.ndarray, ScalarMappable]: cm = copy(plt.get_cmap(cmap)) cm.set_bad("grey") sm = ScalarMappable(cmap=cm, norm=Normalize(vmin=np.nanmin(values), vmax=np.nanmax(values))) return np.array([to_hex(v) for v in (sm.to_rgba(values))]), sm
def make_plot(self, val, cct, clm, cmap='jet', cmap_norm=None, cmap_vmin=None, cmap_vmax=None): # make color mapping smap = ScalarMappable(cmap_norm, cmap) smap.set_clim(cmap_vmin, cmap_vmax) smap.set_array(val) bin_colors = smap.to_rgba(val) # make patches patches = [] for i_c, i_clm in enumerate(clm): patches.append( Rectangle((i_clm[0], i_clm[2]), i_clm[1] - i_clm[0], i_clm[3] - i_clm[2])) patches_colle = PatchCollection(patches) patches_colle.set_edgecolor('face') patches_colle.set_facecolor(bin_colors) return patches_colle, smap
def __init__(self, n): from matplotlib.cm import ScalarMappable from matplotlib.colors import Normalize cmap = plt.get_cmap('hsv') norm = Normalize(vmin=0, vmax=n) self.value_set = set(range(0, n)) self.scalar_map = ScalarMappable(norm=norm, cmap=cmap)
def figcolorbar(fig: Figure, axes: List[Axes], cmap='viridis', vmin: Union[float, None] = None, vmax: Union[float, None] = None, **kwargs): """Creates generic colorbar for list of subplots in figure. Args: fig (Figure): Figure axes (List[Axes]): List of axes (subplots) cmap (str, optional): colormap name. Defaults to ``viridis``. vmin (Union[float, None], optional): Smallest value. Defaults to None. vmax (Union[float, None], optional): Largest values . Defaults to None. ``**kwargs``: parsed to colorbar function Returns: colorbar handle Last modified: Lucas Sawade, 2020.09.15 15.30 ([email protected]) """ norm = cl.Normalize(vmin=vmin, vmax=vmax, clip=False) c = fig.colorbar(ScalarMappable(norm=norm, cmap=cmap), ax=axes, **kwargs) return c
def clippedcolorbar(CS, **kwargs): from matplotlib.cm import ScalarMappable from numpy import arange, floor, ceil fig = CS.ax.get_figure() vmin = CS.get_clim()[0] vmax = CS.get_clim()[1] m = ScalarMappable(cmap=CS.get_cmap()) m.set_array(CS.get_array()) m.set_clim(CS.get_clim()) step = CS.levels[1] - CS.levels[0] cliplower = CS.zmin < vmin clipupper = CS.zmax > vmax noextend = 'extend' in kwargs.keys() and kwargs['extend'] == 'neither' # set the colorbar boundaries boundaries = arange( (floor(vmin / step) - 1 + 1 * (cliplower and noextend)) * step, (ceil(vmax / step) + 1 - 1 * (clipupper and noextend)) * step, step) kwargs['boundaries'] = boundaries # if the z-values are outside the colorbar range, add extend marker(s) # This behavior can be disabled by providing extend='neither' to the function call if not ('extend' in kwargs.keys()) or kwargs['extend'] in ['min', 'max']: extend_min = cliplower or ('extend' in kwargs.keys() and kwargs['extend'] == 'min') extend_max = clipupper or ('extend' in kwargs.keys() and kwargs['extend'] == 'max') if extend_min and extend_max: kwargs['extend'] = 'both' elif extend_min: kwargs['extend'] = 'min' elif extend_max: kwargs['extend'] = 'max' return fig.colorbar(m, **kwargs)
def make_cmap_sm_norm(d=None, clim=None, cmap=None): if cmap == 'red_blue': cmap = red_blue_cm() if cmap == 'banas_cm': if clim == None: cmap = banas_cm(np.min(d[:]), np.min(d[:]), np.max(d[:]), np.max(d[:])) elif len(clim) == 2: cmap = banas_cm(clim[0], clim[0], clim[1], clim[1]) elif len(clim) == 4: cmap = banas_cm(clim[0], clim[1], clim[2], clim[3]) elif cmap == 'banas_hsv_cm': if clim == None: cmap = banas_hsv_cm(np.min(d[:]), np.min(d[:]), np.max(d[:]), np.max(d[:])) elif len(clim) == 2: cmap = banas_hsv_cm(clim[0], clim[0], clim[1], clim[1]) elif len(clim) == 4: cmap = banas_hsv_cm(clim[0], clim[1], clim[2], clim[3]) norm = Normalize(vmin=clim[0], vmax=clim[-1], clip=False) sm = ScalarMappable(norm=norm, cmap=cmap) sm.set_clim(vmin=clim[0], vmax=clim[-1]) sm.set_array(np.array([0])) return cmap, sm, norm
def main(): rospy.init_node('publish_custom_point_cloud') publisher = rospy.Publisher('/custom_point_cloud', PointCloud2, queue_size=1000) map_publisher = rospy.Publisher('/map', PointCloud2, queue_size=1000) for all_points in pd.read_hdf( "/home/cglwn/Documents/Datasets/Michigan-NCLT/velodyne_data/2013-01-10-velodyne_hits.hdf", "velodyne_hits", chunksize=1000): grouped = all_points.groupby("unix_time") for time, points in grouped: header = Header(frame_id='/velodyne', stamp=rospy.Time.from_sec(time / 1e6)) intensity_cmap = ScalarMappable(cmap="viridis") rgb = intensity_cmap.to_rgba(points["intensity"] / 255.0)[:, :3] point_matrix = points[["LI_x", "LI_y", "LI_z"]].values point_matrix[:, 2] = -point_matrix[:, 2] # points_with_color = np.column_stack([point_matrix, rgb]) # point_cloud = pc2.create_cloud(header, FIELDS, points_with_color) # publisher.publish(point_cloud) res = get_tx_at_time(time) if res is not None: x, y, z, yaw, pitch, roll = res point_matrix = transform(point_matrix, x, y, z, yaw, pitch, roll) header = Header(frame_id='/map', stamp=rospy.Time.from_sec(time / 1e6)) points_with_color = np.column_stack([point_matrix, rgb]) point_cloud = pc2.create_cloud(header, FIELDS, points_with_color) map_publisher.publish(point_cloud)
def save_heatmap(data, name): """ получаем матрицу данных и имя для файла """ # Создаем массив 0, 1... 8 # для x и y x = np.arange(0, 8) y = np.arange(0, 8) # Библиотченая функция interp2d - возвращает интерполированную функцию # Можно поиграться с типами интерполяции f = interp2d(x, y, data, kind='linear') # Задаем координаты лдя интерполяции по x и y x_interpolated = np.linspace(0, 8, 128) y_interpolated = np.linspace(0, 8, 128) # Получаем интерполированные значения массива данных z_interpolated = f(x_interpolated, y_interpolated) # Выключаем показ осей на графике plt.axis('off') # Создаем картинку. Пробрасываем нормализацию - можешь менять ее # И цвет - 'plasma' fig = plt.imshow(z_interpolated, interpolation='none', cmap='plasma', norm=NORMALIZATION) # добавляем шкалу справа с тем же цветом и нормализацией plt.colorbar(ScalarMappable(norm=NORMALIZATION, cmap='plasma')) # Сохраняем картинку plt.savefig('./data/processed/%s.png' % name) # Чистим буфер (иначе картинки будут в памяти накладываться) plt.clf()
def create_heatmap(xs, ys, imageSize, blobSize, cmap): blob = Image.new('RGBA', (blobSize * 2, blobSize * 2), '#000000') blob.putalpha(0) colour = 255 / int(math.sqrt(len(xs))) draw = ImageDraw.Draw(blob) draw.ellipse((blobSize / 2, blobSize / 2, blobSize * 1.5, blobSize * 1.5), fill=(colour, colour, colour)) blob = blob.filter(ImageFilter.GaussianBlur(radius=blobSize / 2)) heat = Image.new('RGBA', (imageSize, imageSize), '#000000') heat.putalpha(0) xScale = float(imageSize - 1) / (max(xs) - min(xs)) yScale = float(imageSize - 1) / (min(ys) - max(ys)) xOff = min(xs) yOff = max(ys) for i in range(len(xs)): xPos = int((xs[i] - xOff) * xScale) yPos = int((ys[i] - yOff) * yScale) blobLoc = Image.new('RGBA', (imageSize, imageSize), '#000000') blobLoc.putalpha(0) blobLoc.paste(blob, (xPos - blobSize, yPos - blobSize), blob) heat = ImageChops.add(heat, blobLoc) norm = Normalize(vmin=min(min(heat.getdata())), vmax=max(max(heat.getdata()))) sm = ScalarMappable(norm, cmap) heatArray = pil_to_array(heat) rgba = sm.to_rgba(heatArray[:, :, 0], bytes=True) rgba[:, :, 3] = heatArray[:, :, 3] coloured = Image.fromarray(rgba, 'RGBA') return coloured
def show_elevation(self): """ Draw a contour plot of the elevation data. Due to the large size of the dataest, rhis takes quite a long time. """ from matplotlib.pyplot import colorbar, show from mpl_toolkits.basemap import Basemap from matplotlib.colors import Normalize from matplotlib.cm import ScalarMappable projection = Basemap(projection='cyl', resolution='c') projection.drawcoastlines() lons, lats = np.meshgrid(self.lons, self.lats) levs = np.linspace(-8000., 8000., 256) sm = ScalarMappable(Normalize(vmin=-8000., vmax=8000.), cmap='jet') clevs = [sm.to_rgba(lev) for lev in levs] elevctr = projection.contourf(lons, lats, self.elev, levs, colors=clevs, extend='both') cbar = colorbar(elevctr, orientation='horizontal', aspect=40) cbar.set_ticks(np.arange(-8000., 8001., 1000.)) cbar.set_label("Surface Elevation [m]") show()
def init_axis(ax, title, xlabel, ylabel): """Initialize axis labels.""" face_color = ScalarMappable(cmap='coolwarm').to_rgba(0) ax.set_title(title) ax.set_facecolor(face_color) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel)
def color_scatter(self, lats, lngs, values=None, colormap='coolwarm', size=None, marker=False, s=None, **kwargs): def rgb2hex(rgb): """ Convert RGBA or RGB to #RRGGBB """ rgb = list(rgb[0:3]) # remove alpha if present rgb = [int(c * 255) for c in rgb] hexcolor = '#%02x%02x%02x' % tuple(rgb) return hexcolor if values is None: colors = [None for _ in lats] else: cmap = plt.get_cmap(colormap) norm = Normalize(vmin=min(values), vmax=max(values)) scalar_map = ScalarMappable(norm=norm, cmap=cmap) colors = [rgb2hex(scalar_map.to_rgba(value)) for value in values] for lat, lon, c in zip(lats, lngs, colors): self.scatter(lats=[lat], lngs=[lon], c=c, size=size, marker=marker, s=s, **kwargs)
def _plot_colorbar(self, color_legend_ax: Axes, normalize): """ Plots a horizontal colorbar given the ax an normalize values Parameters ---------- color_legend_ax normalize Returns ------- None, updates color_legend_ax """ cmap = pl.get_cmap(self.cmap) import matplotlib.colorbar from matplotlib.cm import ScalarMappable mappable = ScalarMappable(norm=normalize, cmap=cmap) matplotlib.colorbar.Colorbar(color_legend_ax, mappable=mappable, orientation='horizontal') color_legend_ax.set_title(self.color_legend_title, fontsize='small') color_legend_ax.xaxis.set_tick_params(labelsize='small')
def apply_cmap(data, cmap="gray", clim="auto", bytes=False): """ Apply a matplotlib colormap to a 2D or 3D numpy array and return the rgba data in float or uint8 format. data : 2D or 3D numpy array cmap : string denoting a matplotlib colormap Colormap used for displaying frames from data. Defaults to 'gray'. clim : length-2 list, tuple, or ndarray, or string Upper and lower intensity limits to display from data. Defaults to 'auto' If clim='auto', the min and max of data will be used as the clim. Before applying the colormap, data will be clipped from clim[0] to clim[1]. bytes : bool, defaults to False If true, return values are uint8 in the range 0-255. If false, return values are float in the range 0-1 """ from matplotlib.colors import Normalize from matplotlib.cm import ScalarMappable from numpy import array if clim == "auto": clim = data.min(), data.max() sm = ScalarMappable(Normalize(*clim, clip=True), cmap) rgba = array([sm.to_rgba(d, bytes=bytes) for d in data]) return rgba
def plot_predicted(self, figsize): y_pred = np.reshape(a=self.y_pred_temp, newshape=self.ground_truth.shape) figure, axes = self.__plot_parameters(figsize=figsize) ground_truth_plot = sb.heatmap(data=y_pred, cmap=self.palette, cbar=False, square=True, xticklabels=False, yticklabels=False, ax=axes) ground_truth_plot.set(title=(f'{self.name} {self.model_name} ' f'Predicted Classification Map')) if self.remove_unlabeled: colormap = ListedColormap(self.palette[1:]) else: colormap = ListedColormap(self.palette) colorbar = figure.colorbar(mappable=ScalarMappable(cmap=colormap), ax=axes) colorbar_range = colorbar.vmax - colorbar.vmin num_labels = len(self.labels) colorbar.set_ticks([ colorbar.vmin + 0.5 * colorbar_range / num_labels + i * colorbar_range / num_labels for i in range(num_labels) ]) colorbar.set_ticklabels(self.labels) colorbar.outline.set_visible(False) colorbar.ax.invert_yaxis() figure.savefig(fname=f"{self.evaluate_CNN_path}/predicted-map.svg", format='svg') plt.close(fig=figure)
def render(self, model): # create a mapping from fertility values to colours colour_map = ScalarMappable(norm=Normalize( vmin=-0.5, vmax=np.max(model.grid.fertility) * 1.2), cmap='Greens') # create list of hex colour strings for each column of the grid colours = [] for x in range(self.grid_width): colours.append( to_hex(colour_map.to_rgba(model.grid.fertility[0, x]))) grid_state = defaultdict(list) for x in range(model.grid.width): for y in range(model.grid.height): portrayal = { "Shape": "rect", "x": x, "y": y, "w": 1, "h": 1, "Color": colours[x], "Filled": "true", "Layer": 0 } grid_state[0].append(portrayal) cell_objects = model.grid.get_cell_list_contents([(x, y)]) for obj in cell_objects: portrayal = self.portrayal_method(obj) if portrayal: portrayal["x"] = x portrayal["y"] = y grid_state[portrayal["Layer"]].append(portrayal) return grid_state
def plot_cluster_distribuition(graph): # https://stackoverflow.com/questions/64485434/how-to-plot-the-distribution-of-a-graphs-clustering-coefficient g_connected = graph.subgraph(max(nx.connected_components(graph))) list_cluster_coef = nx.clustering(g_connected) cmap = plt.get_cmap('autumn') norm = plt.Normalize(0, max(list_cluster_coef.values())) node_colors = [ cmap(norm(list_cluster_coef[node])) for node in g_connected.nodes ] fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(10, 10)) nx.draw_spring(g_connected, node_color=node_colors, with_labels=False, ax=ax1) fig.colorbar(ScalarMappable(cmap=cmap, norm=norm), label='Clustering', shrink=0.95, ax=ax1) ax2.hist(list_cluster_coef.values(), bins=10) ax2.set_xlabel('Clustering') ax2.set_ylabel('Frequency') plt.tight_layout() plt.show()
def plot_bar_colors_data(): y_value = 42000 mean_years = create_mean_years_values() yerr_values = create_yerr_values() years = [1992, 1993, 1994, 1995] x_positions = np.arange(len(years)) data_color = [8500., 20500., 15000., 42000.] data_color = [x / max(data_color) for x in data_color] my_cmap = plt.cm.get_cmap('bwr') colors = my_cmap(data_color) fig, ax = plt.subplots() bar_list = ax.bar(x_positions, mean_years, yerr=yerr_values, align='center', color=colors, edgecolor='black', capsize=10) sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0, max(data_color))) sm.set_array([]) cbar = fig.colorbar(sm) cbar.set_label('Over/Below the Yellow Line', rotation=270, labelpad=25) ax.axhline(y_value, color='y') ax.set_xticks(x_positions) ax.set_xticklabels(years)