def plot_weights(weights_file, title="weights", figure_width=16): with plt.style.context('seaborn-whitegrid'): weights = pd.read_csv(weights_file, sep="\t").iloc[::3] weights.iloc[:,:] = weights.iloc[:,:].astype('float64') weights = weights.apply(np.mean, axis=0).sort_values() abs_weights = abs(weights) ext_weights = max(abs_weights) colorbar_weights = [abs_weights, -abs_weights] colorbar_weights = pd.concat(colorbar_weights) fig = plt.figure(figsize=[figure_width,10]) ax = fig.add_subplot(1,1,1) colors = cm.RdBu((weights+max(abs_weights)) / float(ext_weights*2)) plot = plt.scatter(colorbar_weights, colorbar_weights, c = colorbar_weights, cmap = 'RdBu') plt.tick_params(labelsize=11) plt.clf() plt.colorbar(plot) plt.ylabel('Weight') #plt.title(title) weights.plot.bar(color=colors) plt.savefig("weights.svg", format="svg") return
def _animate(self, i): """given a list of new positions at a given timestep, plot those positions""" data = self.data[:i] xs = [] ys = [] zs = [] ious = [] for pos, iou in data: for x, y, z in np.nditer(pos, flags=['external_loop']): xs.append(x) ys.append(y) zs.append(z) ious.append(iou.flatten()) # print("agent ious ", ious) colors = cm.RdBu(ious) # map val to colormap if len(colors) != 0: colors = np.reshape(colors, (-1, 4)) # invalid nesting colors[:, -1] /= 10 if len(xs) > 0: # print("xs ys zs", xs, ys, zs) positions = np.vstack((xs, ys, zs)).T # print("agent positions ", np.shape(positions)) # print("animating agent ") # print("agent colors = ", np.shape(colors), colors) # print("anim positions ", positions.shape, positions) pc = self._plotCubeAt(positions, colors=colors, edgecolor="w") self.ax.add_collection3d(pc) # self.ax.scatter(xs, ys, zs, color=colors, marker="s") self.ax.view_init(30, 0.8 * self.counter) self.fig.canvas.draw() self.counter += 1
def plot_contourf(self,X0,X1,xx, yy, grid_confidence,x_range=None,y_range=None,xlabel=None,ylabel=None,figsize=(3.5,3.5),filename_out=None): fig = plt.figure(figsize=figsize) fig = self.turn_light_mode(fig) map_RdBu = [cm.RdBu(i) for i in numpy.linspace(0, 1, 15)] map_PuOr = [cm.PuOr(i) for i in numpy.linspace(0, 1, 15)] my_cmap = map_RdBu[7:][::-1] + map_PuOr[:7][::-1] my_cmap = colors.ListedColormap(my_cmap) #my_cmap = cm.coolwarm plt.contourf(xx, yy, grid_confidence, cmap=my_cmap, alpha=.25) plt.plot(X0[:, 0], X0[:, 1], 'ro', color='#1F77B4', alpha=0.75) plt.plot(X1[:, 0], X1[:, 1], 'ro', color='#FF7F0E', alpha=0.75) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.tight_layout() if x_range is not None:plt.xlim(x_range) if y_range is not None:plt.ylim(y_range) if filename_out is not None: plt.savefig(self.folder_out+filename_out,facecolor=fig.get_facecolor()) plt.close(fig) return
def polarization_intensity_to_color(data: xr.Dataset, vmax=None, pmax=1): """ Converts a dataset with intensity and polarization into a RGB colorarray. This consists of a few steps: 1. first we take the polarization to get a RdBu RGB value 2. We convert the RGB value to HSV 3. We use the relative intensity to compute a new value for the V ('value') channel 4. We convert back to RGB :param data: :return: """ if vmax is None: # use the 98th percentile data if not provided vmax = np.percentile(data.intensity.values, 98) rgbas = cm.RdBu((data.polarization.values / pmax + 1) / 2) slices = [slice(None) for _ in data.polarization.dims] + [slice(0, 3)] rgbs = rgbas[slices] hsvs = matplotlib.colors.rgb_to_hsv(rgbs) intensity_values = data.intensity.values.copy() / vmax intensity_values[intensity_values > 1] = 1 hsvs[:, :, 2] = intensity_values return matplotlib.colors.hsv_to_rgb(hsvs)
def make_plot(FileName, ColourMap): #create blank figure plt.figure(1, figsize=(6.6, 3.3)) #First plot the morphology through time # declare the file and the axis ProfileName = FileName + "ShoreProfile.xz" f = open(ProfileName, 'r') Lines = f.readlines() NoLines = len(Lines) StartTime = float(Lines[1].strip().split(" ")[0]) EndTime = float(Lines[-1].strip().split(" ")[0]) # Get info on vertical from header Header = np.array(Lines[0].strip().split(" "), dtype=np.float) CliffHeight = Header[0] dz = Header[1] # Only plot every 1 000 years PlotTime = StartTime PlotInterval = 100000 ax1 = plt.subplot(111) #Get header info and setup X coord for j in range(1, NoLines - 1): Line = (Lines[j].strip().split(" ")) Time = float(Line[0]) #Read morphology X = np.array(Line[1:], dtype="float64") NValues = len(X) Z = np.linspace(CliffHeight, -CliffHeight, NValues) if (Time >= PlotTime): colour = Time / StartTime ax1.plot(X, Z, '-', lw=1.5, color=cm.RdBu(colour)) PlotTime += PlotInterval ax1.plot(X, Z, 'k-', lw=1.5) print Z[0], Z[-1] # tweak the plot #ax1.set_xticklabels([]) plt.xlabel("Distance (m)") plt.ylabel("Elevation (m)") xmin, xmax = ax1.get_xlim() #plt.xlim(xmin-10,xmax+10) #plt.ylim(-CliffHeight,CliffHeight) #plt.ylim(-30,30) plt.tight_layout() plt.show()
def _blob(x, y, w, w_max, area): """ Draws a square-shaped blob with the given area (< 1) at the given coordinates. """ hs = sqrt(area) / 2 xcorners = array([x - hs, x + hs, x + hs, x - hs]) ycorners = array([y - hs, y - hs, y + hs, y + hs]) fill(xcorners, ycorners, color=cm.RdBu(int((w + w_max) * 256 / (2 * w_max))))
def test_center_cmap(): """Test centering of colormap.""" from matplotlib.colors import LinearSegmentedColormap from matplotlib.pyplot import Normalize cmap = center_cmap(cm.get_cmap("RdBu"), -5, 10) assert isinstance(cmap, LinearSegmentedColormap) # get new colors for values -5 (red), 0 (white), and 10 (blue) new_colors = cmap(Normalize(-5, 10)([-5, 0, 10])) # get original colors for 0 (red), 0.5 (white), and 1 (blue) reference = cm.RdBu([0., 0.5, 1.]) assert_allclose(new_colors, reference) # new and old colors at 0.5 must be different assert not np.allclose(cmap(0.5), reference[1])
def plot_discs(radii, importances, r_pred, signs=None): phenotypes = ['tumor', 'foxp3', 'cd8', 'cd4', 'pdmac', 'other'] importances = np.array(importances) max_val = np.max(np.abs(importances)) norm = plt.Normalize(vmin=-max_val, vmax=max_val) if signs is not None: importances = np.multiply(signs, importances) colors = cm.RdBu(norm(importances)) fig, ax = plt.subplots(nrows=2, ncols=4) # c1 = plt.Circle((0.5, 0.5), 0.05 / max(radii), color=colors[0,0]) # ax[0,0].add_artist(c1) for phen in range(importances.shape[0]): for r, val in reversed(zip(radii, colors[phen, :])): ax[_2(phen)].add_patch( patches.Circle((0, 0), r / max(radii), fill=True, edgecolor='k', linewidth=0.5, facecolor=val)) ax[_2(phen)].add_patch( patches.Circle((0, 0), r_pred / max(radii), fill=False, edgecolor='k', linewidth=1)) ax[_2(phen)].axis('equal') ax[_2(phen)].set_xlim([-1.2, 1.2]) ax[_2(phen)].set_ylim([-1.2, 1.2]) ax[_2(phen)].set_xticklabels([]) ax[_2(phen)].set_yticklabels([]) ax[_2(phen)].set_xticks([]) ax[_2(phen)].set_yticks([]) ax[_2(phen)].set_title(phenotypes[phen]) for elem in ['bottom', 'top', 'left', 'right']: ax[_2(phen)].spines[elem].set_visible(False) plt.show()
def dump_explanation(self, path, x, z_true, z_pred): fig, axes = plt.subplots(1, 2, sharey=True) x = x[:-1].reshape(5, 5, 4) for i, z in enumerate([z_true, z_pred]): axes[i].set_aspect('equal') z = z[:-1].reshape(5, 5, 4) axes[i].imshow(self._ohe_to_raw(x), interpolation='nearest') for r, c in product(range(5), repeat=2): index = np.argmax(x[r, c]) coeff = z[r, c, index] if np.abs(coeff) >= 1e-2: color = cm.RdBu(0.5 * coeff + 0.5) axes[i].add_patch(Circle((c, r), 0.35, color=color)) fig.savefig(path, bbox_inches=0, pad_inches=0) plt.close(fig)
def prep_data_for_voxels(data): # 320 data = normalize(data) # print("data shape working ", data) facecolors = cm.RdBu(data) # makes the alpha equal to the voxel value. facecolors[:, :, :, -1] = data / 5 # /20 to reduce alpha # facecolors = explode(facecolors) filled = facecolors[:, :, :, -1] != 0 # print("fill shape" , filled.shape, "filled", filled) x, y, z = expand_coordinates(np.indices(np.array(filled.shape) + 1)) # print("x shape", x.shape, "X", x[1]) # set point-of-view: specified by (altitude degrees, azimuth degrees) # static facecolor w some transparency: "#1f77b430" # print("working filled ", filled) # ax.voxels(x, y, z, filled, facecolors=facecolors, edgecolor='#1f77b430') return (x, y, z, filled, facecolors, '#1f77b430')
def draw_pie_graph(self, data_frame): """绘制饼图""" label = data_frame["label"] number = data_frame["number"] # 创建一个图像对象和子图 fig, axes = plt.subplots(figsize=(10, 6), ncols=2) # 创建两个子图 ax1, ax2 = axes.ravel() # 设置颜色 colors = cm.RdBu(np.arange(len(number)) / len(number)) # 生成图片 ax1.axis('equal') ax1.set_title('职位分布', loc='center') patches, texts = ax1.pie(number, labels=None, shadow=False, startangle=0, colors=colors) # 图例 ax2.axis('off') ax2.legend(patches, label, loc='center left', fontsize=8) # 保存 支持eps, pdf, pgf, png, ps, raw, rgba, svg, svgz等格式 plt.savefig('job_distribute.png')
def plot_graph(y_axis_value): prob_map = {} for year in dfT.keys(): mean_value = mean_df[year] yerr = yerr_df[year] lower_limit = mean_value - yerr upper_limit = mean_value + yerr if y_axis_value < lower_limit: prob = 1 elif y_axis_value > upper_limit: prob = 0 else: prob = min(abs(mean_value - y_axis_value) / yerr, 1) prob_map[year] = prob df_prob_map = pd.Series(prob_map) prob_range = df_prob_map.values colors = cm.RdBu(prob_range / float(max(prob_range))) #plot = plt.scatter(prob_range, prob_range, c=prob_range, cmap='RdBu') plt.clf() plt.colorbar(plot) plt.bar(df_prob_map.index, mean_df.values, color=colors) plt.xticks(df_prob_map.index, [str(i) for i in df_prob_map.index]) # plot.spines['top'].set_visible(False) line, = plt.plot(plt.xlim(), [y_axis_value, y_axis_value], 'k-', color=('blue'), lw=2, label="_not in legend") plt.gca().set_title('Distributions mean and confidence interval') plt.show()
def colourmaps(): ''' Plot utility, define a few colourmaps which scale to transparent at their zero values ''' cmaps = [cm.Blues, cm.Greens, cm.Reds, cm.Purples, cm.Greys] cname = [ 'Blues_alpha', 'Greens_alpha', 'Reds_alpha', 'Purples_alpha', 'Greys_alpha' ] nc = 256 for ii in range(len(cmaps)): col_arr = cmaps[ii](range(nc)) col_arr[:, -1] = np.linspace(0, 1, nc) map_obj = LinearSegmentedColormap.from_list(name=cname[ii], colors=col_arr) plt.register_cmap(cmap=map_obj) col_arr = cm.RdBu(range(nc)) col_arr[:, -1] = abs(np.linspace(-1, 1, nc)) map_obj = LinearSegmentedColormap.from_list(name='RdBu_alpha', colors=col_arr) plt.register_cmap(cmap=map_obj)
fig,ax = plt.subplots() for q in qval: # Unit normalization of the kernel for discrete convolution kernelfunc = copy.deepcopy(K['F']); kernelfunc /= np.sum(kernelfunc) # Discrete convolution I_del = tools.conv_(I[key], kernelfunc) print(f'max(I) = {np.max(I[key])}, max(I_del) = {np.max(I_del)}') y = tools.find_delay(t=t, F=I[key], Fd=I_del, rho=q) plt.plot(t, y, label=f'$\\epsilon = {q:0.2f}$', color=cm.RdBu(1-q/np.max(qval))) plt.legend(loc=1) plt.ylim([0,None]) plt.xlim([0,100]) plt.xticks(np.arange(0,110,10)) plt.ylabel('$\\Delta t$ [days] | $\\frac{(K \\ast I)(t + \\Delta t)}{I(t)} = \\epsilon$') plt.xlabel('$t$ [days]') plt.title(f'${key}$') plt.savefig(f'{plotfolder}/cone_{k}.pdf', bbox_inches='tight') #plt.show() k += 1
lr2 = LR() lr1.fit(X=ftle_ts.values[mask_].reshape(-1, 1), y=result['PCA0'].values[mask_].reshape(-1, 1)) lr2.fit(X=ftle_ts.values[~mask_].reshape(-1, 1), y=result['PCA0'].values[~mask_].reshape(-1, 1)) predicted1 = lr1.predict(X=ftle_ts.values[mask_].reshape(-1, 1)) predicted2 = lr2.predict(X=ftle_ts.values[~mask_].reshape(-1, 1)) plt.figure(figsize=[10, 10]) plt.scatter(ftle_ts, result['PCA0'].values, c=colors, cmap='RdBu', alpha=0.7, s=pr_ts.values) plt.plot(ftle_ts.values[mask_], predicted1, color=cm.RdBu(500), lw=1.8) plt.plot(ftle_ts.values[~mask_], predicted2, color=cm.RdBu(0), lw=1.8) plt.xlabel('FTLE') plt.ylabel('PC1') plt.legend(['Origin North', 'Origin South']) plt.savefig('tempfigs/diagnostics/LinReg.pdf') plt.close() LR1 = lr1.score(X=ftle_ts.values[mask_].reshape(-1, 1), y=result['PCA0'].values[mask_].reshape(-1, 1)) LR2 = lr2.score(X=ftle_ts.values[~mask_].reshape(-1, 1), y=result['PCA0'].values[~mask_].reshape(-1, 1)) print(f'R2 statistics for fit1 is {LR1} and for fit 2 is {LR2}') amazon_xs = MAG.amazon.longitude.where( MAG.amazon == 1 ).values[~np.isnan(MAG.amazon.longitude.where(MAG.amazon == 1).values)]
def plot_wigner_function(state, res=100, figsize=None): """Plot the equal angle slice spin Wigner function of an arbitrary quantum state. Args: state (np.matrix[[complex]]): - Matrix of 2**n x 2**n complex numbers - State Vector of 2**n x 1 complex numbers res (int) : number of theta and phi values in meshgrid on sphere (creates a res x res grid of points) figsize (tuple): Figure size in inches. Returns: matplotlib.Figure: The matplotlib.Figure of the visualization Raises: ImportError: Requires matplotlib. References: [1] T. Tilma, M. J. Everitt, J. H. Samson, W. J. Munro, and K. Nemoto, Phys. Rev. Lett. 117, 180401 (2016). [2] R. P. Rundle, P. W. Mills, T. Tilma, J. H. Samson, and M. J. Everitt, Phys. Rev. A 96, 022117 (2017). """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') if figsize is None: figsize = (11, 9) state = np.asarray(state) if state.ndim == 1: state = np.outer(state, state) # turns state vector to a density matrix num = int(np.log2(state.shape[0])) # number of qubits phi_vals = np.linspace(0, np.pi, num=res, dtype=np.complex_) theta_vals = np.linspace(0, 0.5*np.pi, num=res, dtype=np.complex_) # phi and theta values for WF w = np.empty([res, res]) harr = np.sqrt(3) delta_su2 = np.zeros((2, 2), dtype=np.complex_) # create the spin Wigner function for theta in range(res): costheta = harr*np.cos(2*theta_vals[theta]) sintheta = harr*np.sin(2*theta_vals[theta]) for phi in range(res): delta_su2[0, 0] = 0.5*(1+costheta) delta_su2[0, 1] = -0.5*(np.exp(2j*phi_vals[phi])*sintheta) delta_su2[1, 0] = -0.5*(np.exp(-2j*phi_vals[phi])*sintheta) delta_su2[1, 1] = 0.5*(1-costheta) kernel = 1 for _ in range(num): kernel = np.kron(kernel, delta_su2) # creates phase point kernel w[phi, theta] = np.real(np.trace(state.dot(kernel))) # Wigner function # Plot a sphere (x,y,z) with Wigner function facecolor data stored in Wc fig = plt.figure(figsize=figsize) ax = fig.gca(projection='3d') w_max = np.amax(w) # Color data for plotting w_c = cm.RdBu((w+w_max)/(2*w_max)) # color data for sphere w_c2 = cm.RdBu((w[0:res, int(res/2):res]+w_max)/(2*w_max)) # bottom w_c3 = cm.RdBu((w[int(res/4):int(3*res/4), 0:res]+w_max) / (2*w_max)) # side w_c4 = cm.RdBu((w[int(res/2):res, 0:res]+w_max)/(2*w_max)) # back u = np.linspace(0, 2 * np.pi, res) v = np.linspace(0, np.pi, res) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) # creates a sphere mesh ax.plot_surface(x, y, z, facecolors=w_c, vmin=-w_max, vmax=w_max, rcount=res, ccount=res, linewidth=0, zorder=0.5, antialiased=False) # plots Wigner Bloch sphere ax.plot_surface(x[0:res, int(res/2):res], y[0:res, int(res/2):res], -1.5*np.ones((res, int(res/2))), facecolors=w_c2, vmin=-w_max, vmax=w_max, rcount=res/2, ccount=res/2, linewidth=0, zorder=0.5, antialiased=False) # plots bottom reflection ax.plot_surface(-1.5*np.ones((int(res/2), res)), y[int(res/4):int(3*res/4), 0:res], z[int(res/4):int(3*res/4), 0:res], facecolors=w_c3, vmin=-w_max, vmax=w_max, rcount=res/2, ccount=res/2, linewidth=0, zorder=0.5, antialiased=False) # plots side reflection ax.plot_surface(x[int(res/2):res, 0:res], 1.5*np.ones((int(res/2), res)), z[int(res/2):res, 0:res], facecolors=w_c4, vmin=-w_max, vmax=w_max, rcount=res/2, ccount=res/2, linewidth=0, zorder=0.5, antialiased=False) # plots back reflection ax.w_xaxis.set_pane_color((0.8, 0.8, 0.8, 1.0)) ax.w_yaxis.set_pane_color((0.8, 0.8, 0.8, 1.0)) ax.w_zaxis.set_pane_color((0.8, 0.8, 0.8, 1.0)) ax.set_xticks([], []) ax.set_yticks([], []) ax.set_zticks([], []) ax.grid(False) ax.xaxis.pane.set_edgecolor('k') ax.yaxis.pane.set_edgecolor('k') ax.zaxis.pane.set_edgecolor('k') ax.set_xlim(-1.5, 1.5) ax.set_ylim(-1.5, 1.5) ax.set_zlim(-1.5, 1.5) m = cm.ScalarMappable(cmap=cm.RdBu) m.set_array([-w_max, w_max]) cbar = plt.colorbar(m, shrink=0.5, aspect=10, ticks=[-1, -0.5, 0, 0.5, 1.0]) cbar.ax.tick_params(labelsize=14) plt.close(fig) return fig
confd_val = 1.96 * (std_val / math.sqrt(len(df.columns))) # fraction of data that is above the cutoff line def Norm(data): return (data - np.min(data)) / (np.max(data) - np.min(data)) up_bound = mean_val + confd_val lower_bound = mean_val - confd_val confd_length = confd_val*2 cutoff = 42500 fraction = (up_bound - cutoff)/confd_length x_sticks=['1992','1993','1994','1995'] colors = cm.RdBu(fraction) my_cmap = plt.cm.get_cmap('RdBu') fig = plt.figure() ax1 = fig.add_subplot(111) xxx = ax1.bar(x_ndx,mean_val,color=colors,tick_label=x_sticks, yerr=confd_val, error_kw=dict(ecolor='black', lw=1, capsize=2.5, capthick=2)) ax1.axhline(y=cutoff, color='grey', linestyle='--') ax1.set_xlim(0,4) ax1.set_ylim(0,55000) majors = [0.5,1.5,2.5, 3.5] ax1.xaxis.set_major_locator(ticker.FixedLocator(majors))
#plt.title('ORN Response') plt.savefig(odor_path.split('/')[-1] + "_" + 'ORN Response.png', transparent=True) # Plot the ORN Traces from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm fig = plt.figure() fig.patch.set_alpha(0.0) ax = fig.add_subplot(111, projection='3d') ax.patch.set_alpha(0.0) ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) order = np.argsort(orns[:100, :].mean(axis=1)) color = cm.RdBu(np.arange(0, order[::-1].shape[0])) for n, i in enumerate(order[::-1]): ax.plot(5 * n * np.ones(orns[i, ::100].shape), np.arange(0, orns[i, ::100].shape[0]), orns[i, ::100], alpha=1) #plt.ylabel('Time (in ms)') #plt.xlabel('Cell Type') #plt.title('ORN Traces') ax.grid(False) plt.axis('off') plt.savefig(odor_path.split('/')[-1] + "_" + 'ORN Traces.png') # Plot EAD plt.figure() plt.plot(orns.mean(axis=0))
from requests_toolbelt import MultipartEncoder import requests url = 'http://www.kegg.jp/kegg-bin/mcolor_pathway' node_colors = {} if input_data is not None: mini, maxi = input_data.max().max(), input_data.min().min() mapi = np.linspace(mini, maxi, 255) color = lambda x: mapi[np.abs(mapi - x).argmin()] if mini < 0: # We're using a linear zero-centered map cmap = cm.RdBu(x) else: # We're using a linear zero-based map cmap = cm.PuOr(x) scale = utils.calculate_scale([mini, 0, maxi], [9, 1], out=np.around) # rdbu9 scale #for n, m in enumerate(dsi.entities[1]): # xref = self.get_xref( m ) for n, m in enumerate(dsi.entities[1]): if m: if 'LIGAND-CPD' in m.databases:
# verts[verts[:, 0] > 0, 0] -= 20 # verts[verts[:, 0] < 0, 0] += 20 val = np.real(sig2[ind]) fig = plt.figure() ax = Axes3D(fig) ax.view_init(90,90) ax.axis('equal') poly1 = plot_trimesh(verts,faces,val) val1 = np.array(val) # To be safe - set_array() will expect a numpy array val1_norm = (val1-val1.min()) / (val1.max() - val1.min()) #val1_norm = val1 norm = colors.SymLogNorm(vmin=val1.min(), vmax=val1.max(),linthresh=0.1) #colormap = cm.seismic(norm(val1)) colormap = cm.RdBu(norm(val1)) poly1.set_facecolor(colormap) poly1.set_edgecolor('white') poly1.set_linewidth(0.0) ax.add_collection3d(poly1) ax.set_xlim3d(verts[:,0].min(), verts[:,0].max()) ax.set_ylim3d(verts[:,1].min(), verts[:,1].max()) ax.set_zlim3d(verts[:,2].min(), verts[:,2].max()) ax.autoscale_view() plt.axis('off') plt.savefig(savedir + sim[:-4] + "_charge_at_"+ str(int(round(wl[ind]))) +"nm_top.png", dpi=1200) #plt.savefig(savedir + sim[:-4] + "_charge_at_"+ str(int(round(wl[ind]))) +"nm_top.pgf") plt.savefig(savedir + sim[:-4] + "_charge_at_"+ str(int(round(wl[ind]))) +"nm_top.pdf", dpi=1200) #plt.show() plt.close()
axi += 1 ax3[0][0].legend() OData = pd.concat([OData, fit_df], axis=1) #add the fit data to the output OData = pd.concat([OData, OtherData], axis=1) #add the other data to the output OData.to_csv(path + 'O3AnalysisOutput.csv') #save to file fig3.set_size_inches(12, 9) fig3.savefig(path + 'Fits.png') if (1 == 2): #takes a lot of time and so can turn off by making if false cdata = cdata[ ['t'] + O3col + Tcol + Hcol] #cdata=cdata[['t']+O3col+Tcol+Hcol+COcol] get rid of what we don't want sax = pd.plotting.scatter_matrix(cdata, alpha=0.1, diagonal='kde', figsize=(12, 12), s=5) #make fancy scatter plot corr = cdata.corr().as_matrix() #get correlation coeff for i, j in zip(*plt.np.triu_indices_from( sax, k=1)): #format scatter plot to show corr sax[i, j].annotate("%.3f" % corr[i, j], (0.5, 0.2), xycoords='axes fraction', ha='center', va='center', backgroundcolor=(1, 1, 1)) c = 1 - (corr[i, j] - corr.min()) / (corr.max() - corr.min()) sax[i, j].set_facecolor(cm.RdBu(c / 2 + .25)) sax[j, i].set_facecolor(cm.RdBu(c / 2 + .25)) plt.suptitle('Scatter Matrix') plt.savefig(path + 'ScatterMatrix.png')
def set_plot_colors(plot_lines, studies, div_name, bgcolor, grey_scale, restrict_colors=None): rr = RunRecord('set_plot_colors') min_col = 0 max_col = 1 if restrict_colors: col_limits = restrict_colors.split(',') min_col, max_col = (float(col_limits[0]), float(col_limits[1])) # Hack time: this is just for David's Cell-cycle plots num_studies = len(studies) if div_name: # one study doesn't count for coloring num_studies -= 1 if num_studies == 3 and len(plot_lines) == 3: # We're going to use black/white, green and magenta, for G1, M, S if bgcolor == 'black': r = 255; g = 255; b = 255 # white else: r = 0; g = 0; b = 0 # black plot_lines[0].color = '#%02x%02x%02x' % (r, g, b) # green for M r = 0; g = 130; b = 0 plot_lines[1].color = '#%02x%02x%02x' % (r, g, b) # Magenta for S r = 255; g = 0; b = 255 plot_lines[2].color = '#%02x%02x%02x' % (r, g, b) elif num_studies > 1: # give each study a new colour and increase decrease alpha with rank # separate out plotlines per study per_study_lines = {} for line in plot_lines: study = line.study if study in per_study_lines.keys(): per_study_lines[study].append(line) else: per_study_lines[study] = [line] plot_lines = [] for i,s in zip(numpy.linspace(min_col, max_col, num_studies), per_study_lines.keys()): study_color = cm.jet(i) # cm.rainbow(i) rgba = colors.colorConverter.to_rgba(study_color) for study in studies: if s == study.collection_label: for l,alpha in zip(sorted(per_study_lines[s], key=lambda x: x.rank), numpy.linspace\ (0, 0.7, len(per_study_lines[s]))): r, g, b, a = rgba l.color = (r,g,b,a-alpha) l.alpha = a-alpha plot_lines.append(l) elif num_studies == 1 and grey_scale: # grey-scale spectrum. Since background is white or black we can't # have lines that are pure black or white. if bgcolor == 'black': for i, line in enumerate(plot_lines): # todo: replace this is with linspace and black/white col = (240/len(plot_lines)) + ((240/len(plot_lines))*i) r = col; g = col; b = col line.color = '#%02x%02x%02x' % (r, g, b) else: # white background for i, line in enumerate(plot_lines): col = 240 - ((240/len(plot_lines))*i) r = col; g = col; b = col line.color = '#%02x%02x%02x' % (r, g, b) elif num_studies == 1: # coolwarm, RdBu, jet - all decent options # make sure plots get coloured such that genes with low expr (large # number for rank get plotted blue plot_lines = sorted(plot_lines, key=lambda p: p.rank) # For our own plots use 0.05 and 0,85 for min_col, max_col for l,i in zip(plot_lines, numpy.linspace(min_col, max_col, len(plot_lines))): l.color = cm.RdBu(i) return plot_lines
#读取森林地图底图 #Normalize归一化 #np.clip(x,a,b)将x中小于a的值设为a,大于b的值设为b #cm.bwr 蓝白红 bg = imread('erangel.jpg') hmap, extent = heatmap(plot_data_ev[:,0], plot_data_ev[:,1], 1.5, bins =800) alphas = np.clip(Normalize(0, hmap.max()/100, clip=True)(hmap)*1.5,0.0,1.) colors = Normalize(hmap.max()/100, hmap.max()/20, clip=True)(hmap) colors = cm.bwr(colors) colors[..., -1] = alphas hmap2, extent2 = heatmap(plot_data_ek[:,0],plot_data_ek[:,1],1.5, bins = 800) alphas2 = np.clip(Normalize(0, hmap2.max()/100, clip = True)(hmap2)*1.5, 0.0, 1.) colors2 = Normalize(hmap2.max()/100, hmap2.max()/20, clip=True)(hmap2) colors2 = cm.RdBu(colors2) colors2[...,-1] = alphas2 #'森林死亡率图' fig, ax = plt.subplots(figsize = (24,24)) ax.set_xlim(0, 4096);ax.set_ylim(0, 4096) ax.imshow(bg) ax.imshow(colors, extent = extent, origin = 'lower', cmap = cm.bwr, alpha = 1) #ax.imshow(colors2, extent = extent2, origin = 'lower', cmap = cm.RdBu, alpha = 0.5) plt.gca().invert_yaxis() plt.title('森林地图死亡率图') #森林击杀图 fig, ax = plt.subplots(figsize = (24,24)) ax.set_xlim(0, 4096); ax.set_ylim(0, 4096) ax.imshow(bg)
axScatter.axhline(y=0.0, color='k', linestyle='--') axScatter.axvline(x=0.0, color='k', linestyle='--') # now determine nice limits by hand: binwidth = 0.25 xymax = np.max([np.max(np.fabs(X)), np.max(np.fabs(Y))]) lim = (int(xymax / binwidth) + 1) * binwidth bins = np.arange(-lim, lim + binwidth, binwidth) axHistx.hist(X, bins=bins, color=c, alpha=0.5, edgecolor='k') axHisty.hist(Y, bins=bins, orientation='horizontal', color=c, alpha=0.5, edgecolor='k') axHistx.set_xlim(axScatter.get_xlim()) axHisty.set_ylim(axScatter.get_ylim()) plt.clf() r_cohort = log_test.prediction_tracker['label'].dropna().unique() colors = cm.RdBu(np.linspace(0, 1, len(r_cohort))) c = 0 r_cohort.sort() for x in r_cohort: plot_dual_histogram(log_test.prediction_tracker, 'label', x, 'grey', switch=True) plot_dual_histogram(log_test.prediction_tracker, 'label', x, colors[c], switch=False) c += 1 plt.show() plt.clf() """ ******************************************************************************** ANALYZING THE DATA WITH NEURAL NET YOU NEED TENSORFLOW INSTALLED ******************************************************************************** """
plt.title('Temperature (K) (300ppm)') fig = plt.gcf() plt.show() # fig.savefig('saving_directory/fig1.eps') # Plot temperature with contours # This is a fancier way, for a paper for example. plt.figure(2) # determine lower bound, upper bound and number of contours temp_min = 200 temp_max = 300 temp_num = 11 lat, sig = np.meshgrid(lat_, sig_) levels = np.linspace(temp_min, temp_max, temp_num) col = cm.RdBu(np.linspace(1, 0, len(levels))) cs = plt.contourf(lat, sig, temp, levels, colors=col, extend="both") plt.axis([lat.min(), lat.max(), sig.max(), sig.min()]) cb = plt.colorbar() # change contour color here plt.contour(cs, colors='k') plt.xticks(np.linspace(-90, 90, 7)) plt.yticks(np.linspace(1, 0, 6)) plt.xlabel('Latitude (deg)') plt.ylabel('Sigma level (p/ps)') plt.title('Temperature (K) (300ppm)') fig = plt.gcf() plt.show() #fig.savefig('fig2.eps')
def main(): # read in table with pre-computed metrics over each season and state table = pd.read_csv(config.STATES_DIR + '/_overview/final_table_merged.csv') table2 = pd.read_csv(config.STATES_DIR + '/_overview/final_table_ens.csv') states = list(set(table.State.values)) # limit to specific metrics table_rmse = table[table.Metric == 'RMSE'] table_corr = table[table.Metric == 'PEARSON'] table_mape = table[table.Metric == 'MAPE'] table2_rmse = table2[table2.Metric == 'RMSE'] table2_corr = table2[table2.Metric == 'PEARSON'] table2_mape = table2[table2.Metric == 'MAPE'] #################################################### ############ Figure 3 ############ #################################################### # get list of differences between RMSEs rmse_diffs = [float(table_rmse[(table_rmse.Model == 'ARGO') & (table_rmse.State == st)]['ARGONet Period'].values[0]) \ / float(table_rmse[(table_rmse.Model == 'Net') & (table_rmse.State == st)]['ARGONet Period'].values[0]) for st in states] # reorder states with respect to the ordered diffs states_rmse_order = [states[i] for i in argsort(rmse_diffs)[::-1]] # states_corr_order = [states[i] for i in argsort(corr_diffs)] # states_mape_order = [states[i] for i in argsort(mape_diffs)[::-1]] ### GENERATE ARRAYS FOR BAR PLOTS ### # ARRAYS FOR RMSE (PANEL 1) argo_rmse = [] for st in states_rmse_order: tmp = table[(table.Metric == 'RMSE') & (table.Model == 'ARGO') & (table.State == st)]['ARGONet Period'].values[0] argo_rmse.append(tmp) net_rmse = [] for st in states_rmse_order: tmp = table[(table.Metric == 'RMSE') & (table.Model == 'Net') & (table.State == st)]['ARGONet Period'].values[0] net_rmse.append(tmp) ar_rmse = [] for st in states_rmse_order: tmp = table[(table.Metric == 'RMSE') & (table.Model == 'AR52') & (table.State == st)]['ARGONet Period'].values[0] ar_rmse.append(tmp) # END BLOCK # get list of differences between RMSEs rmse_diffs2 = [table2_rmse[(table2_rmse.Model == 'ARGO') & (table2_rmse.State == st)]['ARGONet Period'].values[0] \ / table2_rmse[(table2_rmse.Model == 'ARGONet') & (table2_rmse.State == st)]['ARGONet Period'].values[0] for st in states] # reorder states with respect to the ordered diffs states_rmse_order2 = [states[i] for i in argsort(rmse_diffs2)[::-1]] ### GENERATE ARRAYS FOR BAR PLOTS ### # ARRAYS FOR RMSE (PANEL 1) argo_rmse2 = [] for st in states_rmse_order2: tmp = table2[(table2.Metric == 'RMSE') & (table2.Model == 'ARGO') & (table2.State == st)]['ARGONet Period'].values[0] argo_rmse2.append(tmp) argonet_rmse2 = [] for st in states_rmse_order2: tmp = table2[(table2.Metric == 'RMSE') & (table2.Model == 'ARGONet') & (table2.State == st)]['ARGONet Period'].values[0] argonet_rmse2.append(tmp) ar_rmse2 = [] for st in states_rmse_order2: tmp = table2[(table2.Metric == 'RMSE') & (table2.Model == 'AR52') & (table2.State == st)]['ARGONet Period'].values[0] ar_rmse2.append(tmp) # END BLOCK from math import sqrt def filt(x, y): mat = np.array(zip(x, y)) mat = mat[~np.any(mat == 0, axis=1) & ~np.any(mat == -.001, axis=1)] return mat[:, 0], mat[:, 1] # scoring metric functions def RMSE(predictions, targets): predictions, targets = filt(predictions, targets) return sqrt(((predictions - targets)**2).mean()) # error_bars = np.zeros((2, len(states_rmse_order))) # for state_num, state in enumerate(states_rmse_order): # preds = pd.read_csv(config.STATES_DIR + '/{0}/top_ens_preds.csv'.format(state)) # # target = preds['ILI'].values # argo = preds['ARGO(gt,ath)'].values # argonet = preds['ARGONet'].values # # # methods = np.column_stack((target, argo, argonet)) # # # # geometric probability = 1 / mean length # p = 1./52 # # samples = 1000 # n_models = methods.shape[1] - 1 # # # calculate observed relative efficiency # eff_obs = np.zeros(n_models) # for i in range(n_models): # eff_obs[i] = RMSE(methods[:, 0], methods[:, i + 1]) # eff_obs = eff_obs / eff_obs[-1] # # # perform bootstrap # scores = np.zeros((samples, n_models)) # for iteration in range(samples): # # construct bootstrap resample # new, n1, n2 = sbb.resample(methods, p) # # # calculate sample relative efficiencies # for model in range(n_models): # scores[iteration, model] = RMSE(new[:, 0], new[:, model + 1]) # scores[iteration] = scores[iteration] / scores[iteration, -1] # # # define the variable containing the deviations from the observed rel eff # scores_residual = scores - eff_obs # # # construct output array # report_array = np.zeros((3,n_models)) # for comp in range(n_models): # tmp = scores_residual[:, comp] # # # 90% confidence interval by sorting the deviations and choosing the endpoints of the 95% region # tmp = np.sort(tmp) # report_array[0, comp] = eff_obs[comp] # report_array[1, comp] = eff_obs[comp] + tmp[int(round(samples * 0.05))] # report_array[2, comp] = eff_obs[comp] + tmp[int(round(samples * 0.95))] # # print report_array.T # # error_bars[0, state_num] = report_array[0, 0] - report_array[1, 0] # error_bars[1, state_num] = report_array[2, 0] - report_array[0, 0] ind = np.arange(len(states)) from matplotlib import cm c_range = np.linspace(.2, .8, len(ind)) # c_range[np.abs(c_range - 0.5) < 0.05] -= 0.05 * np.sign(c_range[np.abs(c_range - 0.5) < 0.05]) cmap = cm.RdBu_r(c_range) improvement = np.array( [float(argo_rmse[i]) / float(net_rmse[i]) for i in ind]) improvement2 = np.array([argo_rmse2[i] / argonet_rmse2[i] for i in ind]) colors = cm.RdBu(4 * (improvement - 1) / max(improvement) + 0.5) colors2 = cm.RdBu(4 * (improvement2 - 1) / max(improvement2) + 0.5) # print colors f, (ax1, ax2) = plt.subplots(2, 1) p = ax1.scatter(ind, improvement - 1, s=50, color=colors, edgecolor='k', linewidth=0.5) ax1.set_ylabel('Improvement of Net', labelpad=14, fontsize=12) ax1.set_ylim([-0.38, 0.38]) ax1.set_xlim([-1.5, 37]) ax1.set_xticks(ind) ax1.set_xticklabels(states_rmse_order) p = ax2.scatter(ind, improvement2 - 1, s=50, color=colors2, edgecolor='k', linewidth=0.5, alpha=1) ax2.set_ylabel('Improvement of ARGONet', labelpad=14, fontsize=12) ax2.set_ylim([-0.38, 0.38]) ax2.set_xlim([-1.5, 37]) ax2.set_xticks(ind) ax2.set_xticklabels(states_rmse_order2) ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['left'].set_bounds(-.3, .3) ax1.spines['bottom'].set_bounds(-.5, 36.5) ax1.spines['bottom'].set_linewidth(1) ax1.spines['left'].set_linewidth(1.5) ax1.tick_params(axis='y', length=4, width=1, rotation=0, labelsize=12) ax1.tick_params(axis='x', length=0, width=1, rotation=90, labelsize=9) ax1.set_yticks([-.3, 0, .3]) ax1.set_yticklabels(['0.7', '1', '1.3']) # ax1.locator_params(axis='y', tight=True, nbins=4) ax1.axhline(y=0, color='k', linestyle='--', alpha=0.25) ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.spines['left'].set_bounds(-.3, .3) ax2.spines['bottom'].set_bounds(-.5, 36.5) ax2.tick_params(axis='y', length=4, width=1, rotation=0, labelsize=12) ax2.tick_params(axis='x', length=0, width=1, rotation=90, labelsize=9) ax2.set_yticks([-.3, 0, .3]) ax2.set_yticklabels(['0.7', '1', '1.3']) # ax2.locator_params(axis='y', tight=True, nbins=4) ax2.spines['bottom'].set_linewidth(1) ax2.spines['left'].set_linewidth(1.5) ax2.axhline(y=0, color='k', linestyle='--', alpha=0.25) # ax1.set_title("Net") # ax2.set_title("ARGONet") fig = plt.gcf() fig.set_size_inches(8, 6) fig.savefig(config.STATES_DIR + '/_overview/improvements.png', format='png', dpi=300) plt.show()
np.random.seed(12345) df = pd.DataFrame([np.random.normal(32000,200000,3650), np.random.normal(43000,100000,3650), np.random.normal(43500,140000,3650), np.random.normal(48000,70000,3650)], index=[1992,1993,1994,1995]) value = df.mean(axis=1) std = df.std(axis=1) interval_length = pd.Series() bar_colour = pd.Series() i = 0 for index, row in df.iterrows(): Confidence_interval = st.t.interval(0.95, len(row)-1, loc=np.mean(row), scale=st.sem(row)) interval_length = interval_length.set_value(i,(max(Confidence_interval) - min(Confidence_interval))/2) prob = st.norm.cdf((value.iloc[i] - value.mean())/(st.sem(row))) bar_colour = bar_colour.set_value(i,cm.RdBu(prob)) i=i+1 plt.bar(range(len(df.index)),value,yerr=interval_length,color=bar_colour,alpha=0.5,capsize=10) plt.xticks(range(len(df.index)), df.index) plt.xlabel('Year') plt.ylabel('Stock price') plt.title('Stock price between 1992 and 1994') plt.show()
y = np.zeros(N) z = np.zeros(N) rho, beta, sigma = (28, 8 / 3, 14) x[0], y[0], z[0] = (.2, 2, 0) dt = .01 # time step between every index (frame) # setting up figure plt.style.use('dark_background') fig = plt.figure(figsize = (8, 8)) ax = fig.add_subplot(111, projection = '3d') color_period_freq = 1000 # color goes from dark to light to dark in blank inexes cmhold = abs(np.sin(np.linspace(0, N / color_period_freq, N)))# color map colormap = cm.RdBu(cmhold) for i in range(N - 1): x[i+1] = x[i] + sigma * (y[i] - x[i]) * dt y[i+1] = y[i] + (x[i] * (rho - z[i]) - y[i]) * dt z[i+1] = z[i] + (x[i] * y[i] - beta * z[i]) * dt ax.scatter(x, y, z, c = colormap, s = .2) ax.grid(False) ax.axis('off') plt.show()
fh = logging.handlers.RotatingFileHandler('log.log', maxBytes=1000000, backupCount=3) # file handler fh.setLevel(logging.DEBUG) ch = logging.StreamHandler() # console handler ch.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) fh.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) logger.info('Initializing %s', __name__) colors = [ cm.RdBu(0.85), cm.RdBu(0.7), cm.PiYG(0.7), cm.Spectral(0.38), cm.Spectral(0.25) ] if __name__ == '__main__': # parameter setting gps_dir = s.GPS_DIR gps_counter_file = s.GPS_COUNTER_FILE TWEET_COUNTER_FILE = s.TWEET_COUNTER_FILE timestart = s.TIMESTART timestart_text = s.TIMESTART_TEXT timeend = s.TIMEEND timeend_text = s.TIMEEND_TEXT
def hinton(rho, xlabels=None, ylabels=None, title=None, ax=None): """Draws a Hinton diagram for visualizing a density matrix. Parameters ---------- rho : qobj Input density matrix. xlabels : list of strings list of x labels ylabels : list of strings list of y labels title : string title of the plot (optional) ax : a matplotlib axes instance The axes context in which the plot will be drawn. Returns ------- An matplotlib axes instance for the plot. Raises ------ ValueError Input argument is not a quantum object. """ if isinstance(rho, Qobj): if isket(rho) or isbra(rho): raise ValueError("argument must be a quantum operator") W = rho.full() else: W = rho if ax is None: fig, ax = plt.subplots(1, 1, figsize=(8, 6)) if not (xlabels or ylabels): ax.axis('off') ax.axis('equal') ax.set_frame_on(False) height, width = W.shape w_max = 1.25 * max(abs(diag(matrix(W)))) if w_max <= 0.0: w_max = 1.0 # x axis ax.xaxis.set_major_locator(IndexLocator(1, 0.5)) if xlabels: ax.set_xticklabels(xlabels) ax.tick_params(axis='x', labelsize=14) # y axis ax.yaxis.set_major_locator(IndexLocator(1, 0.5)) if ylabels: ax.set_yticklabels(list(reversed(ylabels))) ax.tick_params(axis='y', labelsize=14) ax.fill(array([0, width, width, 0]), array([0, 0, height, height]), color=cm.RdBu(128)) for x in range(width): for y in range(height): _x = x + 1 _y = y + 1 if real(W[x, y]) > 0.0: _blob(_x - 0.5, height - _y + 0.5, abs(W[x, y]), w_max, min(1, abs(W[x, y]) / w_max)) else: _blob(_x - 0.5, height - _y + 0.5, -abs(W[ x, y]), w_max, min(1, abs(W[x, y]) / w_max)) # color axis norm = mpl.colors.Normalize(-abs(W).max(), abs(W).max()) cax, kw = mpl.colorbar.make_axes(ax, shrink=0.75, pad=.1) cb = mpl.colorbar.ColorbarBase(cax, norm=norm, cmap=cm.RdBu) return ax