我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.cm.get_cmap()。
def get_colors_from_matplotlib(ramp_name, num_colors=1<<8): """Returns a list of color breaks from the color ramps defined by Matplotlib. Args: ramp_name (str): The name of a matplotlib color ramp. See the matplotlib documentation for a list of names and details on each color ramp. num_colors (int, optional): The number of color breaks to derive from the named map. Returns: [int] """ try: import colortools import matplotlib.cm as mpc except: raise Exception('matplotlib>=2.0.0 and colortools>=0.1.2 required') ramp = mpc.get_cmap(ramp_name) return [struct.unpack('>L', bytes(map(lambda x: int(x*255), ramp(x / (num_colors - 1)))))[0] for x in range(0, num_colors)]
def _make_plot(self): x, y, data, C = self.x, self.y, self.data, self.C ax = self.axes[0] # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or 'BuGn' cmap = self.plt.cm.get_cmap(cmap) cb = self.kwds.pop('colorbar', True) if C is None: c_values = None else: c_values = data[C].values ax.hexbin(data[x].values, data[y].values, C=c_values, cmap=cmap, **self.kwds) if cb: img = ax.collections[0] self.fig.colorbar(img, ax=ax)
def show_hexbin(self, query): """shows hexbin plot over map Args: query: name of sql """ self.load() data = pd.read_sql_query(con=self.con, sql=query) points = self.gen_points(data, self.data_map) hx = self.base_map.hexbin( np.array([geom.x for geom in points]), np.array([geom.y for geom in points]), gridsize=275, bins='log', mincnt=1, edgecolor='none', alpha=1., lw=0.2, cmap=plt.get_cmap('afmhot')) plt.tight_layout() plt.show()
def split_colormap(self, colormap, n): """splits map by colour Args: colormap: chloropleth map n: colours Returns: portion of split map """ if type(colormap) == str: colormap = cm.get_cmap(colormap) colors = np.concatenate((np.linspace(0, 1., n), (0., 0., 0., 0.))) rgb_alpha = colormap(colors) indices = np.linspace(0, 1., n + 1) color_dict = {} for color, key in enumerate(('red', 'green', 'blue')): color_dict[key] = [(indices[i], rgb_alpha[i - 1, color], rgb_alpha[i, color]) for i in range(n + 1)] return LinearSegmentedColormap(colormap.name + "_%d" % n, color_dict, 1024)
def cmap_discretize(cmap, N): """ Return a discrete colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: number of colors. Example x = resize(arange(100), (5,100)) djet = cmap_discretize(cm.jet, 5) imshow(x, cmap=djet) """ if type(cmap) == str: cmap = get_cmap(cmap) colors_i = np.concatenate((np.linspace(0, 1., N), (0., 0., 0., 0.))) colors_rgba = cmap(colors_i) indices = np.linspace(0, 1., N + 1) cdict = {} for ki, key in enumerate(('red', 'green', 'blue')): cdict[key] = [(indices[i], colors_rgba[i - 1, ki], colors_rgba[i, ki]) for i in xrange(N + 1)] return LinearSegmentedColormap(cmap.name + "_%d" % N, cdict, 1024)
def __init__(self, dims): self.width = dims[0] self.height = dims[1] try: from plugins.fonts import Font except ImportError: from fonts import Font import numpy as np from matplotlib import cm from datetime import datetime self.dt = datetime self.np = np cmap = cm.get_cmap('magma', 256) self.cols = (cmap.colors * 255)[0:, :3].astype(np.uint8) self.minute = datetime.now().minute self.order = np.arange(0, 3) try: self.fnt = Font('slkscr.ttf', 16) except: import urllib print("Downloading font") urllib.urlretrieve('https://www.dropbox.com/s/adt959l9bx0ojlj/slkscr.ttf?dl=1', 'slkscr.ttf') self.fnt = Font('slkscr.ttf', 16)
def __init__(self, board_dimensions): self.board_dimensions = board_dimensions import numpy as np self.np = np def rbool(): return np.random.choice([True, False]) self.sorted = rbool() self.facing = rbool() self.face_in = rbool() try: from matplotlib import cm numcolors = 9012 color_maps = ['rainbow', 'flag', 'terrain', 'ocean', 'gist_earth', 'viridis', 'gnuplot', 'brg', 'cubehelix', 'CMRmap'] cmap = cm.get_cmap(np.random.choice(color_maps)) self.colors = np.array( [map(lambda x: int(x * 255), list(cmap(1. * i / numcolors))[:-1]) for i in range(numcolors)]) except ImportError: self.colors = np.random.randint(0, 255, [9012, 3]) self.pixels = self.np.zeros((self.board_dimensions[0], self.board_dimensions[1], 3)).astype(self.np.uint8)
def plotEval(image, segments, labels, est, outFilename): estImg = fillSegments(segments, est, labels) colormap = cm.get_cmap('jet') f, ax = plt.subplots(2, 1) ax[0].imshow(image) ax[0].set_title("Image") axx=ax[1].imshow(estImg, cmap=colormap) ax[1].set_title("EST") f.subplots_adjust(right=.8) cbar_ax = f.add_axes([0.85, 0.15, 0.05, 0.7]) f.colorbar(axx, cax=cbar_ax) plt.savefig(outFilename) plt.close(f)
def thetaE(): # plot theta-e # create figure plt.figure(figsize=(8,8)) theta = nc.variables['T'][time] #perturbation potential temperature (theta-t0) theta0 = nc.variables['T00'][0] #base state theta theta = theta[0] + theta0 # total theta psfchpa = conv.pa_to_hpa(psfc[time]) t2c = conv.k_to_c(t2[time]) #convert temp to celcius es = calc.calc_es(t2c) ws = calc.calc_ws(es, psfchpa) thetae = calc.calc_thetae(theta, t2[time], ws) clevs = np.arange(260,372,4) # set by max and min of data cs = m.contourf(x,y,thetae,clevs,cmap=cm.get_cmap('gist_ncar')) title = "Theta-e" ftitle = 'thetae-' cblabel = 'K' cbticks = True makeplot(cs,title,cblabel,clevs,cbticks,ftitle)
def h75lr(): # 700-500mb lapse rates # create figure plt.figure(figsize=(8,8)) pb = nc.variables['PB'][time] #base state pressure, Pa p = nc.variables['P'][time] # perturbation pressure, Pa totalp = pb + p # total pressure in Pa theta = nc.variables['T'][time] #perturbation potential temperature (theta-t0) theta0 = nc.variables['T00'][0] #base state theta totalTheta = theta + theta0 # total potential temp totalT= conv.k_to_c(calc.theta_to_temp(totalTheta, totalp)) # calc temp in deg C # interp temps to levels totalT700 = funcs.linear_interp(totalT,totalp,700) totalT500 = funcs.linear_interp(totalT,totalp,500) # calc h7-h5 lapse rates lr = totalT700 - totalT500 clevs = np.arange(5,10.5,.5) # conditionally unstable levels cs = m.contourf(x,y,lr,clevs,cmap=cm.get_cmap('gist_ncar')) title = "H7-H5 Lapse Rates" ftitle = 'h75lr-' cblabel = r'$\degree$C' cbticks = True makeplot(cs,title,cblabel,clevs,cbticks,ftitle)
def absvort500(): # plot 500mb absolute vorticity # create figure plt.figure(figsize=(8,8)) pb = nc.variables['PB'][time] #base state pressure, Pa p = nc.variables['P'][time] # perturbation pressure, Pa totalp = pb + p # total pressure in Pa U = funcs.unstagger(nc.variables['U'][time],'U') # U wind component UNSTAGGERED V = funcs.unstagger(nc.variables['V'][time],'V') # V wind component fcoriolis = calc.calc_fcoriolis(xlat[0]) uinterp = funcs.linear_interp(U,totalp,500) #interp to 500mb vinterp = funcs.linear_interp(V,totalp,500) vertvort = calc.calc_vertvort(uinterp, vinterp, dx) avort = vertvort + fcoriolis # absolute vorticity avort = np.multiply(avort, 1e5) # scale up for levels clevs = np.arange(-6, 52, 2) cs = m.contourf(x,y,avort,clevs,cmap=cm.get_cmap('gist_ncar')) title = '500mb Absolute Vorticity' ftitle = '500absvort-' cblabel = r'$10^{-5} s^{-1}$' cbticks = True makeplot(cs,title,cblabel,clevs,cbticks,ftitle)
def vertvol(): # plot the vertical velocity at levels. NEEDS CORRECTING TO VERTICAL MOTION OMEGA EQUATION W = funcs.unstagger(nc.variables['W'][time],'W') # unstaggered vertical velocity pb = nc.variables['PB'][time] #base state pressure, Pa p = nc.variables['P'][time] # perturbation pressure, Pa totalp = pb + p # total pressure in Pa levels = opt.lvl.split(',') # get list of levels for level in levels: plt.figure(figsize=(8,8)) #create fig for each plot level = int(level) # make it int Wfinal = funcs.linear_interp(W,totalp,level) # interpolate W to levels clevs = np.arange(-2.0,2.2,0.2) cs = m.contourf(x,y,Wfinal,clevs,cmap=cm.get_cmap('gist_ncar')) level = str(level) title = level+'mb Vertical Velocity' ftitle = level+'mbvv-' cblabel = r'$ms^{-1}$' cbticks = True makeplot(cs,title,cblabel,clevs,cbticks,ftitle)
def plot(self): plt.figure() cmap = cm.get_cmap() used_labels = self._get_occupied() num_labels = len(used_labels) label_colors = {} for idx,label in enumerate(used_labels): label_colors[label] = idx/(num_labels-1. if num_labels > 1 else 1.) for subfigidx,l in enumerate(self.labels_list): plt.subplot(len(self.labels_list),1,1+subfigidx) # TODO assuming data is 2D for label in used_labels: if label in l.z: plt.plot(l.data[l.z==label,0],l.data[l.z==label,1], color=cmap(label_colors[label]),ls='None',marker='x')
def _process_metric(self, ax, metric): if not metric.data.size: ax.tick_params(colors=(0, 0, 0, 0)) ax.set_axis_bgcolor(cm.get_cmap('viridis')(0)) divider = make_axes_locatable(ax) divider.append_axes('right', size='7%', pad=0.1).axis('off') return domain = self._domain(metric) categorical = self._is_categorical(metric.data) if metric.data.shape[1] == 1 and not categorical: self._plot_scalar(ax, domain, metric.data[:, 0]) elif metric.data.shape[1] == 1: indices = metric.data[:, 0].astype(int) min_, max_ = indices.min(), indices.max() count = np.eye(max_ - min_ + 1)[indices - min_] self._plot_distribution(ax, domain, count) elif metric.data.shape[1] > 1: self._plot_counts(ax, domain, metric.data)
def scalar_preprocess(img, **kwargs): """ vmin, vmax, clip, cmap """ vmin = kwargs.get('vmin') vmax = kwargs.get('vmax') clip = kwargs.get('clip') cmap = kwargs.get('cmap', 'jet') # TODO customization normalizer = mpl.colors.Normalize(vmin, vmax, clip) nimg = normalizer(img) cmap = cm.get_cmap(cmap) cimg = cmap(nimg)[:, :, :3] # ignore alpha simg = (255*cimg).astype(np.uint8) return simg
def assign_color(df, value_var, colormap): vmax = df[value_var].abs().max() vmin = vmax * -1 norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) df["color"] = df.apply(lambda s: mpl.colors.rgb2hex( cm.get_cmap(colormap)(norm(s[value_var]))), axis=1) return df
def assign_cat_color(df, cat_var, colormap): color = {} norm = mpl.colors.Normalize(vmin=0, vmax=len(df[cat_var].unique())-1) for i, cat in enumerate(df[cat_var].unique()): color[cat] = mpl.colors.rgb2hex(cm.get_cmap(colormap)(norm(i))) df["color"] = df.apply(lambda s: color[s[cat_var]], axis=1) return df
def get_colorbar_source(df, value_var, colormap): vmax = df[value_var].abs().max() vmin = vmax * -1 norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) value = np.linspace(vmin, vmax, num=50) color = [] for v in value: color.append(mpl.colors.rgb2hex(cm.get_cmap(colormap)(norm(v)))) return vmax*2/49.0, ColumnDataSource(data=dict(value=value, color=color))
def compute_node_colors(self): """Compute the node colors. Also computes the colorbar.""" data = [self.graph.node[n][self.node_color] for n in self.nodes] data_reduced = sorted(list(set(data))) dtype = infer_data_type(data) n_grps = num_discrete_groups(data) if dtype == 'categorical' or dtype == 'ordinal': cmap = get_cmap(cmaps['Accent_{0}'.format(n_grps)].mpl_colormap) elif dtype == 'continuous' and not is_data_diverging(data): cmap = get_cmap(cmaps['continuous'].mpl_colormap) elif dtype == 'continuous' and is_data_diverging(data): cmap = get_cmap(cmaps['diverging'].mpl_colormap) for d in data: idx = data_reduced.index(d) / n_grps self.node_colors.append(cmap(idx)) # Add colorbar if required. logging.debug('length of data_reduced: {0}'.format(len(data_reduced))) logging.debug('dtype: {0}'.format(dtype)) if len(data_reduced) > 1 and dtype == 'continuous': self.sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=min(data_reduced), # noqa vmax=max(data_reduced) # noqa ) ) self.sm._A = []
def plot_z2(f, fignum=None, range=None, color_map='gray'): # plt.figure(fignum) if range is None: plt.imshow(f, interpolation='nearest', cmap=cm.get_cmap(color_map)) else: plt.imshow(f, interpolation='nearest', cmap=cm.get_cmap(color_map), vmin=range[0], vmax=range[1]) plt.xticks(np.arange(f.shape[1]), [str(i) for i in np.arange(f.shape[1])]) plt.yticks(np.arange(f.shape[0]), [str(i) for i in np.arange(f.shape[0])])
def show_label_array(ax, label_array, cmap=None, aspect=None,interpolation='nearest',**kwargs): """ YG. Sep 26, 2017 Modified show_label_array(ax, label_array, cmap=None, **kwargs) from https://github.com/Nikea/xray-vision/blob/master/xray_vision/mpl_plotting/roi.py Display a labeled array nicely Additional kwargs are passed through to `ax.imshow`. If `vmin` is in kwargs, it is clipped to minimum of 0.5. Parameters ---------- ax : Axes The `Axes` object to add the artist too label_array: ndarray Expected to be an unsigned integer array. 0 is background, positive integers label region of interest cmap : str or colormap, optional Color map to use, defaults to 'Paired' Returns ------- img : AxesImage The artist added to the axes """ if cmap is None: cmap = 'viridis' #print(cmap) _cmap = copy.copy((mcm.get_cmap(cmap))) _cmap.set_under('w', 0) vmin = max(.5, kwargs.pop('vmin', .5)) im = ax.imshow(label_array, cmap=cmap, interpolation=interpolation, vmin=vmin, **kwargs) if aspect is None: ax.set_aspect(aspect='auto') #ax.set_aspect('equal') return im
def _make_cmap(cmap_name='jet', alpha=0.2, filter_ratio=0.5): """Create a colormap which will be used to adding color spans to text Parameters ---------- cmap_name : str name of colormap, see here for all possible values: http://matplotlib.org/users/colormaps.html alpha : float color's transparency filter_ratio : float make fully transparent (1 - filter_ratio) of the color bar Returns ------- matplotlib.colors.LinearSegmentedColormap final color map with transparency """ import matplotlib as mpl import matplotlib.cm as cm cmap = cm.get_cmap(cmap_name) # Extract colormap's colors and set new alpha cmap_array = cmap(np.arange(cmap.N)) N = cmap_array.shape[0] if filter_ratio is not None: if not 0 <= filter_ratio <= 1: raise ValueError('filter_ratio = {} must be in the [0, 1] range'.format(filter_ratio)) nf_ratio = 1 - filter_ratio cmap_array[:, -1] = 0.0 cmap_array[:int(nf_ratio*N / 2), -1] = alpha cmap_array[-int(nf_ratio*N / 2):, -1] = alpha else: cmap_array[:, -1] = alpha # Create new colormap from the array with modified alpha cmap_with_trancparency = mpl.colors.ListedColormap(cmap_array) return cmap_with_trancparency
def _extract_lookup_table(cmap_name): cmap = mcm.get_cmap(cmap_name) if not cmap._isinit: cmap._init() r = cmap._lut[:-3, 0] g = cmap._lut[:-3, 1] b = cmap._lut[:-3, 2] a = np.ones(b.shape) return [r, g, b, a]
def cmap_cycle(event_coll, event): """Change colormap""" cmap = ['arbre', 'algae', 'kamae', 'viridis', 'inferno', 'magma'] cmap = cm.get_cmap(random.choice(cmap)) event_coll.camera.cmap = np.array(cmap(np.linspace(0, 1, 256)), dtype=np.float32) event_coll.camera.cmap_new = True print("Setting colormap to {}".format(cmap.name)) return True
def __init__(self, position=(0.0, 0.0, 1.0), focus=(0.0, 0.0, 0.0), up=(0.0, 1.0, 0.0), fov=45.0, near_plane=0.01, far_plane=20.0, aspect_ratio=8.0/6.0): self.position = np.array(position) self.focus = np.array(focus) self.up = np.array(up) self.fov = fov self.near_plane = near_plane self.far_plane = far_plane self.aspect_ratio = aspect_ratio # set cmap cmap = cm.get_cmap(ytcfg.get("yt", "default_colormap")) self.cmap = np.array(cmap(np.linspace(0, 1, 256)), dtype=np.float32) self.cmap_min = 1e55 self.cmap_max = -1e55 self.cmap_log = True self.cmap_new = True self.view_matrix = np.zeros((4, 4), dtype=np.float32) self.projection_matrix = np.zeros((4, 4), dtype=np.float32) self.orientation = np.zeros((4, 4), dtype=np.float32) self.proj_func = get_perspective_matrix
def plot_interpolated(self, aperture_centers, aperture_means): """ This function ... :param aperture_centers: :param aperture_means: :return: """ x_values = np.array([center.x for center in aperture_centers]) y_values = np.array([center.y for center in aperture_centers]) x_ticks = np.arange(0, self.frame.xsize, 1) y_ticks = np.arange(0, self.frame.ysize, 1) z_grid = mlab.griddata(x_values, y_values, aperture_means, x_ticks, y_ticks) self.sky = Frame(z_grid) from matplotlib.backends import backend_agg as agg from matplotlib import cm # plot #fig = Figure() # create the figure fig = plt.figure() agg.FigureCanvasAgg(fig) # attach the rasterizer ax = fig.add_subplot(1, 1, 1) # make axes to plot on ax.set_title("Interpolated Contour Plot of Experimental Data") ax.set_xlabel("X") ax.set_ylabel("Y") cmap = cm.get_cmap("hot") # get the "hot" color map contourset = ax.contourf(x_ticks, y_ticks, z_grid, 10, cmap=cmap) cbar = fig.colorbar(contourset) cbar.set_ticks([0, 100]) fig.axes[-1].set_ylabel("Z") # last axes instance is the colorbar plt.show() # -----------------------------------------------------------------
def make_overlay(image, gt_prob): mycm = cm.get_cmap('bwr') overimage = mycm(gt_prob, bytes=True) output = 0.4*overimage[:,:,0:3] + 0.6*image return output
def make_overlay(image, gt_prob): mycm = cm.get_cmap('bwr') overimage = mycm(gt_prob, bytes=True) output = 0.4*overimage[:, :, 0:3] + 0.6*image return output
def _string_to_cmap(cm_name): """Return colormap given name. Parameters: cm_name (str): Name of colormap. Returns: `matplotlib.cm <http://matplotlib.org/api/cm_api.html>`_ (colormap) object """ if isinstance(cm_name, str): if 'linearlab' in cm_name: try: cmap, cmap_r = linearlab() except IOError: cmap = cm.viridis else: if '_r' in cm_name: cmap = cmap_r else: cmap = cm.get_cmap(cm_name) elif isinstance(cm_name, ListedColormap) or isinstance(cm_name, LinearSegmentedColormap): cmap = cm_name else: raise MarvinError('{} is not a valid cmap'.format(cm_name)) return cmap
def on_mappable_changed(self, mappable): """ Updates this colorbar to match the mappable's properties. Typically this is automatically registered as an event handler by :func:`colorbar_factory` and should not be called manually. """ self.set_cmap(mappable.get_cmap()) self.set_clim(mappable.get_clim()) self.update_normal(mappable)
def spikesplot_cb(position, cmap='viridis', fig=None): # Add colorbar if fig is None: fig = plt.gcf() cax = fig.add_axes(position) cb = ColorbarBase(cax, cmap=get_cmap(cmap), spacing='proportional', orientation='horizontal', drawedges=False) cb.set_ticks([0, 0.5, 1.0]) cb.set_ticklabels(['Inferior', '(axial slice)', 'Superior']) cb.outline.set_linewidth(0) cb.ax.xaxis.set_tick_params(width=0) return cax
def colormap_lut(color = 'viridis', ncolors = None): # build lookup table if color == 'r': pos = np.array([0.0, 1.0]) color = np.array([[0,0,0,255], [255,0,0,255]], dtype=np.ubyte) ncolors = 512; elif color =='g': pos = np.array([0.0, 1.0]) color = np.array([[0,0,0,255], [0,255,0,255]], dtype=np.ubyte) ncolors = 512; elif color =='b': pos = np.array([0.0, 1.0]) color = np.array([[0,0,0,255], [0,0,255,255]], dtype=np.ubyte) ncolors = 512; else: #pos = np.array([0.0, 0.25, 0.5, 0.75, 1.0]) #color = np.array([[0,0,255,255], [0,255,255,255], [0,255,0,255], [255,255,0,255], [255,0,0,255]], dtype=np.ubyte) #color = np.array([[0,0,128,255], [0,255,255,255], [0,255,0,255], [255,255,0,255], [128,0,0,255]], dtype=np.ubyte) cmap = cm.get_cmap(color); if ncolors is None: ncolors = cmap.N; pos = np.linspace(0.0, 1.0, ncolors); color = cmap(pos, bytes = True); cmap = pg.ColorMap(pos, color) return cmap.getLookupTable(0.0, 1.0, ncolors);
def nb_imshow(image, cmap='jet'): ''' Interactive equivalent of imshow for ipython notebook ''' colormap = cm.get_cmap(cmap) # choose any matplotlib colormap here grayp = [mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))] xr = Range1d(start=0, end=image.shape[1]) yr = Range1d(start=image.shape[0], end=0) p = bpl.figure(x_range=xr, y_range=yr) # p = bpl.figure(x_range=[0,image.shape[1]], y_range=[0,image.shape[0]]) # p.image(image=[image], x=0, y=0, dw=image.shape[1], dh=image.shape[0], palette=grayp) p.image(image=[image[::-1, :]], x=0, y=image.shape[0], dw=image.shape[1], dh=image.shape[0], palette=grayp) return p
def col_colors(df, col, num_bins=5, cmap='spectral', start=0.1, stop=0.9): """ Get a list of colors by binning a continuous variable column into quantiles Parameters ---------- df : pandas.DataFrame col : string the name of the column in the dataframe with the continuous variable num_bins : int how many quantiles cmap : string name of a colormap start : float where to start in the colorspace stop : float where to end in the colorspace Returns ------- colors : list """ col = df[df[col].notnull()][col] bins_used, categories = _recursive_category_gen(col, num_bins) if not bins_used == num_bins: log('Too many bins requested, using max bins possible. ' 'To avoid duplicate edges, ' + str(bins_used) + ' bins used.') color_list = [cm.get_cmap(cmap)(x) for x in np.linspace(start, stop, bins_used)] cleaned_categories = [int(cat) for cat in categories] colors = [color_list[cat] for cat in cleaned_categories] return colors
def get_colors(n, cmap='viridis', start=0., stop=1., alpha=1., return_hex=False): """ Return n-length list of RGBa colors from the passed colormap name and alpha. Parameters ---------- n : int number of colors cmap : string name of a colormap start : float where to start in the colorspace stop : float where to end in the colorspace alpha : float opacity, the alpha channel for the RGBa colors return_hex : bool if True, convert RGBa colors to a hexadecimal string Returns ------- colors : list """ colors = [cm.get_cmap(cmap)(x) for x in np.linspace(start, stop, n)] colors = [(r, g, b, alpha) for r, g, b, _ in colors] if return_hex: colors = rgb_color_list_to_hex(colors) return colors
def chloropleth(self, query, color = "Blues"): """shows a chloropleth map of crimes Args: query: name of sql """ self.load() data = pd.read_sql_query(con=self.con, sql=query) points = self.gen_points(data, self.data_map) self.data_map['count'] = self.data_map['poly'].map(lambda x: len(list(filter(prep(x).contains, points)))) self.data_map['density_m'] = self.data_map['count'] / self.data_map['area_m'] self.data_map['density_km'] = self.data_map['count'] / self.data_map['area_km'] self.data_map.replace(to_replace={'density_m': {0: np.nan}, 'density_km': {0: np.nan}}, inplace=True) breaks = nb( self.data_map[self.data_map['density_km'].notnull()].density_km.values, initial=300, k=5) jb = pd.DataFrame({'jenks_bins': breaks.yb}, index=self.data_map[self.data_map['density_km'].notnull()].index) self.data_map = self.data_map.join(jb) self.data_map.jenks_bins.fillna(-1, inplace=True) jenks_labels = ["<= %0.1f/km$^2$(%s communities)" % (b, c) for b, c in zip( breaks.bins, breaks.counts)] jenks_labels.insert(0, 'None (%s communities)' % len(self.data_map[self.data_map['density_km'].isnull()])) cmap = plt.get_cmap(color) self.data_map['patches'] = self.data_map['poly'].map(lambda x: PolygonPatch(x, ec='#555555', lw=.2, alpha=1., zorder=4)) pc = PatchCollection(self.data_map['patches'], match_original=True) norm = Normalize() pc.set_facecolor(cmap(norm(self.data_map['jenks_bins'].values))) self.ax.add_collection(pc) cb = self.gen_colorbar(colors=len(jenks_labels), color_map=cmap, shrink=0.5, labels=jenks_labels) cb.ax.tick_params(labelsize=6) plt.tight_layout() plt.show()
def get_colormap_for_boardings(cls, max_n_boardings=None): n_default = 5 if max_n_boardings in [float('nan'), None]: max_n_boardings = n_default from matplotlib import cm cmap = cm.get_cmap("cubehelix_r") start = 0.1 end = 0.9 if max_n_boardings is 0: step = 0 else: divider = max(n_default, max_n_boardings) step = (end - start) / divider truncated = _truncate_colormap(cmap, start, start + step * max_n_boardings) return truncated
def plot_2d_input_weights(): name = 'XeAe' weights = get_2d_input_weights() fig = b2.figure(fig_num, figsize = (18, 18)) im2 = b2.imshow(weights, interpolation = "nearest", vmin = 0, vmax = wmax_ee, cmap = cmap.get_cmap('hot_r')) b2.colorbar(im2) b2.title('weights of connection' + name) fig.canvas.draw() return im2, fig
def colorbar(cmap="jet", cm_min=0, cm_max=1): if isinstance(cmap, str): cmap = cmget_cmap(cmap) norm = matplotlibpyplotNormalize(cm_min, cm_max) mappable = cmScalarMappable(cmap=cmap, norm=norm) mappable._A = [] return cmap, norm, mappable
def _analyze_correlation(csv_filepath): """ Analyze and visualize the correlation of features. Parameters ---------- csv_filepath : str Path to a CSV file which points to images """ import pandas as pd from matplotlib import pyplot as plt from matplotlib import cm as cm symbol_id2index, labels = generate_index(csv_filepath) data, y, s = load_images(csv_filepath, symbol_id2index, one_hot=False, flatten=True) df = pd.DataFrame(data=data) logging.info("Data loaded. Start correlation calculation. Takes 1.5h.") fig = plt.figure() ax1 = fig.add_subplot(111) # Where we want the ticks, in pixel locations ticks = np.linspace(0, 1024, 17) # What those pixel locations correspond to in data coordinates. # Also set the float format here ax1.set_xticks(ticks) ax1.set_yticks(ticks) labels = ax1.get_xticklabels() plt.setp(labels, rotation=30) cmap = cm.get_cmap('viridis', 30) cax = ax1.imshow(df.corr(), interpolation="nearest", cmap=cmap) ax1.grid(True) # Add colorbar, make sure to specify tick locations to match desired # ticklabels fig.colorbar(cax, ticks=[-0.15, 0, 0.15, 0.30, 0.45, 0.60, 0.75, 0.90, 1]) filename = '{}.pdf'.format('feature-correlation') plt.savefig(filename)
def build_map_nmf(df_map, m, coords, info, title, CrimePatterns): # plt.clf() fig = plt.figure() ax = fig.add_subplot(111, axisbg='w', frame_on=True) # draw wards with grey outlines norm = Normalize() for i in xrange(5): color = colormaps[i] cmap = plt.get_cmap(color) pc = PatchCollection(df_map[df_map['class'] == i+1]['patches'], match_original=True, alpha=0.8) pc.set_facecolor(cmap(norm(df_map.loc[(df_map['class'] == i+1), i].values))) ax.add_collection(pc) pc = PatchCollection(df_map[df_map['class'] == 0]['patches'], match_original=True, alpha=0.2) pc.set_facecolor('grey') ax.add_collection(pc) x, y = m(coords[0] + 0.02, coords[1] + 1.0) details = plt.annotate(info, xy=(x, y), size=24, color='#555555') # Draw a map scale m.drawmapscale( coords[0] + 0.2, coords[1] + 0.95, coords[0], coords[1], 20., fontsize=8, barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', units='mi', zorder=5) legend_patches = [] for i in range(6): legend_patches.append(mpatches.Patch(color=colors[i], label=CrimePatterns[i])) plt.legend(handles=legend_patches, loc='lower right') x1, y1 = m(coords[0] + 0.05, 33.62) colorinfo = 'Color represent each cluster of community;\nBrightness represent the severities of crime in each community' plt.annotate(colorinfo, xy=(x1, y1), size=16, color='#555555') plt.tight_layout() fig.set_size_inches(12, 13) plt.savefig(title, dpi=300, alpha=True)
def __init__(self, dims): self.width = dims[0] self.height = dims[1] import numpy as np from matplotlib import cm from itertools import cycle self.np = np color_maps = ['inferno', 'gnuplot', 'magma', 'viridis', 'plasma', 'cubehelix', 'gnuplot2', 'ocean', 'terrain', 'CMRmap', 'nipy_spectral'] maps = [ np.array(map(lambda i: (np.array(cm.get_cmap(x, 256)(i)[:-1]) * 255).astype(np.uint8), np.arange(0, 256))) for x in color_maps] # tup = [] # for m in maps: # tup.extend([m, m[::-1]]) tup = ( maps[0], maps[0][::-1], maps[1], maps[1][::-1], maps[2], maps[2][::-1], maps[5], maps[5][::-1], maps[3], maps[4][::-1], maps[6], maps[7][::-1], maps[8], maps[9][::-1], maps[10], maps[10][::-1]) self.cols = np.concatenate(tup) self.cols = np.concatenate((self.cols, self.cols[::-1])) self.step = 0 # print("Colors length:", len(self.cols)) denoms = np.cos(np.arange(0, 3 * np.pi, 0.01)) + (2*np.pi) self.denom = cycle(denoms) self.up = True self.half_len = len(self.cols) / 64. # print("Half length", self.half_len) self.init_gpu()
def _n_colors(n, bytes_=False, cmap='hsv'): """Produce a list of n unique RGBA color tuples based on a colormap Parameters ---------- n : int Number of colors. bytes : bool Return colors as integers values between 0 and 255 (instead of floats between 0 and 1). cmap : str Which colormap to use. Returns ------- colors : array, shape (n, 4) RGBA color values. """ n_max = 2 ** 10 if n > n_max: raise NotImplementedError("Can't produce more than %i unique " "colors" % n_max) from matplotlib.cm import get_cmap cm = get_cmap(cmap, n_max) pos = np.linspace(0, 1, n, False) colors = cm(pos, bytes=bytes_) if bytes_: # make sure colors are unique for ii, c in enumerate(colors): if np.any(np.all(colors[:ii] == c, 1)): raise RuntimeError('Could not get %d unique colors from %s ' 'colormap. Try using a different colormap.' % (n, cmap)) return colors