def plot_d18O(ax): if ax is ax1: ax.set_ylabel("Depth (cm)") else: plt.setp(ax.get_yticklabels(), visible=False) ax.yaxis.tick_right() im = ax.step(np.append(self.sample_profile.df.d18O.values[0], self.sample_profile.df.d18O.values), np.append(self.sample_profile.df.height_top.values, 0), where='post', color='#d62728') ax.set_title("d18O ($^{o}/_{oo}$)") xlim = ax.get_xlim() # Add shading for the ice type of sample sample ax.barh( self.sample_profile.layer_bot - (self.sample_profile.layer_bot - self.sample_profile.layer_top) / 2, np.repeat(xlim[1] - xlim[0], self.sample_profile.layer_top.__len__()), - (self.sample_profile.layer_bot - self.sample_profile.layer_top), np.repeat(xlim[0], self.sample_profile.layer_top.__len__()), color=cm.bone(pd.Categorical(self.sample_profile.df.ice_type).codes), alpha=0.2) # Add grid following the layering ax.barh(self.layers_bot - (self.layers_bot - self.layers_top) / 2, np.repeat(xlim[1] - xlim[0], self.layers_top.__len__()), - (self.layers_bot - self.layers_top), np.repeat(xlim[0], self.layers_top.__len__()), color='w', alpha=0.2, edgecolor='k', linewidth=0.5, linestyle=':') ax.set_xlim(xlim) ax.grid(axis='x', linewidth=0.5, linestyle=':') for tick in ax.get_xticklabels(): tick.set_rotation(45) return im
def visualize_modes(shape_model): mu, phi, sigma2 = shape_model K = phi.shape[1] n = 10 colors = [cm.bone(i) for i in np.linspace(0.35, 1, n)] for d in range(K): plt.gca().set_color_cycle(colors) for h_v in np.linspace(2, -2, n): h = np.zeros((K, 1)) h[d] = h_v s = mu + phi @ h s = s.reshape(-1, 2) plt.plot(s[:, 0], s[:, 1]) plt.savefig('mode{}.png'.format(d), transparent=True) plt.clf()
return field def normalize(field): return field / abs(field).max() def clip(field): return maximum(minimum(field, 1.0), -1.0) ion() #field = rand(1024, 1024) * 2.0 - 1.0 field = rand(512, 512) * 2.0 - 1.0 #field[200:300, :] = rand(100, 512) * 2.0 - 1.0 pic = imshow(field, cmap=cm.bone) img = cm.bone(field) pool = Pool(5) #image = gtk.Image() #pb = gtk.gdk.pixbuf_new_from_array((img * 128 + 128).astype(uint8), gtk.gdk.COLORSPACE_RGB, 8) #image.set_from_pixbuf(pb) #window = gtk.Window(type=gtk.WINDOW_TOPLEVEL) #window.set_size_request(512, 512) #window.add(image) #image.show() #window.show() for i in range(1000): # for j in range(10): # field = evolve_fft(field)
n0=nmax f_tm=np.transpose(np.array(fs))[None,:,:]*(np.ones(LMAX+1))[:,None,None] fish=cgf.get_fisher_dd(run_name,f_tm,n_ij_fid,do_print=False) return 1./np.sqrt(np.sum(fish)) sigma_tomo=np.array([get_sigma_tomo(i) for i in np.arange(nbins)+1]) plt.figure(); plt.plot(fishers/np.sum(fishers)); plt.plot(1-np.cumsum(fishers)/np.sum(fishers)) plt.figure(); plt.plot(sigma_cumul/sigma_cumul[-1]); plt.plot(sigma_tomo/sigma_cumul[-1]) #np.savetxt("sigmas_kl.txt",np.transpose([np.arange(nbins)+1,sigma_cumul])) np.savetxt("sigmas_tm.txt",np.transpose([np.arange(nbins)+1,sigma_tomo])) print sigma_tomo plt.figure(); nplot=10 for i in np.arange(nplot) : f=(i+0.5)/nplot plt.plot(zbarr,vv[10,:,i],'-',lw=2,color=cm.bone(f)) plt.show() ''' e_v,c_p_fid=diagonalize(c_ij_fid,np.linalg.inv(n_ij_fid)) c_p_dfn =change_basis(c_ij_dfn,metric,e_v) fisher=(larr+0.5)[:,None]*(c_p_dfn/c_p_fid)**2 isort=np.argsort(-np.sum(fisher,axis=0)) e_o=e_v[:,:,isort] f_o=np.array([np.dot(in_ij_fid[l],e_o[l,:,:]) for l in np.arange(LMAX+1)]) c_p_fid=change_basis(c_ij_fid,metric,e_o) c_p_dfn=change_basis(c_ij_dfn,metric,e_o) #Plot power spectrum of K-L modes if plot_stuff : plt.figure();
def scatter_plot(name, direc): """ This is a function which will generate the scatterplots with lots of variance Parameters: nameof_plot:name of the plot which will be saved. direc:directory Returns: ax : Axis of the plots fig :Figure of the plot x, y : The X and Y coordinates of the plots s : Size of the points categories_of_points : Categories of the points tick_size : Tick size on the plot xAxisPos, yAxisPos: Position of the labels of the axis. """ #using different stydes for plotting in matplotlib style = random.choice(styles) plt.style.use(style) #dpi and size of the ticks dpi = int( minimum_dpi + np.random.rand(1)[0] * (maximum_dpi - minimum_dpi) ) #randomly selecting dpi with predefined maximum dpi and minimum dpi values figsize = (figsize_min + np.random.rand(2) * (figsize_max - figsize_min)).astype( int) #randomly selecting the size of the figures tick_size = [(tick_size_width_min + np.random.rand(1)[0] * (tick_size_width_max - tick_size_width_min)), (tick_size_length_min + np.random.rand(1)[0] * (tick_size_length_max - tick_size_length_min))] tick_size.sort() fig, ax = plt.subplots(figsize=figsize, dpi=dpi) #ax=plt.axes() #using pandas to read the dataset (Bike Sharing Dataset) df = pd.read_csv("hour.csv") dataframe = pd.DataFrame(df) c = dataframe.iloc[:, 12] # reading the humidity column in the dataset d = dataframe.iloc[:, 16] # reading the count column in the dataset x = random.sample(c, 4) #taking 20 random values from the c column as X axis y = random.sample(d, 4) #taking 20 random values from the d column as Y axis # variance in points pointsVar = 1 + int( np.random.rand(1)[0] * max_points_variations) #setting up some random variance values pointsColors = 1 + int( np.random.rand(1)[0] * pointsVar ) #setting up the color of the points based on the variance values pointsMarkers = 1 + int( np.random.rand(1)[0] * (pointsVar - pointsColors) ) #setting up the markers of the points based on the variance values and colors pointsSize = max( 1, 1 + pointsVar - pointsColors - pointsMarkers ) #setting up the size of the points based on the variance values, colors and markers random_Color = np.random.rand(1)[0] if random_Color <= 0.5: colors = cm.jet( np.random.rand(pointsColors) ) #colormaps in matplotlib ## https://matplotlib.org/users/colormaps.html elif random_Color > 0.5 and random_Color <= 0.8: colors = cm.hot(np.random.rand(pointsColors)) else: colors = cm.bone(np.linspace(0, 0.6, pointsColors)) s_set = (maxPointSize + np.random.rand(pointsSize) * (maxPointSize - minPointSize))**2 markers_subset = list(np.random.choice(markers, size=pointsMarkers)) markers_empty = np.random.rand(1)[0] > 0.75 markers_empty_ratio = random.choice([0.0, 0.5]) #generating the plots using X and Y values s = [] categories_of_points = [] cat_dict = {} index_cat = 0 #zipped_data_x=[] #zipped_data_y=[] for i, j in zip(x, y): s_ = random.choice(s_set) c_ = random.choice(colors) m_ = random.choice(markers_subset) #zipped_data_x.append(chunked_data_x[i]) #zipped_data_y.append(chunked_data_y[j]) if m_ in diff_markers and markers_empty: e_ = np.random.rand(1)[0] > markers_empty_ratio else: e_ = False cat = [s_, c_, m_, e_] if category(cat, cat_dict) is False: cat_dict[index_cat] = cat index_cat += 1 categories_of_points.append(category(cat, cat_dict)) s.append(s_) if e_: plt.scatter(i, j, s=s_, color=c_, marker=m_, facecolors='none') else: plt.scatter(i, j, s=s_, color=c_, marker=m_) # padding between ticks and labels padX = max(tick_size[1] + 0.5, int(pad_min + np.random.rand(1)[0] * (pad_max - pad_min))) padY = max(tick_size[1] + 0.5, int(pad_min + np.random.rand(1)[0] * (pad_max - pad_min))) directionX = random.choice(tickDirection) directionY = random.choice(tickDirection) # tick prob ticksProb = np.random.rand(1)[0] # style and location of the ticks for the X axis if np.random.rand(1)[0] > 0.5: xAxisPos = 1 ax.xaxis.tick_top() ax.xaxis.set_label_position("top") if ticksProb > 0.8: ax.xaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=padX, direction=directionX, bottom=np.random.rand(1)[0] > 0.5, top=True) else: ax.xaxis.set_tick_params(bottom=np.random.rand(1)[0] > 0.5, top=True) if np.random.rand(1)[0] > 0.5: ax.spines['bottom'].set_visible( False) #setting up the axes position ax.xaxis.set_tick_params(bottom=False) if np.random.rand(1)[0] > 0.5: xAxisPos = np.random.rand(1)[0] ax.spines['top'].set_position( ('axes', xAxisPos)) #setting up the axes (X) position else: xAxisPos = 0 if ticksProb > 0.8: ax.xaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=padX, direction=directionX, bottom=True, top=np.random.rand(1)[0] > 0.5) else: ax.xaxis.set_tick_params(bottom=True, top=np.random.rand(1)[0] > 0.5) if np.random.rand(1)[0] > 0.5: ax.spines['top'].set_visible(False) ax.xaxis.set_tick_params(top=False) if np.random.rand(1)[0] > 0.5: xAxisPos = np.random.rand(1)[0] ax.spines['bottom'].set_position(('axes', xAxisPos)) # style and location of the ticks for the Y axis if np.random.rand(1)[0] > 0.5: yAxisPos = 1 ax.yaxis.tick_right() ax.yaxis.set_label_position("right") if ticksProb > 0.8: ax.yaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=padY, direction=directionY, left=np.random.rand(1)[0] > 0.5, right=True) else: ax.yaxis.set_tick_params(left=np.random.rand(1)[0] > 0.5, right=True) if np.random.rand(1)[0] > 0.5: ax.spines['left'].set_visible(False) ax.yaxis.set_tick_params(left=False) if np.random.rand(1)[0] > 0.5: yAxisPos = np.random.rand(1)[0] ax.spines['right'].set_position(('axes', yAxisPos)) else: yAxisPos = 0 if ticksProb > 0.8: ax.yaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=padY, direction=directionY, left=True, right=np.random.rand(1)[0] > 0.5) else: ax.yaxis.set_tick_params(left=True, right=np.random.rand(1)[0] > 0.5) if np.random.rand(1)[0] > 0.5: ax.spines['right'].set_visible(False) ax.yaxis.set_tick_params(right=False) if np.random.rand(1)[0] > 0.5: yAxisPos = np.random.rand(1)[0] ax.spines['left'].set_position(('axes', yAxisPos)) if ticksProb > 0.8: color_subtick = random.choice(color_subtick_list) length_subtick = 0.75 * np.random.rand(1)[0] * tick_size[1] if np.random.rand(1)[0] > 0.7: minorLocator = AutoMinorLocator() ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_tick_params(which='minor', length=length_subtick, direction=directionX, color=color_subtick, bottom=ax.spines['bottom'].get_visible(), top=ax.spines['top'].get_visible()) if np.random.rand(1)[0] > 0.7: minorLocator = AutoMinorLocator() ax.yaxis.set_minor_locator(minorLocator) ax.yaxis.set_tick_params(which='minor', length=length_subtick, direction=directionY, color=color_subtick, left=ax.spines['left'].get_visible(), right=ax.spines['right'].get_visible()) xmin = min(x) xmax = max(x) ignoreX = 0.05 * abs(xmax - xmin) plt.xlim(xmin - ignoreX, xmax + ignoreX) # avoiding the points to get start from the axis ymin = min(y) ymax = max(y) ignoreY = 0.05 * abs(ymax - ymin) plt.ylim(ymin - ignoreY, ymax + ignoreY) # font and size of the tick labels, axes labels and title font = random.choice(list_font) tickSize = int(SizeTickLabelMin + np.random.rand(1)[0] * (SizeTickLabelMax - SizeTickLabelMin)) axesSize = int(SizeAxisLabelMin + np.random.rand(1)[0] * (SizeAxisLabelMax - SizeAxisLabelMin)) titleSize = int(SizeTitleMin + np.random.rand(1)[0] * (SizeTitleMax - SizeTitleMin)) ticks_font = font_manager.FontProperties(fname=font, style='normal', size=tickSize, weight='normal', stretch='normal') axes_font = font_manager.FontProperties(fname=font, style='normal', size=axesSize, weight='normal', stretch='normal') title_font = font_manager.FontProperties(fname=font, style='normal', size=titleSize, weight='normal', stretch='normal') x_label = "humidity" y_label = "count" title = "Bike Sharing dataset" plt.xlabel(x_label, fontproperties=axes_font) plt.ylabel(y_label, fontproperties=axes_font, color='black') if xAxisPos == 1: plt.title(title, fontproperties=title_font, color='black', y=1.1) else: plt.title(title, fontproperties=title_font, color='black') for label in ax.get_xticklabels(): label.set_fontproperties(ticks_font) for label in ax.get_yticklabels(): label.set_fontproperties(ticks_font) # background colors if np.random.rand(1)[0] > 0.75: color_bg = (1 - colorbg_transparant_max ) + colorbg_transparant_max * np.random.rand(3) ax.set_axis_bgcolor(color_bg) if np.random.rand(1)[0] > 0.75: color_bg = (1 - colorbg_transparant_max ) + colorbg_transparant_max * np.random.rand(3) fig.patch.set_facecolor(color_bg) plt.tight_layout() plt.savefig("./data/{}/".format(direc) + name, dpi='figure', facecolor=fig.get_facecolor()) return ax, fig, x, y, s, categories_of_points, tick_size, xAxisPos, yAxisPos
def plot_solution_slots(solution, ax=None, xlim=None, colors=None, figsize=None, linewidth=None, kind="steps", colormaps=None, legend=True, pos_legend=None, amazon_or_azure=True): """ Plots allocations as a stacked area plot. It can be used both for load-level and for time-slot representations. Several customizations are possible through arguments. solution: the solution to plot, as provided by lloovia classes ax: the matplotlib axis in which to plot, useful for subplots. If None, a new figure is created xlim: the range to zoom. If None, the whole solution is plot colors: the colors to use for each instance class. This is a list of matplotlib colors. If there are more ICs than colors, those are recycled. If none, a sensible colormap is used, by using matplotlib palettes. figsize: a tuple containing the width and height (inches) for the figure linewidth: width (in points) of the line around areas. If None, 0.5 is used. kind: the kind of area. "steps" by default colormaps: it is a dictionary whose keys are regexps and the values are matplotlib palettes. The colors in the palette are used for all ICs whose name matches the regexp. This allows to assign similar colors to sets of ICs who share something in their names (eg: the region) legend: Boolean indicating if a legend should be shown pos_legend: a pair indicating where to put the legend. The first element is passed to matplotlib's "loc" parameter and the second one to matplotlib "bbox_to_anchor" parameter. If None, the default position would be centered below (outside) the plot. amazon_or_azure: is a boolean indicating whether the solution to plot correspond to instance classes from amazon or azure. If True, some heuristics are applied to guess from the instance attributes if it is an Amazon VM or an Azure VM, and this is used as part of the name of the instance class and for the colors of the legend (unless different colors were enforced through colors or colormaps parameters) """ # Make a copy, since we will alter the data to plot it stepwise df = solution.copy() # Clip-out unwanted xlim if xlim is not None: df = df[slice(*xlim)] # Remove unused Instance Classes df = df[df.columns[(df.fillna(0) != 0).any()]] # Reorder columns: first by provider, then by reserved vs. on-demand # then by efficiency (perf/price) with greatest efficiency first def order(s): efficiency = s.price / s.performance # Use the inverse if "US" in s.cloud.name: efficiency -= 10 if s.reserved: efficiency -= 10 return efficiency def order(s): efficiency = s.price / s.performance # Use the inverse r = "00" if s.reserved else "10" return "{}{}{}".format(r, s.cloud.name, efficiency) df = df[sorted(df.columns, key=order)] df.columns = prettify_names(df.columns, amazon_or_azure=amazon_or_azure) # Create the colormaps if colors is None: if colormaps is None: colormaps = {"Azure": cm.cool, "Amazon": cm.autumn} colors = [] zone_counter = {} for zone in colormaps.keys(): zone_counter[zone] = [1, len([x for x in df.columns if zone in x])] total_classes = len(df.columns) c_others = 0 for c in df.columns: for k in colormaps.keys(): if k in c: colors.append(colormaps[k](zone_counter[k][0] / zone_counter[k][1])) zone_counter[k][0] += 1 break else: colors.append(cm.bone(c_others / total_classes)) c_others += 1 if figsize is None: figsize = (4, 2.5) if linewidth is None: linewidth = 0.5 if pos_legend is None: pos_legend = ("upper center", (0.5, -0.25)) if ax is None: fig, ax = plt.subplots() if kind == "steps": # Double the data, to make a stepwise function aux = pd.DataFrame() for c in df.columns: y = df[c].values yy = np.array([y, y]).flatten("F") aux[c] = yy[1:] x = df.index aux["time"] = np.array([x, x]).flatten('F')[:-1] df = aux p = df.plot(x="time", ax=ax, kind="area", stacked=True, figsize=figsize, linewidth=linewidth, alpha=0.7, legend=False, color=colors, ylim=(0, None)) # Create the legend and put it outside if legend: handles, labels = p.get_legend_handles_labels() p.legend(reversed([ mpatches.Rectangle((0, 0), 1, 1, fc=handle.get_color(), linewidth=handle.get_linewidth(), alpha=handle.get_alpha()) for handle in handles[:len(df.columns)] ]), reversed(labels[:len(df.columns)]), loc=pos_legend[0], bbox_to_anchor=pos_legend[1]) else: p = df.plot(ax=ax, kind="bar", stacked=True, figsize=figsize, linewidth=linewidth, alpha=0.7, legend=False, color=colors, ylim=(0, None)) for container in ax.containers: plt.setp(container, width=1) ticks = ax.xaxis.get_ticklocs() ticklabels = [l.get_text() for l in ax.xaxis.get_ticklabels()] ax.xaxis.set_ticks(ticks[::5]) ax.xaxis.set_ticklabels(ticklabels[::5]) plt.tight_layout() if legend: handles, labels = ax.get_legend_handles_labels() ax.legend(reversed(handles), reversed(labels), loc=pos_legend[0], bbox_to_anchor=pos_legend[1]) ax.set_xlabel("Hour") ax.set_ylabel("Number of virtual machines") return p
return exp def find_nearest(array, value): ''' returns the index and value of the nearest value in an array. ''' idx = (abs(array - value)).argmin() return idx, array[idx] # get the models for BC03 tau = [1, 1.25, 1.5, 1.75, 2] models = [setup_models(5, t) for t in tau] # make some colored lines for the plots cm_subset = linspace(0.2, 0.8, len(tau)) colors = [cm.bone(x) for x in cm_subset] results = loadClusters() users = ['boada', 'felipe', 'doze'] for user in users: r_user = results[~results['Confidence_{}'.format(user)].isnull()] # now we loop over all of the results for i, (indx, c) in enumerate(r_user.Cluster.iteritems()): print(user, '--', c) bcg = r_user.iloc[i]['BCG_{}'.format(user)] bcg = int(bcg) # load the member data try:
def plot_results(lats, z, qs, name, norm, costs=None, cmap=magma, include_columns=False, column_label=None, titles=None, reference=None, wp="ice"): n_plots = len(qs) if not costs is None: height_ratios = [1.0] + [1.0] * n_plots + [0.1] n_panels = n_plots + 2 else: height_ratios = [1.0] * n_plots + [0.1] n_panels = n_plots + 1 if include_columns: n_panels += 1 height_ratios.insert(1, 1.0) f = plt.gcf() if f is None: f = plt.figure(figsize=(10, 15)) gs = GridSpec(n_panels, 1, height_ratios=height_ratios) #cmap.set_bad("grey", 1.0) x = lats y = z / 1e3 i = 0 # # OEM cost # prefix = [ "({})".format(l) for l in ["a", "b", "c", "d", "e", "f", "g", "h"] ] if not costs is None: ax = plt.subplot(gs[0]) inds = [] for i, c in enumerate(costs): inds += [c > 10.0] if not titles is None: ax.plot(x, c, c="C{0}".format(i), label=titles[i + 1]) ax.set_title(prefix[0] + " Final OEM cost", fontsize=14, loc="left") #ax.axhline(y = 10, c = "k") ax.legend(loc="center", ncol=3, fontsize=14, bbox_to_anchor=[0.5, 1.17]) ax.set_ylabel(r"$\chi^2_y$", fontsize=14) ax.set_xticks([]) ax.set_xlim([x[0], x[-1]]) ax.set_ylim([1e-3, 1e3]) ax.set_yscale("log") i = 1 # # Integrated quantities # if include_columns: ax = plt.subplot(gs[i]) qr = np.trapz(qs[0], x=z) for j, q in enumerate(qs[1:]): q = np.copy(q) inds = np.broadcast_to(np.reshape(z > 20e3, (1, -1)), q.shape) q[inds] = 0.0 qi = np.trapz(q, x=z) #ax.plot(x, qi, label = titles[j + 1]) ax.plot(x, 10.0 * np.log10(qi / qr), label=titles[j + 1], zorder=2) ax.set_ylabel(column_label, fontsize=14) ax.set_title(prefix[i] + " Column-integrated results", fontsize=14, loc="left") ax.set_xticks([]) ax.set_ylim([-5, 5]) #ax.set_yscale("log") ax.set_xlim([x[0], x[-1]]) ax.grid(False) if not reference is None: ax.set_zorder(10) ax2 = ax.twinx() ax.patch.set_visible(False) if wp == "ice": iwp = np.zeros(x.size) colors = ["k", "dimgrey", "grey", "lightgrey"] hatch = [r"", r"", r"", r""] handles = [] for j, s in enumerate(["swc", "iwc", "gwc", "hwc"]): iwp_s = np.trapz(reference[s], x=z) handles += [ ax2.fill_between(x, y1=iwp, y2=iwp + iwp_s, linewidth=1, edgecolor="white", alpha=0.7, facecolor=bone((j + 1) / 5), hatch=hatch[j], zorder=-10 - j) ] iwp = iwp + iwp_s labels = ["Snow", "Ice", "Graupel", "Hail"] ax2.set_ylim([1e-2, 1e2]) ax2.set_yscale("log") ax2.set_xlim([x[0], x[-1]]) ax2.set_ylabel(r"IWP, Reference [$\unit{kg\ m^{-2}}$]", fontsize=14, color=bone(2 / 5)) ax2.grid(False) ax2.legend(handles=handles, labels=labels, loc="center", ncol=4, fontsize=14, bbox_to_anchor=[0.5, 1.17]) if wp == "rain": colors = ["grey"] hatch = [r"", r"", r"", r""] handles = [] rwp = np.trapz(reference["rwc"], x=z) handles += [ ax2.fill_between(x, y1=rwp, y2=0.0, linewidth=1, alpha=0.7, facecolor=bone((2) / 5), zorder=-10 - j) ] ax2.set_ylim([1e-2, 1e2]) ax2.set_yscale("log") ax2.set_xlim([x[0], x[-1]]) labels = [] ax2.set_ylabel(r"RWP, Reference [$\unit{kg\ m^{-2}}$]", fontsize=14, color=bone(2 / 5)) ax2.grid(False) ax2.legend(handles=handles, labels=labels, loc="center", ncol=4, fontsize=14, bbox_to_anchor=[0.5, 1.17]) i = i + 1 for j in range(n_plots): ax = plt.subplot(gs[i + j]) q = qs[j] img = ax.pcolormesh(x, y, q.T, norm=norm, cmap=cmap) ax.set_ylim([0, 20]) ax.set_ylabel(r"Altitude [$\unit{km}$]", fontsize=14) if j < n_plots - 1: ax.set_xticks([]) else: ax.set_xlabel(r"Latitude [$\unit{^\circ \text{N}}$]", fontsize=14) if not titles is None: ax.set_title(prefix[j + i] + " " + titles[j], loc="left", fontsize=14) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(12) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(12) # # Colorbar # ax = plt.subplot(gs[-1]) cbar = plt.colorbar(img, cax=ax, orientation="horizontal", label=name, extend="both") cbar.ax.tick_params(labelsize=12) cbar.set_label(name, fontsize=14) plt.tight_layout() return f
# extract the last 2 values d = data[i][-2:] # select the data to compute the fitting function y = data[i][:-2] # use a polynomial of degree 3 c = np.polyfit(x, y, 3) # create a function out of those coefficients p = np.poly1d(c) # compute p on x2 values (we need integers, so the map) y2 = map(int, p(x2)) # create the bars for each element, on top of the previous bars bt = plt.bar(len(b1)+np.arange(len(d)), d, width=width/2, color=cm.hsv(32*(i)), bottom=b2_1) # create bars for the extrapolated values bt = plt.bar(len(b1)+np.arange(len(d))+width/2, y2, width=width/2, color=cm.bone(32*(i+2)), bottom=b2_2) # update the bottom array b2_1 += d b2_2 += y2 # label the X ticks with years plt.xticks(np.arange(len(years))+width/2, [int(year) for year in years]) # draw a legend, with a smaller font plt.legend(loc='upper left', prop=font_manager.FontProperties(size=7)) # save & show the graph plt.subplots_adjust(bottom=0.11, left=0.15)
#!/usr/bin/env python3 # # CLIMPORN # # L. Brodeau, November 2020 import sys import numpy as nmp from matplotlib import cm vcm = cm.bone(range(256)) (nl, nc) = nmp.shape(vcm) print('\n *** Shape of vcm =', nl, nc) if nl != 256 or nc != 4: print("Problem of shape") sys.exit(0) irgb = nmp.zeros((3, ), dtype=int) f = open('bone.ncmap', 'w') for jl in range(nl): for jc in range(3): irgb[jc] = int(round(255. * vcm[jl, jc], 0)) #print(irgb[:])
from pylab import rcParams from pylab import sqrt import matplotlib.cm as cm from numpy import mod from matplotlib.ticker import MaxNLocator GRAPH_COLOR = cm.summer LINE_STYLES = ['-', '-', '-', '-', '--', '--', '--', '--', ':', ':', ':', ':'] COLORS = [GRAPH_COLOR(0), cm.bone(196), GRAPH_COLOR(156), GRAPH_COLOR(210)] def calcShortFigSize(fig_width_pt=240.0): #fig_width_pt = 240.0 # Get this from LaTeX using \showthe\columnwidth inches_per_pt = 1.0 / 72.27 # Convert pt to inch golden_mean = (sqrt(5) - 1.0) / 2.0 # Aesthetic ratio fig_width = fig_width_pt * inches_per_pt # width in inches fig_height = fig_width * golden_mean # height in inches fig_size = [fig_width, fig_height - 50 * inches_per_pt] return fig_size def calcFigSize(fig_width_pt=240.0): #fig_width_pt = 240.0 # Get this from LaTeX using \showthe\columnwidth inches_per_pt = 1.0 / 72.27 # Convert pt to inch golden_mean = (sqrt(5) - 1.0) / 2.0 # Aesthetic ratio fig_width = fig_width_pt * inches_per_pt # width in inches fig_height = fig_width * golden_mean # height in inches fig_size = [fig_width, fig_height] return fig_size
c = np.polyfit(x, y, 3) # create a function out of those coefficients p = np.poly1d(c) # compute p on x2 values (we need integers, so the map) y2 = map(int, p(x2)) # create the bars for each element, on top of the previous bars bt = plt.bar(len(b1) + np.arange(len(d)), d, width=width / 2, color=cm.hsv(32 * (i)), bottom=b2_1) # create bars for the extrapolated values bt = plt.bar(len(b1) + np.arange(len(d)) + width / 2, y2, width=width / 2, color=cm.bone(32 * (i + 2)), bottom=b2_2) # update the bottom array b2_1 += d b2_2 += y2 # label the X ticks with years plt.xticks(np.arange(len(years)) + width / 2, [int(year) for year in years]) # draw a legend, with a smaller font plt.legend(loc='upper left', prop=font_manager.FontProperties(size=7)) # save & show the graph plt.subplots_adjust(bottom=0.11, left=0.15) plt.savefig('7900_09_06.png') plt.show()