def olr_r(): n_colors=36 olr_map =[cm.gist_yarg(cc) for cc in range(5*n_colors,0,-5)] olr_coltbl = ListedColormap(olr_map,name = 'orl_coltbl',N=n_colors) #olr_coltbl.set_bad(color='gray') olr_coltbl.set_bad(color= olr_coltbl.colors[0]) return olr_coltbl
def plot(): """Do plotting work""" cmap1 = plt.get_cmap('inferno_r') colors = list(cmap1(np.arange(10) / 10.)) cmap2 = plt.get_cmap('Pastel1') colors.extend(list(cmap2(np.arange(2) / 2.))) cmap = ListedColormap(colors) cmap.set_under('tan') cmap.set_over('white') minval = np.load('minval.npy') maxval = np.load('maxval.npy') diff = maxval - minval lons = np.load('lons.npy') lats = np.load('lats.npy') mp = MapPlot(sector='midwest', statebordercolor='white', title=(r"Diff between coldest wind chill and warmest " "air temp 29 Jan - 3 Feb 2019"), subtitle=("based on hourly NCEP Real-Time Mesoscale Analysis " "(RTMA) ending midnight CST")) levels = list(range(0, 101, 10)) levels.extend([105, 110]) mp.pcolormesh(lons, lats, diff, levels, cmap=cmap, clip_on=False, units=r"$^\circ$F", spacing='proportional') mp.postprocess(filename='test.png')
def get_planck_cmap(): from matplotlib.colors import ListedColormap colombi1_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt")/255.) colombi1_cmap.set_bad("gray") # color of missing pixels colombi1_cmap.set_under("white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colombi1_cmap) return colombi1_cmap
def load_colormap(filename): """Load a colormap defined in a text file filename is the .txt file name located in the data/ path, not the full path. list_available_colormaps() lists the available color tables """ try: if rank == 0: vals = np.loadtxt(os.path.join(DATA_PATH, filename))/255.0 n_vals = len(vals) else: vals = None if par.use_mpi: vals = mpi.COMM_WORLD.bcast(vals, root=0) colormap = ListedColormap(vals) except exceptions.IOError: print("Cannot load colormap, available colormaps: \n* " + "\n* ".join(list_available_colormaps())) raise # color of missing pixels colormap.set_bad("gray") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colormap) colormap.set_under("white") return colormap
def main(): """ Plot the data using the row_labels as, you guessed it, row labels and the data_dict as columns. The plot will be saved as input_file.png with the previous extension removed. """ input_file = sys.argv[1] row_labels, data_dict = ParseFile(input_file) # Get the data needed. df = pd.DataFrame(data_dict, index=row_labels) # Create the dataframe. # EDIT THIS TO CHANGE FIGURE SIZE. plt.figure(figsize=(8, 11), dpi=1200) # Set colors [-5 to 5]. Can use html hex codes, recognized html colors, or rgb triplets. colors = ['#8c510a', "#bf812d", "#f5f5f5", "#f5f5f5", "#80cdc1", "#01665e"] cmap = ListedColormap(colors, name="cmap", N=6) # Change N if you have a greater range. # Set colors for over/under the bound limits. cmap.set_over("#003c30") cmap.set_under("#543005") bounds = [-20, -10, -3, 0, 3, 10, 20] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # Create the plot without y axis labels. Change 'extend' to 'both' or 'min' to make cbar extend # in opposite direction. heatmap = sns.heatmap(df, cbar=True, cbar_kws={'extend':'max'} ,cmap=cmap, norm=norm, yticklabels=False) plt.xticks(rotation=90) plt.title(input_file.split(".")[0]) out_name = input_file.split(".")[0] + ".pdf" # EDIT extension to change output format. heatmap.figure.savefig(out_name)
def planck_color_map(self): ''' Itab = [ 0, 13, 26, 39, 52, 65, 76, 77, 88, 101, 114, 127, 140, 153, 166, 179, 192, 205, 218, 231, 255] Rtab = [ 0, 10, 30, 80, 191, 228, 241, 241, 245, 248, 249.9, 242.25,204, 165, 114, 127.5, 178.5, 204, 229.5, 242.25, 252.45] Gtab = [ 0, 20, 184, 235, 239, 240, 241, 241, 240, 235, 204, 153, 76.5, 32, 0, 127.5, 178.5, 204, 229.5, 242.25, 252.45] Btab = [ 255, 255, 255, 255, 250, 245, 212, 212, 175, 130, 38.25, 12.75, 0, 32, 32, 153, 204, 229.5, 242.25, 249.9, 255] ncolors = 256 ii = np.arange(ncolors, dtype=np.float32) R = np.interp(ii, Itab, Rtab) G = np.interp(ii, Itab, Rtab) B = np.interp(ii, Itab, Rtab) ''' cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.) cmap.set_bad("darkgray") cmap.set_under("white") return cmap
def planck_color_map(self): cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.) cmap.set_bad("darkgray") cmap.set_under("white") return cmap
def load_colormap(filename): """Load a colormap defined in a text file filename is the .txt file name located in the data/ path, not the full path. list_available_colormaps() lists the available color tables """ try: colormap = ListedColormap(np.loadtxt(os.path.join(DATA_PATH, filename))/255.) except IOError: print("Cannot load colormap, available colormaps: \n* " + "\n* ".join(list_available_colormaps())) raise colormap.set_bad("gray") # color of missing pixels colormap.set_under("white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colormap) return colormap
def create_colormap(self, ticks, prec=1e-6): ncolor_p = len(np.where(ticks > prec)[0]) + 1 # including zero ncolor_n = len(np.where(ticks < -prec)[0]) + 1 # including zero colors_interpolated_p = create_colors_interpolated(self._colors_p, ncolor_p) colors_interpolated_n = create_colors_interpolated(self._colors_n, ncolor_n) colors = np.vstack(( colors_interpolated_n, colors_interpolated_p, )) colors = convert_white_to_transparent(colors) print("colors:") print(colors) cmap = ListedColormap(colors[1:-1]) cmap.set_under(colors[ 0]) cmap.set_over (colors[-1]) return cmap
def pycmap(gacmap): from matplotlib.colors import ListedColormap from numpy import vstack r = gacmap.table['r'] g = gacmap.table['g'] b = gacmap.table['b'] rt = ListedColormap(vstack((r, g, b)).T) rt.set_over((r[-1], g[-1], b[-1])) rt.set_under((r[0], g[0], b[0])) rt.set_bad(color='k', alpha=0) return rt
def main(): figure = plt.figure() basemap, lons2d, lats2d = get_basemap_and_coords() lons2d[lons2d > 180] -= 360 x0, y0 = basemap(lons2d, lats2d) dx = x0[1, 0] - x0[0, 0] dy = y0[0, 1] - y0[0, 0] x1 = x0 - dx / 2.0 y1 = y0 - dy / 2.0 permafrost_kind_field = get_permafrost_mask(lons2d, lats2d) cmap = ListedColormap(["r", "b", "y", "c"]) cmap.set_over("w") cmap.set_under("w") # permafrost_kind_field = np.ma.masked_where(permafrost_kind_field == 0, permafrost_kind_field) ax_map = plt.gca() # img = basemap.pcolormesh(x1, y1, permafrost_kind_field, ax = ax_map, vmin = 0.5, vmax = 4.5, cmap = cmap ) permafrost_kind_field = maskoceans(lons2d, lats2d, permafrost_kind_field) img = basemap.contourf(x0, y0, permafrost_kind_field, levels=np.arange(0.5, 5, 0.5), cmap=cmap) divider = make_axes_locatable(ax_map) cax = divider.append_axes("bottom", "5%", pad="3%") cb = plt.colorbar(img, ticks=MultipleLocator(), cax=cax, orientation="horizontal") basemap.contour(x0, y0, permafrost_kind_field, ax=ax_map, levels=list(range(6)), linewidths=0.5, colors="k") basemap.drawcoastlines(ax=ax_map) plt.savefig("test.png") # gdal.Dataset. # TODO: implement pass
def create_colormap_old_2(self, values, prec=1e-6): color_p = self._color_p color_n = self._color_n ncolor_p = len(np.where(values > prec)[0]) ncolor_n = len(np.where(values < -prec)[0]) color_list_0 = np.array([[0.0, 0.0, 0.0, 0.0]]) color_list_n = self.create_color_list(color_n, ncolor_n) color_list_n = color_list_n[::-1] color_list_n = np.vstack((color_list_n, color_list_0)) color_list_p = self.create_color_list(color_p, ncolor_p) color_list_p = np.vstack((color_list_0, color_list_p)) color_list = np.vstack((color_list_n, color_list_p)) color_list = self.convert_white_to_transparent(color_list) print("color_list:") print(color_list) cmap = ListedColormap(color_list[1:-1]) cmap.set_under(color_list[0]) cmap.set_over(color_list[-1]) return cmap
from setup_matplotlib import * import healpy as hp m = hp.ma(hp.read_map("../../data/wmap_band_iqumap_r9_7yr_W_v4.fits", 0)) * 1e3 # muK nside = hp.npix2nside(len(m)) # setup colormap from matplotlib.colors import ListedColormap colombi1_cmap = ListedColormap(np.loadtxt("../../data/parchment1.dat")/255.) colombi1_cmap.set_bad("gray") # color of missing pixels # using directly matplotlib instead of mollview has higher # quality output, I plan to merge this into healpy # ratio is always 1/2 xsize = 2000 ysize = xsize/2. unit = r"$\mathrm{\mu K}$" # this is the mollview min and max vmin = -1e3; vmax = 1e3 theta = np.linspace(np.pi, 0, ysize) phi = np.linspace(-np.pi, np.pi, xsize) longitude = np.radians(np.linspace(-180, 180, xsize)) latitude = np.radians(np.linspace(-90, 90, ysize)) # project the map to a rectangular matrix xsize x ysize PHI, THETA = np.meshgrid(phi, theta) grid_pix = hp.ang2pix(nside, THETA, PHI)
from setup_matplotlib import * import healpy as hp m = hp.ma(hp.read_map("../../data/wmap_band_iqumap_r9_7yr_W_v4.fits", 0)) * 1e3 # muK nside = hp.npix2nside(len(m)) # setup colormap from matplotlib.colors import ListedColormap colombi1_cmap = ListedColormap(np.loadtxt("../../data/parchment1.dat") / 255.0) colombi1_cmap.set_bad("gray") # color of missing pixels colombi1_cmap.set_under("white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colombi1_cmap) use_mask = False # using directly matplotlib instead of mollview has higher # quality output, I plan to merge this into healpy # ratio is always 1/2 xsize = 2000 ysize = xsize / 2.0 unit = r"$\mathrm{\mu K}$" # this is the mollview min and max vmin = -1e3 vmax = 1e3 theta = np.linspace(np.pi, 0, ysize) phi = np.linspace(-np.pi, np.pi, xsize)
def plot_mult_decision_boundary(ax, X, y, k, scaled=True, title='Title', xlabel='xlabel', ylabel='ylabel', hard_class=True): """Plot the decision boundary of a kNN classifier. Builds and fits a sklearn kNN classifier internally. X must contain only 2 continuous features. Function modeled on sci-kit learn example. Parameters ---------- ax: Matplotlib axes object The plot to draw the data and boundary on X: numpy array Training data y: numpy array Target labels k: int The number of neighbors that get a vote. scaled: boolean, optional (default=True) If true scales the features, else uses features in original units title: string, optional (default = 'Title') A string for the title of the plot xlabel: string, optional (default = 'xlabel') A string for the label on the x-axis of the plot ylabel: string, optional (default = 'ylabel') A string for the label on the y-axis of the plot hard_class: boolean, optional (default = True) Use hard (deterministic) boundaries vs. soft (probabilistic) boundaries Returns ------- None """ x_mesh_step_size = 0.1 y_mesh_step_size = 0.01 #Hard code in colors for classes, one class in red, one in blue bg_colors = np.array( [np.array([255, 150, 150]) / 255, np.array([150, 150, 255]) / 255]) cmap_light = ListedColormap(bg_colors) cmap_bold = ListedColormap(['#FF0000', '#0000FF']) #Build a kNN classifier clf = neighbors.KNeighborsClassifier(n_neighbors=k, weights='uniform') if scaled: #Build pipeline to scale features clf = make_pipeline(StandardScaler(), clf) clf.fit(X, y) else: clf.fit(X, y) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = 45, 85 y_min, y_max = 2, 4 xx, yy = np.meshgrid(np.arange(x_min, x_max, x_mesh_step_size), np.arange(y_min, y_max, y_mesh_step_size)) if hard_class: dec_boundary = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) ax.pcolormesh(xx, yy, dec_boundary, cmap=cmap_light) ax.scatter(X[:, 0], X[:, 1], c='black', cmap=cmap_bold) else: dec_boundary = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()]) colors = dec_boundary.dot(bg_colors) ax.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) ax.imshow(colors.reshape(200, 400, 3), origin="lower", aspect="auto", extent=(x_min, x_max, y_min, y_max)) ax.set_title(title + ", k={0}, scaled={1}".format(k, scaled)) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_xlim((x_min, x_max)) ax.set_ylim((y_min, y_max))
fig2 = plt.figure(figsize=(4, 2)) m2 = Basemap(projection='merc', llcrnrlon=-77.4614, llcrnrlat=38.72096, urcrnrlon=-76.7381, urcrnrlat=39.17577, resolution='h') ny2 = freq.shape[0] nx2 = freq.shape[1] lons2, lats2 = m2.makegrid(nx2, ny2) # get lat/lons of ny by nx evenly space grid. x2, y2 = m2(lons2, lats2) mdata2 = maskoceans(lons2, lats2, freq) cMAP = ListedColormap([ '#0080ff', '#00bfff', '#00ffff', '#009933', '#33cc33', '#c6ff1a', '#ffff00', '#ffbf00', '#ff8000', '#ff4000' ]) clevs = np.arange(0, 5.5, 0.5) cMAP.set_over('#cc0000') m2.drawcoastlines() m2.drawcounties(linewidth=0.4) parallels = np.arange(0., 90, 0.1) m2.drawparallels(parallels, labels=[1, 0, 0, 0], dashes=[2, 900], fontsize=10, linewidth=0.4) meridians = np.arange(180., 360., 0.2) m2.drawmeridians(meridians,
# Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid( np.arange(start=X_set[:, 0].min() - 1, stop=X_set[:, 0].max() + 1, step=0.01), np.arange(start=X_set[:, 1].min() - 1, stop=X_set[:, 1].max() + 1, step=0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha=0.75, cmap=ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c=ListedColormap(('red', 'green'))(i), label=j) plt.title('Kernel SVM (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() # Visualising the Test set results from matplotlib.colors import ListedColormap
def test_DataSet_plotQPlane(): plt.ioff() import matplotlib matplotlib.use('Agg') convertFiles = [os.path.join(dataPath,'camea2018n000137.hdf')]#'TestData/ManuallyChangedData/A3.hdf')] Datset = DataSet(dataFiles = convertFiles) Datset.convertDataFile(saveFile=True) EmptyDS = DataSet() try: Datset.plotQPlane() # No Bins, Emin or Emax assert False except AttributeError: assert True try: Datset.plotQPlane(EBins=[10]) # Length of bins is 1 assert False except AttributeError: assert True try: Datset.plotQPlane(EMin=20,EMax=10) # EMin>EMax assert False except AttributeError: assert True try: EmptyDS.plotQPlane(EMin=2,EMax=3) # Empty DataSet assert False except AttributeError: assert True EMin = np.min(Datset.energy) EMax = EMin+0.5 Data,[Qx,Qy],ax1 = Datset.plotQPlane(EMin,EMax,binning='xy',xBinTolerance=0.05,yBinTolerance=0.05,enlargen=True,log=False,rlu=True) Data,[Qx,Qy],ax2 = Datset.plotQPlane(EMin,EMax,binning='polar',xBinTolerance=0.05,yBinTolerance=0.05,enlargen=False,log=True,rlu=True) fig,AX = plt.subplots() Data,[Qx,Qy],ax3 = Datset.plotQPlane(EMin,EMax,binning='xy',xBinTolerance=0.05,yBinTolerance=0.05,enlargen=False,ax=AX,colorbar=True,vmin=0,vmax=1e-6,zorder=10) ax1.set_clim(-20,-15) ax2.set_clim(0,1e-6) Data,[Qx,Qy],ax3 = Datset.plotQPlane(EMin,EMax,binning='xy',xBinTolerance=0.05,yBinTolerance=0.05) cmap = plt.cm.coolwarm Dataset = DataSet(dataFiles=convertFiles) for d in Dataset.dataFiles: d.A3Off +=90 # rotate data to fall into problem of arctan2 Data,[Qx,Qy],ax2 = Datset.plotQPlane(EMin,EMax,binning='polar',xBinTolerance=0.05,yBinTolerance=0.05,enlargen=False,log=True,rlu=True,cmap=cmap) QxShape = np.array(Qx[0]).shape QyShape = np.array(Qy[0]).shape assert(QxShape==QyShape) assert(np.all(np.array(Data[0][0]).shape == np.array(QxShape)-np.array([1,1]))) try: Datset.plotQPlane(EMin,EMax,binning='notABinningMethod') assert False except: assert True # 3D from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import ListedColormap cmap = plt.cm.coolwarm my_cmap = cmap(np.arange(cmap.N)) my_cmap[:,-1] = np.linspace(0, 1, cmap.N) my_cmap = ListedColormap(my_cmap) fig = plt.figure(figsize=(10,11)) ax = fig.add_subplot(111, projection='3d') Energies = np.concatenate(Datset.energy,axis=0) E = np.arange(Energies.min()+0.35,Energies.max(),0.35) [I,Monitor,Norm,NormCount],[xBins,yBins],ax = \ Datset.plotQPlane(EBins=E,ax = ax,xBinTolerance=0.03,yBinTolerance=0.03, binning='polar',vmin=7.5e-7,vmax=7e-6,antialiased=True,cmap=cmap,rlu=True,extend='max') plt.close('all')
def _z_kde_drone(args): """ Drone function to be called by multiprocessing Pool in make_z_kdes. Not intended to be called manually. """ data, year, lims, N, label, pkg = args w = 3 h = 3 kde = stats.gaussian_kde(data, bw_method='silverman') kde.set_bandwidth(kde.factor / 2) base_level = 1 / (2 * np.pi * np.linalg.det(kde.covariance)**0.5) / data.shape[1] * 0.6 levels = [base_level * 2**i for i in range(9)] x = np.linspace(-lims, lims, N) y = np.linspace(-lims, lims, N) xx, yy = np.meshgrid(x, y, indexing='ij') positions = np.vstack([xx.ravel(), yy.ravel()]) if pkg == 'sp': zz = kde(positions).T.reshape(xx.shape) elif pkg == 'sk': kde = KernelDensity(kde.factor) kde.fit(data.T) zz = np.exp(kde.score_samples(positions.T)).reshape(xx.shape) else: raise ValueError("""pkg must be either 'sk' or 'sp'""") fig, ax = plt.subplots(figsize=(w, h)) plt.subplots_adjust(0, 0, 0.8, 0.8) pardir = os.path.abspath(os.pardir) fontfile = pardir + '/Futura-Medium.ttf' # change as needed if os.path.isfile(fontfile): props = fm.FontProperties(fname=fontfile, size=6) propl = fm.FontProperties(fname=fontfile, size=12) else: props = fm.FontProperties(family='sans-serif', size=6) propl = fm.FontProperties(family='sans-serif', size=12) # set up axes plt.ylabel(r'County Population (standard score)', fontproperties=props) plt.xlabel(r'Per Capita Personal Income (standard score)', fontproperties=props) ax.set_xlim([-lims, lims]) ax.set_ylim([-lims, lims]) majorLocator = MultipleLocator(2) minorLocator = MultipleLocator(1) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_minor_locator(minorLocator) ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_minor_locator(minorLocator) for label_i in ax.get_xticklabels(): label_i.set_fontproperties(props) for label_i in ax.get_yticklabels(): label_i.set_fontproperties(props) # draw contour plot cmap = ListedColormap(Spectral9) ax.contourf(xx, yy, zz, cmap=cmap, levels=levels, norm=LogNorm()) ax.contour(xx, yy, zz, colors='k', levels=levels) # add year to corner fig.text(0.591, 0.7, year, transform=ax.transAxes, fontproperties=propl, horizontalalignment='left', verticalalignment='baseline') # add manual color scale r = 0.02 colors = list(Spectral9) del colors[3] cs_starty = 0.2 cs_endy = 0.8 cs_tscale = 0.8 # bug with placing text, axes transform does not work (always in figure mode) cs_tboosty = -0.005 cs_cx = 1.09 cs_tx = 0.918 delta = (cs_endy - cs_starty) / (len(colors) - 1) for i, c in enumerate(colors): fig.text(cs_tx, cs_tscale * (cs_starty + delta * i + cs_tboosty), 2**i, transform=ax.transAxes, fontproperties=props, horizontalalignment='left', verticalalignment='center') c = mpl.patches.Ellipse(xy=(cs_cx, cs_starty + delta * i), width=h * r, height=w * r, transform=ax.transAxes, linewidth=0.5, facecolor=c, edgecolor='k', clip_on=False) ax.add_artist(c) # add integer sd rings for j in range(1, lims): c = mpl.patches.Circle(xy=(0, 0), radius=j, linewidth=0.5, facecolor='none', edgecolor='k', clip_on=True, zorder=10, alpha=0.5) ax.add_artist(c) # save png fig.savefig(label + '.png', dpi=300, bbox_inches='tight') # free up memory del data del kde ax.cla() fig.clf() plt.close(fig) gc.collect()
knn.predict(iris_X_test) print iris_y_test # KNN Visualization. n_neighbors = 30 neighbors = [5,15,30] h = .02 # step size in the mesh for n_neighbors in neighbors: # Create color maps from matplotlib.colors import ListedColormap cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) for weights in ['uniform', 'distance']: # we create an instance of Neighbours Classifier and fit the data. knn = KNeighborsClassifier(n_neighbors, weights=weights) knn.fit(X, y) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, x_max]x[y_min, y_max]. xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape)
'blue': ((0.0, 0.0, 0.0), (0.125, 1.0, 1.0), (0.25, 1.0, 1.0), (0.4, 1.0, 1.0), (0.5, 1.0, 1.0), (0.6, 0.0, 0.0), (0.7, 0.0, 0.0), (0.825, 0.0, 0.0), (1.0, 0.2, 0.2)) } spec_center = LinearSegmentedColormap('spec_c', cdict2) # IN PROGRESS cdict3 = { 'red': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)) } #spec_center = LinearSegmentedColormap('spec_c', cdict3) #Custom heatmap spectral_colors = np.loadtxt('../utilities/spectral_cm.txt') spectral_wb = ListedColormap(spectral_colors[:, :3], name="spectral_wb", N=256) #Custom heatmap #spectral_colors = np.loadtxt('../utilities/spectral_center.txt') #spectral_c = ListedColormap(spectral_colors[:,:3], name="spectral_c", N=256) """ ---------------------- 2D Hist Methods ---------------------------------- """ """ 2-dimensional histogram, creates histogram ready for imshow, and factors for converting between matrix elements and real-world values. - Read & Bin Data - Print data to file - Read data from file - plot data -- raw bins -- Smoothed bins -- Error Blurred bins """
def _kde_drone(args): """ Drone function to be called by multiprocessing Pool in make_kdes. Not intended to be called manually. """ data, year, extr, lims, N, label, pkg = args xmin, xmax, x_majscale, ymin, ymax, y_majscale = lims top_vals, top_names, bot_vals, bot_names = extr w = 5 h = 3 kde = stats.gaussian_kde(data, bw_method='silverman') kde.set_bandwidth(kde.factor / 2) base_level = 1 / (2 * np.pi * np.linalg.det(kde.covariance)**0.5) / data.shape[1] * 0.6 levels = [base_level * 2**i for i in range(9)] x = np.linspace(xmin, xmax, N) y = np.linspace(ymin, ymax, N) xx, yy = np.meshgrid(x, y, indexing='ij') positions = np.vstack([xx.ravel(), yy.ravel()]) if pkg == 'sp': zz = kde(positions).T.reshape(xx.shape) elif pkg == 'sk': kde = KernelDensity(kde.factor) kde.fit(data.T) zz = np.exp(kde.score_samples(positions.T)).reshape(xx.shape) else: raise ValueError("""pkg must be either 'sk' or 'sp'""") fig, ax = plt.subplots(figsize=(w, h)) pardir = os.path.abspath(os.pardir) fontfile = pardir + '/Futura-Medium.ttf' # change as needed if os.path.isfile(fontfile): props = fm.FontProperties(fname=fontfile, size=6) propl = fm.FontProperties(fname=fontfile, size=12) else: props = fm.FontProperties(family='sans-serif', size=6) propl = fm.FontProperties(family='sans-serif', size=12) # set up axes plt.ylabel(r'County Population', fontproperties=props) plt.xlabel(r'Per Capita Personal Income (2015 Dollars, Thousands)', fontproperties=props) xmajorLocator = MultipleLocator(x_majscale) xminorLocator = MultipleLocator(x_majscale / 2) ymajorLocator = FixedLocator( range(ymin, ymax + 1, y_majscale) ) # this was necessary (over MultipleLocator) for correct tick labels yminorLocator = FixedLocator( [j + np.log10(i) for j in range(ymin, ymax) for i in range(1, 10)]) ax.xaxis.set_major_locator(xmajorLocator) ax.xaxis.set_minor_locator(xminorLocator) ax.yaxis.set_major_locator(ymajorLocator) ax.yaxis.set_minor_locator(yminorLocator) ax.set_yticklabels( ['$\mathregular{{10^{num}}}$'.format(num=i) for i in ax.get_yticks()], minor=False, fontproperties=props) for label_i in ax.get_xticklabels(): label_i.set_fontproperties(props) # draw contour plot cmap = ListedColormap(Spectral9) ax.contourf(xx, yy, zz, cmap=cmap, levels=levels, norm=LogNorm()) ax.contour(xx, yy, zz, colors='k', levels=levels) # add year to corner fig.text(0.775, 0.8, year, transform=ax.transAxes, fontproperties=propl, horizontalalignment='left', verticalalignment='baseline') # add manual color scale r = 0.012 colors = list( Spectral9 ) # need to copy list before modifying, or later processes will have truncated list del colors[3] cs_starty = 0.2 cs_endy = 0.8 cs_tscale = 0.8 # bug with placing text, axes transform does not work (always in figure mode) cs_tboosty = 0.12 cs_cx = 1.055 cs_tx = 0.97 delta = (cs_endy - cs_starty) / (len(colors) - 1) for i, c in enumerate(colors): fig.text(cs_tx, cs_tscale * (cs_starty + delta * i + cs_tboosty), 2**i, transform=ax.transAxes, fontproperties=props, horizontalalignment='left', verticalalignment='center') c = mpl.patches.Ellipse(xy=(cs_cx, cs_starty + delta * i), width=h * r, height=w * r, transform=ax.transAxes, linewidth=0.5, facecolor=c, edgecolor='k', clip_on=False) ax.add_artist(c) # save version with minimal annotations fig.savefig('min_' + label + '.png', dpi=300, bbox_inches='tight') # add statistics display_str = 'rho:\nmean PCPI:\nskewness:' measure_str = '{rho:+5.2f}\n{mean:5.2f}\n{skew:5.3f}'.format( rho=stats.spearmanr(data, axis=1)[0], mean=data[0].mean(), skew=stats.skew(data[0])) fig.text(0.23, 0.81, display_str, transform=ax.transAxes, fontproperties=props, horizontalalignment='right', verticalalignment='center', linespacing=1.0) fig.text(0.24, 0.81, measure_str, transform=ax.transAxes, fontproperties=props, horizontalalignment='left', verticalalignment='center', linespacing=1.0) # save version with basic annotations fig.savefig('med_' + label + '.png', dpi=300, bbox_inches='tight') # place lowest and highest values and text in lower part of figure txt_y = 0.365 txt_x_lft = 0.19 txt_x_rgt = 0.82 delta = 0.0525 vals_str = '\n{: 4.1f}\n{: 4.1f}\n{: 4.1f}\n{: 4.1f}\n{: 4.1f}'.format( *top_vals) names_str = 'Top 5 PCPI\n{}\n{}\n{}\n{}\n{}'.format( *[name + ':' for name in top_names]) bbox_dict = { 'pad': 3, 'edgecolor': (1, 1, 1, 0), 'facecolor': (1, 1, 1, 0.7) } thv = fig.text(txt_x_rgt + 0.01, txt_y - delta, vals_str, transform=ax.transAxes, fontproperties=props, horizontalalignment='left', verticalalignment='top', linespacing=1.0) thv.set_bbox(bbox_dict) thn = fig.text(txt_x_rgt, txt_y - delta, names_str, transform=ax.transAxes, fontproperties=props, horizontalalignment='right', verticalalignment='top', linespacing=1.0) thn.set_bbox(bbox_dict) vals_str = '\n{:> 4.1f}\n{:> 4.1f}\n{:> 4.1f}\n{:> 4.1f}\n{:> 4.1f}'.format( *bot_vals) names_str = ' Bottom 5 PCPI\n{}\n{}\n{}\n{}\n{}'.format( *[' :' + name for name in bot_names]) tln = fig.text(txt_x_lft, txt_y - delta, names_str, transform=ax.transAxes, fontproperties=props, horizontalalignment='left', verticalalignment='top', linespacing=1.0) tln.set_bbox(bbox_dict) tlv = fig.text(txt_x_lft - 0.01, txt_y - delta, vals_str, transform=ax.transAxes, fontproperties=props, horizontalalignment='right', verticalalignment='top', linespacing=1.0) tlv.set_bbox(bbox_dict) # save version with full annotations fig.savefig('full_' + label + '.png', dpi=300, bbox_inches='tight') # free up memory del data del kde ax.cla() fig.clf() plt.close(fig) gc.collect()
X = StandardScaler().fit_transform(X) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.34, random_state=42) x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5 y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # just plot the dataset first cm = plt.cm.RdBu cm_bright = ListedColormap(["#FF0000", "#0000FF"]) ax = plt.subplot(len(datasets), len(classifiers) + 1, i) if ds_cnt == 0: ax.set_title("Input data") # Plot the training points ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright) # and testing points ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6) ax.set_xlim(xx.min(), xx.max()) ax.set_ylim(yy.min(), yy.max()) ax.set_xticks(())
def create_single_big_boxplot(list_of_files, save=False, save_path='C:\\Users\\s145576\\Desktop', compare_best=False): df_list = [] for index, results_file in enumerate(list_of_files): res_df = create_results_df(results_file, index) df_list.append(res_df) results_df = pd.DataFrame(columns=['setting 0', 'setting 1', 'p-value']) # either use permutations or combinations permutation_list = [i for i in itertools.permutations(df_list, r=2)] for permutation in permutation_list: if not compare_best: w, p = wilcoxon( permutation[0][permutation[0]["class"] == '1'] ['dice'].to_numpy(), permutation[1][permutation[1]["class"] == '1']['dice'].to_numpy()) results_df = results_df.append( { 'setting 0': permutation[0]['config_name'][0], 'setting 1': permutation[1]['config_name'][0], 'p-value': p }, ignore_index=True) else: best_config_name = get_best_config(df_list) if permutation[0]['config_name'][ 0] == best_config_name or permutation[1]['config_name'][ 0] == best_config_name: w, p = wilcoxon( permutation[0][permutation[0]["class"] == '1'] ['dice'].to_numpy(), permutation[1][ permutation[1]["class"] == '1']['dice'].to_numpy()) results_df = results_df.append( { 'setting 0': permutation[0]['config_name'][0], 'setting 1': permutation[1]['config_name'][0], 'p-value': p }, ignore_index=True) else: results_df = results_df.append( { 'setting 0': permutation[0]['config_name'][0], 'setting 1': permutation[1]['config_name'][0], 'p-value': 1.0 }, ignore_index=True) # results_df.sort_values(by=['setting 0', 'setting 1']) # corr_p_values = multipletests(results_df['p-value'], alpha=0.05, method='bonferroni', is_sorted=False, returnsorted=False) # results_df['corr_p_values'] = corr_p_values[1] plt.figure(figsize=(30, 30)) print(results_df[results_df.duplicated()]) results_df = results_df.pivot("setting 0", "setting 1", "p-value") mask = np.zeros_like(results_df) mask[results_df > 0.05] = True mask[np.triu_indices_from(mask)] = True # g = sns.heatmap(results_df, mask=mask, cbar=False, annot=True, linewidths=0.5, fmt=".3f",cmap=ListedColormap(['#89cf55', '#fffde8']), center = 0.05) g = sns.heatmap(results_df, cbar=False, annot=True, linewidths=0.5, fmt=".3f", cmap=ListedColormap(['#89cf55', '#fffde8']), center=0.05) if save: if 'Ergo' in save_path: filename = '\\Ergo_Results_Wilcoxon_test.png' df_filename = '\\Ergo_Results_Wilcoxon_test.csv' elif 'BTD' in save_path and 'seed 0' in save_path: filename = '\\BTD_Results_Wilcoxon_test_seed_0.png' df_filename = '\\BTD_Results_Wilcoxon_test_seed_0.csv' elif 'BTD' in save_path and 'seed 13' in save_path: filename = '\\BTD_Results_Wilcoxon_test_seed_13.png' df_filename = '\\BTD_Results_Wilcoxon_test_seed_13.csv' elif 'BTD' in save_path and 'seed 364' in save_path: filename = '\\BTD_Results_Wilcoxon_test_seed_364.png' df_filename = '\\BTD_Results_Wilcoxon_test_seed_364.csv' elif 'LiTS' in save_path: filename = '\\LiTS_Results_Wilcoxon_test.png' df_filename = '\\LiTS_Results_Wilcoxon_test.csv' results_df.to_csv(save_path + df_filename, index=False) plt.savefig(save_path + filename, format='png') plt.close() else: plt.show()
X=[0]*len(x) for i in range(len(X)): X[i]=[x[i],y[i]] ###################### """from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=8).fit(X) labels=kmeans.labels_ """ # Compute Affinity Propagation af = AffinityPropagation(preference=(len(X)/20)).fit(X) cluster_centers_indices = af.cluster_centers_indices_ labels = af.labels_ ################### PLOT ################### import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap #m=('s', 'x', 'o', '^', 'v', '*', 'd') colors = ('blue', 'lightgreen', 'gray', 'cyan', 'yellow', 'black','green') cmap = ListedColormap(colors[:len(numpy.unique(y))]) plt.scatter(x, y,c=labels, cmap=plt.cm.Paired, edgecolors='k') #marker=m , edgecolors='k' fig = plt.gcf() ############################################
def test_DataSet_plotCutQELine(): Points = np.array([[0.7140393034102988,-0.4959224853328328], [1.128363301356428,-1.6520150761601147], [1.9002545852012716,-0.9393552598967219], [1.0432282332853056,-0.12375569239528339]],dtype=float) QPoints = np.zeros((Points.shape[0],3)) QPoints[:,:2]=Points EnergyBins = np.linspace(1.7,2.7,11) minPixel = 0.001 width=0.1 import matplotlib matplotlib.use('Agg') DataFile = [os.path.join(dataPath,'camea2018n000136.hdf'),os.path.join(dataPath,'camea2018n000137.hdf')] dataset = DataSet(convertedFiles=DataFile) dataset.convertDataFile(saveFile=False) try: # No Q-points dataset.plotCutQELine([],EnergyBins,width=width,minPixel=minPixel,rlu=False) assert False except AttributeError: assert True try: # No points in E range dataset.plotCutQELine(QPoints,EnergyBins+100,width=width,minPixel=minPixel,rlu=True,vmin=0.0,vmax=1.5e-6,ticks=10) assert False except AttributeError: assert True try: # No wrong dim of QPonts dataset.plotCutQELine(QPoints,EnergyBins,width=width,minPixel=minPixel,rlu=False) assert False except AttributeError: assert True try: # No wrong dim of QPonts dataset.plotCutQELine(QPoints[:,:2],EnergyBins,width=width,minPixel=minPixel,rlu=True) assert False except AttributeError: assert True fig = plt.figure() ax = fig.gca() ax,DataList,BinListTotal,centerPositionTotal,binDistanceTotal = dataset.plotCutQELine( QPoints[:,:2],EnergyBins,width=width,minPixel=minPixel,rlu=False,ax=ax,vmin=0.0,vmax=1.5e-6,log=True,seperatorWidth=3) HKLPoints = np.array([[1.0,0.0,0.0], [0.5,1.5,0.0], [1.7,-0.1,0.0], [1.0,1.0,0.0]]) ax,DataList,BinListTotal,centerPositionTotal,binDistanceTotal = dataset.plotCutQELine( HKLPoints,EnergyBins,width=width,minPixel=minPixel,rlu=True,plotSeperator = False,ticks=1,tickRound=1,colorbar=True,log=True) # 3D from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import ListedColormap cmap = plt.cm.coolwarm my_cmap = cmap(np.arange(cmap.N)) my_cmap[:,-1] = np.linspace(0, 1, cmap.N) my_cmap = ListedColormap(my_cmap) fig = plt.figure(figsize=(10,11)) ax = fig.add_subplot(111, projection='3d') Energies = np.concatenate(dataset.energy,axis=0) E = np.arange(Energies.min()+0.35,Energies.max(),0.35) ax,DataList,BinListTotal,centerPositionTotal,binDistanceTotal = \ dataset.plotCutQELine(QPoints=HKLPoints,EnergyBins=E,ax = ax,width=0.05,minPixel=0.01, vmin=7.5e-7,vmax=7e-6,cmap=cmap,rlu=True) plt.close('all')
file_dict.keys() # In[37]: # # make a 5 color palette # import seaborn as sns from matplotlib.colors import ListedColormap, LinearSegmentedColormap colors = ["royal blue", "baby blue", "eggshell", "burnt red", "soft pink"] print([the_color for the_color in colors]) colors = [sns.xkcd_rgb[the_color] for the_color in colors] pal = ListedColormap(colors, N=5) # In[38]: # # # the A2014127.2110 scene is a descending orbit, so south is on top # and west is on the right, need to rotate through 180 degrees # get_ipython().magic("matplotlib inline") from matplotlib import pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(10, 10)) phase_rot = np.rot90(file_dict["phase"], 2) CS = ax.imshow(phase_rot, cmap=pal) ax.set_title("ungridded phase map with 2 rotations")
from sklearn.model_selection import cross_val_score accuracies = cross_val_score(clf, X=X_train, y=y_train, cv=10) # Plot from matplotlib.colors import ListedColormap plt.figure() X_set, y_set = X_train, y_train X1, X2 = np.meshgrid( np.arange(X_set[:, 0].min() - 1, X_set[:, 0].max() + 1, step=0.01), np.arange(X_set[:, 1].min() - 1, X_set[:, 1].max() + 1, step=0.01)) boundary = clf.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape) plt.contourf(X1, X2, boundary, alpha=0.75, cmap=ListedColormap(('#fc7a74', '#6ff785'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c=ListedColormap(('red', 'green'))(i), label=j, s=20) plt.title('Gaussian SVM') plt.xlabel('Age') plt.ylabel('Salary') plt.legend() plt.show()
( 253 , 245 , 230), ( 255 , 228 , 180), ( 243 , 164 , 96), ( 237 , 118 , 0), ( 205 , 102 , 29), ( 224 , 49 , 15), ( 237 , 0 , 0), ( 205 , 0 , 0), ( 139 , 0 , 0)] colors = numpy.array(colors) / 255.0 #colors = ["#FFFFFF", "#7FFF00", "#00CD00", "#008B00", "#104E8B", "#1E90FF", # "#00B2EE", "#00EEEE", "#8968CD", "#912CEE", "#8B008B", "#8B0000", # "#CD0000", "#EE4000", "#FF7F00", "#CD8500", "#FFD700", "#EEEE00", # "#FFFF00", "#7FFF00","#000000"] cmap = ListedColormap(colors[:]) cmap.set_over(color=colors[-1]) cmap.set_under(color=colors[0]) normer = BoundaryNorm(values, cmap.N, clip=False) #data_proj,x,y = map.transform_scalar(data,lons,lats,nx,ny,returnxy=True) cax = plt.axes([0.902,0.2,0.03,0.6]) res = map.imshow(data, interpolation='nearest', cmap=cmap, norm=normer, ax=ax) clr = plt.colorbar(res, cax=cax, format='%g') clr.set_ticks(values) map.drawcoastlines(ax=ax) map.drawstates(ax=ax) map.drawcountries(ax=ax)
#y_pred=clasifier.predict(6.5) #crear matriz de confusión (evaluar prediccion) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test,y_pred) print(cm) """ #------<VISUALIZAR MODELOS DE CLASIFICACION>---------- """ # Representación gráfica de los resultados del algoritmo en el Conjunto de Entrenamiento from matplotlib.colors import ListedColormap X_set, y_set = x_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Clasificador Naive Bayes(Conjunto de Entrenamiento)') plt.xlabel('Edad') plt.ylabel('Sueldo Estimado') plt.legend() plt.show() # Representación gráfica de los resultados del algoritmo en el Conjunto de Testing X_set, y_set = x_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
points = [] data = [] dr = rmax / nr for r in np.linspace(0, 5, nr): for pt in geode_pts: r_ = r + dr * (np.random.random() - 0.5) points.append(pt * r_) theta = np.abs(np.arccos(pt[2] / r_)) data.append(r_ * np.cos(theta) * np.exp(-r_)) points = pv.pyvista_ndarray(points) datac = pv.pyvista_ndarray(data) point_cloud = pv.PolyData(points) point_cloud["Psi"] = datac mapping = np.linspace(datac.min(), datac.max(), 256) newcolors = np.empty((256, 4)) newcolors[mapping >= 0.9 * 256] = np.array([256 / 256, 0 / 256, 0 / 256, 1]) newcolors[mapping <= 0.8 * 256] = np.array([256 / 256, 0 / 256, 0 / 256, .9]) newcolors[mapping <= 0.7 * 256] = np.array([256 / 256, 0 / 256, 0 / 256, .8]) newcolors[mapping <= 0.6 * 256] = np.array([256 / 256, 0 / 256, 0 / 256, .7]) newcolors[mapping <= 0.5 * 256] = np.array([256 / 256, 0 / 256, 0 / 256, .6]) newcolors[mapping <= 0.4 * 256] = np.array([256 / 256, 0 / 256, 0 / 256, .5]) newcolors[mapping <= 0.3 * 256] = np.array([256 / 256, 0 / 256, 0 / 256, .4]) newcolors[mapping <= 0.2 * 256] = np.array([256 / 256, 0 / 256, 0 / 256, .3]) newcolors[mapping <= 0.1 * 256] = np.array([256 / 256, 0 / 256, 0 / 256, .2]) my_colormap = ListedColormap(newcolors) point_cloud.plot(render_points_as_spheres=False, cmap=my_colormap)
def get_color_ramp(midpoint, palette="default", N=9, as_cmap=False): """ Return a color ramp with the specified midpoint color and number of colors. Color maps were generated using the chroma.js tool. Notes ----- This can return either a list of hex strings, or a `matplotlib.colors.ListedColorMap` object if `as_cmap` is True. Parameters ---------- midpoint : str the name of a color in the specified palette, e.g., 'purple', 'blue', 'electric-blue' palette : 'default', 'light', 'dark', optional the color palette to use if midpoint is specified as a color name N : int, optional the number of colors in the returned ramp as_cmap : bool, optional whether to return a `matplotlib.colors.ListedColorMap` object Returns ------- ramp : list of str, or `matplotlib.colors.ListedColorMap` object the color ramp, either as a list of hex code strings, or a `matplotlib.colors.ListedColorMap` object """ # default color palette assert palette in ["default", "light", "dark"] # The mid/end points of the color ramp colors = { "blue": { "default": ["#253757", "#6584c0", "#d3daef"], "dark": ["#242d4e", "#6c7ab6", "#d2d4e9"], "light": ["#363f61", "#7989c9", "#dddff4"], }, "green": { "default": ["#30512a", "#65a25a", "#d8ebd3"], "dark": ["#234821", "#569b51", "#d1e6cd"], "light": ["#365b32", "#66ab60", "#dcf1d8"], }, "yellow": { "default": ["#64531f", "#b99a3a", "#faebce"], "dark": ["#574a1a", "#ac933b", "#f2e6ca"], "light": ["#685d27", "#b7a443", "#fbf1d3"], }, "orange": { "default": ["#674119", "#ca843a", "#fde1c9"], "dark": ["#5a3917", "#bd7e3f", "#f5dcc7"], "light": ["#694b22", "#c69044", "#fde7cf"], }, "red": { "default": ["#672013", "#de5b3f", "#ffd1c4"], "dark": ["#5a1d11", "#cd5d43", "#f9cdc2"], "light": ["#6a291b", "#de644a", "#ffd5ca"], }, "electric-blue": { "default": ["#2a5664", "#52a4bd", "#d8edf6"], "dark": ["#274c5a", "#569bb5", "#d5e7f0"], "light": ["#395f66", "#66abb8", "#dff3f7"], }, "purple": { "default": ["#592767", "#bf63d8", "#f2d4f8"], "dark": ["#521f5d", "#b95ccc", "#eecff3"], "light": ["#662e67", "#cf66d0", "#fad8f8"], }, } # make the midpoint is specified allowed = list(colors) if midpoint not in allowed: raise ValueError( f"If specified as as color name, allowed values are: {allowed}") # Create the ramp ramp = [ color.hexcode for color in spectra.Scale(colors[midpoint][palette]).range(N) ] if as_cmap: from matplotlib.colors import ListedColormap ramp = ListedColormap(ramp, name=f"custom-{midpoint}") return ramp
# In[92]: file_dict.keys() # In[93]: # # make a 5 color palette # import seaborn as sns from matplotlib.colors import ListedColormap, LinearSegmentedColormap colors = ["royal blue", "baby blue", "eggshell", "burnt red", "soft pink"] print([the_color for the_color in colors]) colors=[sns.xkcd_rgb[the_color] for the_color in colors] pal=ListedColormap(colors,N=5) # In[94]: # # # the A2014127.2110 scene is a descending orbit, so south is on top # and west is on the right, need to rotate through 180 degrees # get_ipython().magic('matplotlib inline') from matplotlib import pyplot as plt fig,ax = plt.subplots(1,1,figsize = (10,10)) phase_rot=np.rot90(file_dict['phase'],2) CS=ax.imshow(phase_rot,cmap=pal) ax.set_title('ungridded phase map with 2 rotations') cax=fig.colorbar(CS)
# ---------------------------------------------------------- # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) # Confusion matrix is simply actual values vs. predicted values in a # table # Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('grey', 'white'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Classifier (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() # Visualising the Test set results from matplotlib.colors import ListedColormap X_set, y_set = X_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
def colour_map(colours, match_colour=None, match_value=None, dmin=None, dmax=None, data=None, cmap_len=256, extend='neither'): """ Return a matplotlib colour map from a list of colours. A single colour within the list can be assigned a value by providing the data limits that the colour map will be used on. Note, if using this functionality, match_colour, match_value and data limits (or all the data) must be provided. Args: * colours: list A list of matplotlib accepted colours. These include names (see http://www.w3schools.com/html/html_colornames.asp), html hex colour codes and RGB arrays. Kwargs: * match_colour: string or RBG array Specify one of the colours in the colour list (but not the first or last) to be matched against a given value (see below). * match_value: float Specify a value to which a given colour is to be matched. * dmin: float Data minimum. * dmax: Data maximum * data: array like Alternative to providing the limits. Limits are calculated using the data within the function. * cmap_len: integer Total number of colours in the colour map. * extend: 'neither' or 'both' If 'both', the first and last colours are set to under and over data range colours. Returns: matplotlib.colors.Colormap """ cmap = LinearSegmentedColormap.from_list('cmap', colours, N=cmap_len) if match_colour is not None: assert match_value is not None, 'A value must be given with which to '\ 'match the colour.' colours = [colour.lower() for colour in colours] match_colour = match_colour.lower() assert match_colour in colours, 'The colour to match, %s, is not in'\ ' the given colours list, %s.' % (match_colour, colours) if dmin is None or dmax is None: assert data is not None, 'To scale the colour map, data or data '\ 'minimum and maximum must be provided.' dmin = numpy.min(data) dmax = numpy.max(data) else: assert dmin is not None and dmax is not None, 'Both dmin and dmax'\ ' must be provided.' assert dmin < dmax, 'dmin must be smaller than dmax.' assert dmin <= match_value <= dmax, 'match_value, %s, value must fall'\ ' within the data range, %s & %s.' % (match_value, dmin, dmax) colour_position = float(colours.index(match_colour)) / \ float(len(colours) - 1) if colour_position in [0., 1]: raise UserWarning('The colour to match the value cannot be a '\ 'colour on the limits of the colour map.') value_position = float(match_value - dmin) / \ float(dmax - dmin) if value_position > colour_position: # Cut off the top end of the colour map using equation... x = (colour_position * cmap.N) / value_position # Take colours from 0 to x (+1 for range to reach x value) colour_RGBs = cmap(range(int(round(x + 1)))) cmap = ListedColormap(colour_RGBs) elif value_position < colour_position: # Cut off the bottom end of the colour map using equation... x = ((colour_position - value_position) * cmap.N) / \ (1. - value_position) # Take colours from x to end colour index (+1 for range to reach x # value) colour_RGBs = cmap(range(int(round(x)), (cmap.N + 1))) cmap = ListedColormap(colour_RGBs) else: assert match_value is None, 'A value has been specified without a '\ 'colour to match it with.' if extend == 'both': over_colour = cmap(cmap.N) under_colour = cmap(0) colour_RGBs = cmap(range(1, cmap.N - 1)) cmap = ListedColormap(colour_RGBs) cmap.set_over(over_colour) cmap.set_under(under_colour) return cmap
'''get gamap's WhGrYlRd color scheme from file''' import numpy as np from matplotlib.colors import ListedColormap import os current_dir = os.path.dirname(__file__) rgb_WhGrYlRd = np.genfromtxt(current_dir + '/colormap_data/WhGrYlRd.txt', delimiter=' ') WhGrYlRd = ListedColormap(rgb_WhGrYlRd / 255.0)
# Build a coarser grid to plot a set of ensemble classifications # to show how these are different to what we see in the decision # surfaces. These points are regularly space and do not have a # black outline xx_coarser, yy_coarser = np.meshgrid( np.arange(x_min, x_max, plot_step_coarser), np.arange(y_min, y_max, plot_step_coarser)) Z_points_coarser = model.predict(np.c_[xx_coarser.ravel(), yy_coarser.ravel()]).reshape( xx_coarser.shape) cs_points = plt.scatter(xx_coarser, yy_coarser, s=15, c=Z_points_coarser, cmap=cmap, edgecolors="none") # Plot the training points, these are clustered together and have a # black outline plt.scatter(X[:, 0], X[:, 1], c=y, cmap=ListedColormap(['r', 'y', 'b']), edgecolor='k', s=20) plot_idx += 1 # move on to the next plot in sequence plt.suptitle("Classifiers on feature subsets of the Iris dataset") plt.axis("tight") plt.show()
def publication_plot_old(save=False): from matplotlib.gridspec import GridSpec freqs = get_freqs(gag=True) N_samples, L, _ = freqs.shape #freqs_rm = get_freqs(gag=True, remove_rm=True) freqs_rm = freqs.copy() #for i in range(L): # if i in GAG_RESISTANCE: continue # freqs_rm[:, i-1] = 0. for i in range(L): for xi, ch in enumerate(ALPHABET[:20]): if str(i+1) + ch in GAG_RESISTANCE_MUTS_SIMP: continue freqs_rm[:, i, xi] = 0. freqs = freqs.sum(axis=2) freqs.sort(axis=0) freqs = freqs[::-1] freqs_rm = freqs_rm.sum(axis=2) freqs_rm.sort(axis=0) freqs_rm = freqs_rm[::-1] #lanl_freqs = np.genfromtxt('lanl/gag_freqs_nowt_experienced.txt') lanl_freqs = np.genfromtxt('lanl/gag_freqs_nowt_naive.txt') lanl_freqs = lanl_freqs.reshape(-1,500,20) lanl_rm = lanl_freqs.copy() for i in range(L): for xi, ch in enumerate(ALPHABET[:20]): if str(i+1) + ch in GAG_RESISTANCE_MUTS_SIMP: continue lanl_rm[:, i, xi] = 0. lanl_freqs = lanl_freqs.sum(axis=2) lanl_rm = lanl_rm.sum(axis=2) print lanl_freqs.shape, lanl_rm.shape print freqs.shape #fig = plt.figure(figsize=(24, 12)) fig = plt.figure(figsize=(7.5, 4)) fig.suptitle('Variant Frequencies in Gag', size=20) gs = GridSpec(3, 2, height_ratios=[10,1,10], width_ratios=[100, 1]) ax1 = plt.subplot(gs[0, :-1]) ax3 = plt.subplot(gs[1, :-1]) ax2 = plt.subplot(gs[2, :-1]) matplotlib.rc('font', size=24) matplotlib.rc('axes', linewidth=5) [ax.set_xlabel('Sequence Position') for ax in (ax1, ax2)] ax1.set_ylabel('Samples with variants') ax2.set_ylabel('LANL PI-naive\nsequences with variants') red_cmap = ListedColormap(['red']) black_cmap = ListedColormap(['black']) red_cmap.set_bad((0,0,0,0)) freqs_ma = np.ma.masked_where(freqs < 0.01, freqs) freqs_rm_ma = np.ma.masked_where(freqs_rm < 0.01, freqs_rm) plt1 = ax1.pcolor(freqs_ma, cmap=black_cmap, edgecolors='none') plt2 = ax1.pcolor(freqs_rm_ma, cmap=red_cmap, alpha=0.75, edgecolors='none') plt3 = ax2.bar(np.arange(L), lanl_freqs.sum(axis=0), width=1, fc='0.5', ec='0.5') plt4 = ax2.bar(np.arange(L), lanl_rm.sum(axis=0), width=1, fc='r', ec='none', alpha=0.75) plt.setp(ax1.get_xticklabels(), visible=False) quart1 = N_samples / 4. quart2 = lanl_freqs.shape[0] / 4. ax1.set_yticks(np.arange(0, N_samples+quart1, quart1)) ax2.set_yticks(np.arange(0, N_samples+quart1, quart1)) ax2.set_yticks(np.arange(0, lanl_freqs.shape[0]+quart2, quart2)) quarter = N_samples / 4. #[ax.set_yticks(np.arange(0, N_samples + quarter, quarter)) for ax in (ax1, ax2)] [ax.set_yticklabels(['0%', '25%', '50%', '75%', '100%']) for ax in (ax1, ax2)] ax1.set_ylim(0, 1.5*N_samples) #ax2.set_ylim(0, 0.8*N_samples) ax2.set_ylim(0, 0.9*lanl_freqs.shape[0]) locs = [(132, 'MA'), (363, 'CA'), (377, 'p2'), (432, 'NC'), (448, 'p1'), (500, 'p6')] x_start = 0 colors = ('#AAAAAA', '#EEEEEE') for i, (junc, name) in enumerate(locs): color = colors[i%2] width = junc - x_start rect = Rectangle((x_start, 0), width, 1, edgecolor='None', color=color) ax3.add_patch(rect) ax3.text(x_start + width/2., 1/2., name, ha='center', va='center') ax1.axvline(x_start, color='k', ls='--', lw=1.0) ax2.axvline(x_start, color='k', ls='--', lw=1.0) x_start = junc ax3.set_xlim(0, L) plt.setp(ax3.get_xticklabels(), visible=False) plt.setp(ax3.get_yticklabels(), visible=False) [ax.tick_params(top=False, left=False, right=False, bottom=False) for ax in (ax1, ax2, ax3)] ax2.invert_yaxis() fig.subplots_adjust(hspace=0., wspace=0.02, left=0.08, right=0.95, top=0.95, bottom=0.06) if not save: plt.show() else: fig.savefig('PUB_VARIANTS_PLOT.tiff', dpi=600)
def olr(): olr_map =[cm.gist_yarg(cc) for cc in range(0,255,5)] olr_coltbl = ListedColormap(olr_map,name = 'orl_coltbl',N=36) olr_coltbl.set_bad(color= olr_coltbl.colors[-1]) return olr_coltbl
# mpl.rcParams["fig.size"]=(10,10) from matplotlib.colors import ListedColormap x_set, y_set = x_train, y_train x1, x2 = np.meshgrid( np.arange(start=x_set[:, 0].min() - 1, stop=x_set[:, 0].max() + 1, step=0.01), np.arange(start=x_set[:, 1].min() - 1, stop=x_set[:, 1].max() + 1, step=0.01)) plt.contourf(x1, x2, classifier.predict(np.array([x1.ravel(), x2.ravel()]).T).reshape(x1.shape), alpha=0.75, cmap=ListedColormap(("red", "green"))) plt.xlim(x1.min(), x1.max()) plt.ylim(x2.min(), x2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(x_set[y_set == j, 0], x_set[y_set == j, 1], c=ListedColormap(("red", "green"))(i), label=j) plt.title('KNN training set') plt.xlabel("age") plt.ylabel("estimated salary") plt.legend() plt.show() # visualizing the training set results # mpl.rcParams["fig.size"]=(10,10)
def draw_legend(im_ax, bbox=(1.05, 1), titles=None, cmap=None, classes=None): """Create a custom legend with a box for each class in a raster using the image object, the unique classes in the image and titles for each class. Parameters ---------- im_ax : matplotlib image object This is the image returned from a call to imshow(). bbox : tuple (default = (1.05, 1)) This is the bbox_to_anchor argument that will place the legend anywhere on or around your plot. titles : list (optional) A list of a title or category for each unique value in your raster. This is the label that will go next to each box in your legend. If nothing is provided, a generic "Category x" will be populated. cmap : str (optional) Colormap name to be used for legend items. classes : list (optional) A list of unique values found in the numpy array that you wish to plot. Returns ---------- matplotlib.pyplot.legend A matplotlib legend object to be placed on the plot. """ try: im_ax.axes except AttributeError: raise AttributeError("""Oops. The legend function requires a matplotlib axis object to run properly. You have provided a {}.""".format(type(im_ax))) # If classes not provided, get them from the im array in the ax object # Else use provided vals if classes: try: # Get the colormap from the mpl object cmap = im_ax.cmap.name except AssertionError: raise AssertionError("""Looks like we can't find the colormap name which means a custom colormap was likely used. Please provide the draw_legend function with a cmap= argument to ensure your legend draws properly.""") # If the colormap is manually generated from a list if cmap == "from_list": cmap = ListedColormap(im_ax.cmap.colors) colors = make_col_list(nclasses=len(classes), unique_vals=classes, cmap=cmap) else: classes = list(np.unique(im_ax.axes.get_images()[0].get_array())) # Remove masked values, could next this list comp but keeping it simple classes = [ aclass for aclass in classes if aclass is not np.ma.core.masked ] colors = [im_ax.cmap(im_ax.norm(aclass)) for aclass in classes] # If titles are not provided, create filler titles if not titles: titles = ["Category {}".format(i + 1) for i in range(len(classes))] if not len(classes) == len(titles): raise ValueError("""The number of classes should equal the number of titles. You have provided {0} classes and {1} titles.""".format(len(classes), len(titles))) patches = [ mpatches.Patch(color=colors[i], label="{l}".format(l=titles[i])) for i in range(len(titles)) ] # Get the axis for the legend ax = im_ax.axes return ax.legend( handles=patches, bbox_to_anchor=bbox, loc=2, borderaxespad=0.0, prop={"size": 13}, )
x_set, y_set = x_test, y_test x1, x2 = np.meshgrid( np.arange(start=x_set[:, 0].min() - 1, stop=x_set[:, 0].max() + 1, step=0.01), np.arange(start=x_set[:, 1].min() - 1, stop=x_set[:, 1].max() + 1, step=0.01)) #setting the pexicles #To draw the separator (straight line) plt.contourf(x1, x2, classifier.predict(np.array([x1.ravel(), x2.ravel()]).T).reshape(x1.shape), alpha=0.75, cmap=ListedColormap(('red', 'green'))) #if 0 (red) if 1 (green) #now to color the scattered points either red or green we will iterate and check predict #if 1 make it green else red plt.xlim(x1.min(), x1.max()) plt.ylim(x2.min(), x2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(x_set[y_set == j, 0], x_set[y_set == j, 1], c=ListedColormap(('red', 'green'))(i), label=j) #now label the axies plt.title('K-NN(Test Set)') plt.xlabel('Age') plt.ylabel('Salary') plt.legend()
ds = gdal.Open(filename) landcover = np.array(ds.GetRasterBand(1).ReadAsArray()) filename = os.path.join(dir_root, "data", "mean", "ppt_mean.tif") ds = gdal.Open(filename) ppt = np.array( ds.GetRasterBand(1).ReadAsArray()) * 365 #(daily to yearly conversion) ppt[landcover == 0] = np.nan sns.set(font_scale=1., style="ticks") plt.style.use("pnas") fig, ax = plt.subplots(figsize=(3, 3)) colors = sns.color_palette("Blues", n_colors=3).as_hex() colors = list(np.repeat(colors[0], 2)) + list(np.repeat(colors[1], 4)) + list( np.repeat(colors[2], 10)) plot = ax.imshow(ppt, vmin=0, vmax=2000, cmap=ListedColormap(colors)) plt.axis('off') cax = fig.add_axes([1, 0.2, 0.05, 0.6]) cax.set_title("Annual\nprecipitation (mm)") cbar = fig.colorbar(plot, cax=cax, orientation='vertical') cbar.set_ticks([0, 250, 750, 2000]) plt.show() def histedges_equalN(x, nbin): npt = len(x) return np.interp(np.linspace(0, npt, nbin + 1), np.arange(npt), np.sort(x)) def segregate_plantClimate(plantClimatePath, n=20,
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth, alpha, **options): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function or a list of boolean functions of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``None``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of ``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``, respectively ``'-'``, ``'--'``, ``':'``, ``'-.'``. - ``borderwidth`` -- integer (default: None), the width of the border in pixels - ``alpha`` -- (default: 1) How transparent the fill is. A number between 0 and 1. - ``legend_label`` -- the label for this item in the legend - ``base`` - (default: 10) the base of the logarithm if a logarithmic scale is set. This must be greater than 1. The base can be also given as a list or tuple ``(basex, basey)``. ``basex`` sets the base of the logarithm along the horizontal axis and ``basey`` sets the base along the vertical axis. - ``scale`` -- (default: ``"linear"``) string. The scale of the axes. Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``, ``"semilogy"``. The scale can be also be given as single argument that is a list or tuple ``(scale, base)`` or ``(scale, basex, basey)``. The ``"loglog"`` scale sets both the horizontal and vertical axes to logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis to logarithmic scale. The ``"linear"`` scale is the default value when :class:`~sage.plot.graphics.Graphics` is initialized. EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Graphics object consisting of 1 graphics primitive Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') Graphics object consisting of 2 graphics primitives An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) Graphics object consisting of 2 graphics primitives A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)) Graphics object consisting of 1 graphics primitive A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Graphics object consisting of 1 graphics primitive Since it doesn't look very good, let's increase ``plot_points``:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400) Graphics object consisting of 1 graphics primitive To get plots where only one condition needs to be true, use a function. Using lambda functions, we definitely need the extra ``plot_points``:: sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), plot_points=400) Graphics object consisting of 1 graphics primitive The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400) Graphics object consisting of 1 graphics primitive Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) Graphics object consisting of 2 graphics primitives If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Graphics object consisting of 1 graphics primitive Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200) Graphics object consisting of 2 graphics primitives The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s,t=var('s,t') sage: region_plot(s>0,(t,-2,2),(s,-2,2)) Graphics object consisting of 1 graphics primitive :: sage: region_plot(s>0,(s,-2,2),(t,-2,2)) Graphics object consisting of 1 graphics primitive An example of a region plot in 'loglog' scale:: sage: region_plot(x^2+y^2<100, (x,1,10), (y,1,10), scale='loglog') Graphics object consisting of 1 graphics primitive TESTS: To check that :trac:`16907` is fixed:: sage: x, y = var('x, y') sage: disc1 = region_plot(x^2+y^2 < 1, (x, -1, 1), (y, -1, 1), alpha=0.5) sage: disc2 = region_plot((x-0.7)^2+(y-0.7)^2 < 0.5, (x, -2, 2), (y, -2, 2), incol='red', alpha=0.5) sage: disc1 + disc2 Graphics object consisting of 2 graphics primitives To check that :trac:`18286` is fixed:: sage: x, y = var('x, y') sage: region_plot([x == 0], (x, -1, 1), (y, -1, 1)) Graphics object consisting of 1 graphics primitive sage: region_plot([x^2+y^2==1, x<y], (x, -1, 1), (y, -1, 1)) Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics from sage.plot.misc import setup_for_eval_on_grid from sage.symbolic.expression import is_Expression from warnings import warn import numpy if not isinstance(f, (list, tuple)): f = [f] feqs = [equify(g) for g in f if is_Expression(g) and g.operator() is operator.eq and not equify(g).is_zero()] f = [equify(g) for g in f if not (is_Expression(g) and g.operator() is operator.eq)] neqs = len(feqs) if neqs > 1: warn("There are at least 2 equations; If the region is degenerated to points, plotting might show nothing.") feqs = [sum([fn**2 for fn in feqs])] neqs = 1 if neqs and not bordercol: bordercol = incol if not f: return implicit_plot(feqs[0], xrange, yrange, plot_points=plot_points, fill=False, \ linewidth=borderwidth, linestyle=borderstyle, color=bordercol, **options) f_all, ranges = setup_for_eval_on_grid(feqs + f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in f_all[neqs::]],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) if outcol: outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol, alpha=alpha) else: outcol = rgbcolor('white') cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol, alpha=0) cmap.set_under(incol, alpha=alpha) g = Graphics() # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale == 'semilogy' or scale == 'semilogx': options['aspect_ratio'] = 'automatic' g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) if neqs == 0: g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(contours=[-1e-20, 0, 1e-20], cmap=cmap, fill=True, **options))) else: mask = numpy.asarray([[elt > 0 for elt in rows] for rows in xy_data_array], dtype=bool) xy_data_array = numpy.asarray([[f_all[0](x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], dtype=float) xy_data_array[mask] = None if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **options))) return g
X1, X2 = np.meshgrid( np.arange(start=X_set[:, 0].min() - 1, stop=X_set[:, 0].max() + 1, step=0.01), np.arange(start=X_set[:, 1].min() - 1, stop=X_set[:, 1].max() + 1, step=0.01)) # counterf function is responsible for actually dividing the the graph in two section. # i.e. the prediction boundary and colouring each section which is divided using prediction boundary. plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha=0.75, cmap=ListedColormap(colors)) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c=colors[i], label=j) plt.title('Classifier (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() # Visualising the Test set results from matplotlib.colors import ListedColormap
[24,203,255,255], [231,255,0,255], [231, 66, 0, 255], [226,143,122,255], [228,0,145,255], [226,164,43,255], [255,0,0,255], [255,151,0,255], [206,73,255,255], [142,5,10,255], [18,95,0,255], [8,212,125,255], [0,255,59,255], ])/255.1 from matplotlib.colors import ListedColormap mycmap = ListedColormap(colorlist[:,:3], 'segmentation') mycmap.set_bad(color=(0,0,0,0)) vols = config.vols.keys() class GetDices(object): def __init__(self, dir, title): self.dir = dir self.title = title self.dices = {'title': self.title} self.nsample = 0 def __call__(self, args, dirnames, fnames): dir = self.dir file_dice = args #args.pop('file_dice','dice_labels.txt') if file_dice in fnames: path = os.path.normpath(dirnames).split(os.sep)
import matplotlib.pyplot as plt import KNN1 iris2 = KNN1.iris2 print('3-圖表分析') print('後續將要進行顏色區分,將三種不同類型鳶尾花分別顯示') from matplotlib.colors import ListedColormap classes = ['setosa', 'versicolor', 'virginica'] colours = ListedColormap(['r', 'b', 'g']) fig = plt.figure(figsize=(12, 6)) ax1 = fig.add_subplot(2, 2, 1) ax2 = ax1.scatter(iris2['sepal_length'], iris2['sepal_width'], c=iris2['level'], cmap=colours) ax1.set_xlabel('sepal_length') ax1.set_ylabel('sepal_width') ax1.legend(handles=ax2.legend_elements()[0], labels=classes) # 各名稱的顏色 ax1 = fig.add_subplot(2, 2, 2) ax2 = ax1.scatter(iris2['petal_length'], iris2['petal_width'], c=iris2['level'], cmap=colours) ax1.set_xlabel('petal_length') ax1.set_ylabel('petal_width') ax1.legend(handles=ax2.legend_elements()[0], labels=classes) ax1 = fig.add_subplot(2, 2, 3) ax2 = ax1.scatter(iris2['sepal_length'], iris2['petal_width'], c=iris2['level'], cmap=colours) ax1.set_xlabel('sepal_length')
#plt.show() import numpy as np import healpy as hp import matplotlib.pyplot as plt from glob import glob def GetMapName(freq): indir = '/data/NEVERCOMMIT/' f = np.int(freq) filename = glob('/data/NEVERCOMMIT/*_%d_*fits' % f)[0] return filename ############### Universal colormap # setup linear colormap from matplotlib.colors import ListedColormap planck_freqmap_cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.) planck_freqmap_cmap.set_bad("gray") # color of missing pixels planck_freqmap_cmap.set_under("white") # color of background, necessary if you want to use # Graticule spacing in degrees grat_spacing = 10.0 imgsize = 750 imgresolution = 5. faces_to_do = np.arange(32) freq = sys.argv[1] # load a map mapfname = GetMapName(freq) I = hp.ma(hp.read_map(mapfname,field=0,verbose=True)) if np.int(freq)<500:
def aux_params(metalens): ''' Compute additional parameters. ''' metalens['aperture'] = 2 * metalens['R'] metalens['num of unit cells'] = int(metalens['aperture'] / metalens['unit cell size']) if metalens['num of unit cells'] % 2: pass else: metalens['num of unit cells'] += -1 metalens['ws'] = metalens['R'] metalens['fcen'] = 1 / metalens['wavelength'] metalens['n'] = np.sqrt(metalens['epsilon']) metalens['TIR_onset_coordinate'] = (np.tan(np.arcsin(1 / metalens['n'])) * metalens['H']) metalens['wavelength_rgb'] = wave_to_rgb(metalens['wavelength']) metalens['k'] = metalens['n'] * 2. * np.pi / metalens[ 'wavelength'] # inside dia metalens['cmap'] = ListedColormap( np.array([[ i / 255 * metalens['wavelength_rgb'][0], i / 255 * metalens['wavelength_rgb'][1], i / 255 * metalens['wavelength_rgb'][2], 1 ] for i in range(256)])) metalens['sim_cell_width'] = (2 * max(metalens['R'], metalens['w']) + 2 * metalens['pml_width'] + 2 * metalens['gap']) if metalens['w'] >= metalens['R']: metalens['sim_cell_width'] += 2 * metalens['gap'] metalens['sim_cell_height'] = (metalens['s'] + 2 * metalens['pml_width'] + metalens['post_height'] + metalens['d'] + 2 * metalens['gap']) metalens['source_coordinate'] = (-metalens['sim_cell_height'] / 2 + metalens['pml_width'] + metalens['gap']) metalens['top_of_posts_coordinate'] = (-metalens['sim_cell_height'] / 2 + metalens['pml_width'] + metalens['gap'] + metalens['s'] + metalens['post_height']) metalens['eta'] = metalens['w'] / metalens['R'] - 1 metalens['interface_coordinate'] = (-metalens['sim_cell_height'] / 2 + metalens['pml_width'] + metalens['s'] + metalens['gap']) metalens['source_width'] = 2. / metalens['fcen'] metalens['NA_c'] = (metalens['n'] * metalens['R'] / np.sqrt(metalens['R']**2 + metalens['H']**2)) metalens['simulation_time'] = ( metalens['source_width'] + (metalens['n'] * metalens['s'] / metalens['wavelength']) + ((np.sqrt(metalens['d']**2 + metalens['R']**2)) / metalens['wavelength'])) metalens['cell_width'] = metalens['simulation_parameters']['cell_width'] metalens['extent'] = [ -metalens['sim_cell_width'] / 2, metalens['sim_cell_width'] / 2, -metalens['sim_cell_height'] / 2, metalens['sim_cell_height'] / 2 ] metalens['detector_plane_coordinate'] = (metalens['sim_cell_height'] / 2 - metalens['pml_width'] - metalens['gap']) return metalens
def makeMap(timegrid,method,datadir,popfile,popcolormap,stationdict,citylist,elats,elons): figwidth = 8.0 bounds = timegrid.getRange() bounds = list(bounds) if bounds[1] < 0 and bounds[0] > bounds[1]: bounds[1] = bounds[1] + 360 clat = bounds[2] + (bounds[3] - bounds[2])/2 clon = bounds[0] + (bounds[1] - bounds[0])/2 dx = (bounds[1] - bounds[0])*111191 * np.cos(np.degrees(clat)) dy = (bounds[3] - bounds[2])*111191 aspect = np.abs(dy/dx) figheight = aspect * figwidth fig = plt.figure(figsize=(figwidth,figheight),edgecolor='g',facecolor='g') ax1 = fig.add_axes([0,0,1.0,1.0]) m = Basemap(llcrnrlon=bounds[0],llcrnrlat=bounds[2], urcrnrlon=bounds[1],urcrnrlat=bounds[3], resolution='h',projection='merc',lat_ts=clat) #get the population grid popgrid = EsriGrid(popfile) popgrid.load(bounds=bounds) popdata = np.flipud(popgrid.griddata) cmap = GMTColormap(popcolormap) clist = cmap.getColorList() boundaries = cmap.getZValues() palette = ListedColormap(clist,'my_colormap') i = np.where(np.isnan(popdata)) popdata[i] = -1 popdatam = np.ma.masked_values(popdata, -1) palette.set_bad(WATER_COLOR,1.0) ncolors = len(boundaries) am = m.imshow(popdatam,cmap=palette,norm=BoundaryNorm(boundaries,ncolors),interpolation='nearest') statgrid = np.flipud(timegrid.griddata) (lons,lats) = getLatLonGrids(timegrid) (x,y) = m(lons,lats) clevels = np.arange(MINTIME,MAXTIME+DTIME,DTIME) cs = m.contour(x,y,statgrid,clevels) #plt.clabel(cs, inline=1, fontsize=10) proxy = [plt.Rectangle((0,0),1,1,fc = pc.get_color()[0]) for pc in cs.collections] labels = [str(c)+' sec' for c in clevels] sx,sy = m(stationdict['lon'],stationdict['lat']) m.plot(sx,sy,'rD') plt.text(sx,sy,stationdict['code']) #plot the various epicenters for elat,elon in zip(elats,elons): ex,ey = m(elon,elat) m.plot(ex,ey,'k*') #plot the cities for city in citylist: cx,cy = m(city['lon'],city['lat']) m.plot(cx,cy,'.',color=CITY_COLOR) plt.text(cx,cy,city['name'],color=CITY_COLOR) m.drawrivers(color=WATER_COLOR) m.drawcountries(color='k',linewidth=2.0) mer = getMapLines(bounds[0],bounds[1]) par = getMapLines(bounds[2],bounds[3]) xmap_range = m.xmax-m.xmin ymap_range = m.ymax-m.ymin xoff = -0.09*(xmap_range) yoff = -0.04*(ymap_range) m.drawmeridians(mer,labels=[0,0,1,0],fontsize=8, linewidth=0.5,color='black',yoffset=yoff,xoffset=xoff,dashes=[1,0.01]) m.drawparallels(par,labels=[0,1,0,0],fontsize=8, linewidth=0.5,color='black',yoffset=yoff,xoffset=xoff,dashes=[1,0.01]) m.drawmapboundary(color='k',linewidth=2.0) plt.legend(proxy,labels) outfile = os.path.join(datadir,method+'.pdf') plt.savefig(outfile) plt.close()
# iterate over datasets for ds_cnt, ds in enumerate(datasets): # preprocess dataset, split into training and test part X, y = ds ##X = StandardScaler().fit_transform(X) X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size=0.01, random_state=42) x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # just plot the dataset first cm = plt.cm.RdBu cm_bright = ListedColormap(['#FF0000', '#0000FF']) ##cm = ListedColormap(['#FFAAAA', '#AAFFAA']) ##cm_bright = ListedColormap(['#FF0000', '#00FF00']) ax = plt.subplot(len(datasets), len(classifiers) + 1, i) if ds_cnt == 0: ax.set_title("Input data") # Plot the training points ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors='k') # Plot the testing points ax.scatter(X_test[:, 0], X_test[:, 1],
def main(): # White balanced colors = [(0, 0, 0), (24 , 24 , 112), ( 16 , 78 , 139), ( 23 , 116 , 205), ( 72 , 118 , 255), ( 91 , 172 , 237), ( 173 , 215 , 230), ( 209 , 237 , 237), ( 229 , 239 , 249), ( 242 , 255 , 255), ( 253 , 245 , 230), ( 255 , 228 , 180), ( 243 , 164 , 96), ( 237 , 118 , 0), ( 205 , 102 , 29), ( 224 , 49 , 15), ( 237 , 0 , 0), ( 205 , 0 , 0), ( 139 , 0 , 0)] colors = numpy.array(colors) / 255.0 colors = ["#FFFFFF", "#7FFF00", "#00CD00", "#008B00", "#104E8B", "#1E90FF", "#00B2EE", "#00EEEE", "#8968CD", "#912CEE", "#8B008B", "#8B0000", "#CD0000", "#EE4000", "#FF7F00", "#CD8500", "#FFD700", "#EEEE00", "#FFFF00", "#7FFF00","#000000"] cmap = ListedColormap(colors[1:]) cmap.set_over(color=colors[-1]) cmap.set_under(color=colors[-1]) #values = numpy.arange(0,10,0.25) #values = [0.01,0.05,0.1,0.25,0.5,0.75,1.0,1.25,1.5,1.75,2.0,2.5,3.0,4.0,5.0,7.5,10.0] values = [0.01,0.10,0.25,0.50,1.0,1.5,2.0,2.5,3.0,4.0,5.0,7.5,10.0,12.5,15.0,17.5,20.0] normer = BoundaryNorm(values, cmap.N, clip=False) ctx = {} nc = netCDF4.Dataset('/mesonet/data/iemre/2012_mw_daily.nc', 'r') lon = nc.variables['lon'][:] lat = nc.variables['lat'][:] ctx['llcrnrlon'] = numpy.min(lon) ctx['llcrnrlat'] = numpy.min(lat) ctx['urcrnrlon'] = numpy.max(lon) ctx['urcrnrlat'] = numpy.max(lat) setup_plot(ctx) idx = iemre.day_idx( mx.DateTime.DateTime(2012,3,1,1,5) ) idx2 = iemre.day_idx( mx.DateTime.DateTime(2012,4,1,1,5) ) tmpk = numpy.ma.array( numpy.sum(nc.variables['p01d'][idx:idx2,:,:],0) ) / 25.4 #nx = int((ctx['map'].xmax-ctx['map'].xmin)/40000.)+1 #ny = int((ctx['map'].ymax-ctx['map'].ymin)/40000.)+1 #rm_tmpk,x,y = ctx['map'].transform_scalar(tmpk,nc.variables['lon'], # nc.variables['lat'],nx,ny, # returnxy=True,masked=True) #print 'Content-Type: text/plain\n' #print numpy.min(rm_tmpk), numpy.max(rm_tmpk) tmpk.mask = numpy.where(tmpk < 0.01, True, False) im = ctx['map'].imshow(tmpk, cmap=cmap,interpolation='nearest',norm=normer,zorder=1) cax = plt.axes([0.932,0.2,0.015,0.6]) clr = ctx['fig'].colorbar(im, cax=cax, format='%g') clr.set_ticks(values) cax.text(-0.75, 0.5, 'Precipitation [inch]', transform=cax.transAxes, size='medium', color='k', horizontalalignment='center', verticalalignment='center', rotation='vertical') ctx['plotax'].text(0.05, -0.05, 'Test test test', ha='left', va='baseline', transform=ctx['plotax'].transAxes) nc.close() print "Content-Type: image/png\n" ctx['fig'].savefig(sys.stdout, format='png', edgecolor='k') """
# Visualizing the Training set Results from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid( np.arange(start=X_set[:, 0].min() - 1, stop=X_set[:, 0].max() + 1, step=0.01), np.arange(start=X_set[:, 1].min() - 1, stop=X_set[:, 1].max() + 1, step=0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha=0.75, cmap=ListedColormap(('magenta', 'indigo', 'cyan'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c=ListedColormap(('magenta', 'indigo', 'cyan'))(i), label=j) plt.title('Logistic Regression (Training Set)') plt.xlabel('PC1') plt.ylabel('PC2') plt.legend() plt.show() # Visualizing the Test set Results from matplotlib.colors import ListedColormap
def plot_decision_region(X, y, classifier, test_idx=None, resolution=0.02, title=''): markers = ('s', 'x', 'o', '^', 'v') # 점표시 모양 5개 정의 colors = ('r', 'b', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) #print('cmap : ', cmap.colors[0], cmap.colors[1], cmap.colors[2]) # decision surface 그리기 x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 0].min() - 1, X[:, 0].max() + 1 xx, yy = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) # xx, yy를 ravel()를 이용해 1차원 배열로 만든 후 전치행렬로 변환하여 퍼셉트론 분류기의 # predict()의 안자로 입력하여 계산된 예측값을 Z로 둔다. Z = classifier.predict(np.array([xx.ravel(), yy.ravel()]).T) Z = Z.reshape(xx.shape) #Z를 reshape()을 이용해 원래 배열 모양으로 복원한다. # X를 xx, yy가 축인 그래프상에 cmap을 이용해 등고선을 그림 plt.contourf(xx, yy, Z, alpha=0.5, cmap=cmap) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) X_test = X[test_idx, :] for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], c=cmap(idx), marker=markers[idx], label=cl) if test_idx: X_test = X[test_idx, :] plt.scatter(X_test[:, 0], X_test[:, 1], c='', linewidth=1, marker='o', s=80, label='testset') plt.xlabel('표준화된 꽃잎 길이') plt.ylabel('표준화된 꽃잎 너비') plt.legend(loc=2) plt.title(title) plt.show()
n_classes=2, n_redundant=0, n_clusters_per_class=1, random_state=7) # In[4]: reg_data, reg_target = datasets.make_regression(n_features=2, n_informative=1, n_targets=1, noise=5, random_state=7) # In[9]: colors = ListedColormap(['red', 'blue']) plt.scatter([i[0] for i in reg_data], [i[1] for i in reg_data], c=clf_target, cmap=colors) # In[10]: plt.scatter([i[0] for i in reg_data], reg_target, color='r') plt.scatter([i[1] for i in reg_data], reg_target, color='b') # In[11]: clf_train_data, clf_test_data, clf_train_labels, clf_test_labels = train_test_split( clf_data, clf_target, test_size=0.3, random_state=1) # In[12]:
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth,**options): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels - ``legend_label`` -- the label for this item in the legend EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)) A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase ``plot_points``:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400) To get plots where only one condition needs to be true, use a function. Using lambda functions, we definitely need the extra ``plot_points``:: sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), plot_points=400) The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200) The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s,t=var('s,t') sage: region_plot(s>0,(t,-2,2),(s,-2,2)) :: sage: region_plot(s>0,(s,-2,2),(t,-2,2)) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid import numpy if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **options))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **options))) return g
import numpy as np import matplotlib.cm as cm from matplotlib.colors import ListedColormap ############### CMB colormap from matplotlib.colors import ListedColormap colombi1_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt")/255.) colombi1_cmap.set_bad("gray") # color of missing pixels colombi1_cmap.set_under("gray") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colombi1_cmap) ############### CMB colormap planck_parchment_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt")/255.) #planck_parchment_cmap.set_bad("gray") # color of missing pixels planck_parchment_cmap.set_bad("lightslategray") # color of missing pixels #planck_parchment_cmap.set_under("white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=planck_parchment_cmap) planck_grey_cmap = cm.get_cmap('gray') ############### Universal colormap # setup linear colormap planck_freqmap_cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.) planck_freqmap_cmap.set_bad("gray") # color of missing pixels planck_freqmap_cmap.set_under("white") # color of background, necessary if you want to use # setup nonlinear colormap from matplotlib.colors import LinearSegmentedColormap class PlanckUniversalColormap(LinearSegmentedColormap): name = "planckuniv"