def inset_momentum_axes(cd): # TODO: This plot does not refresh correctly, skip the inset fig = mpl.figure(cd.plotfigure.figno) axes = fig.add_subplot(111) # Plot main figure axes.plot(cd.x, hu_1(cd), 'b-') axes.plot(cd.x, hu_2(cd), 'k--') axes.set_xlim(xlimits) axes.set_ylim(ylimits_momentum) momentum_axes(cd) # Create inset plot from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_inset inset_axes = zoomed_inset_axes(axes, 0.5, loc=3) inset_axes.plot(cd.x, hu_1(cd), 'b-') inset_axes.plot(cd.x, hu_2(cd), 'k--') inset_axes.set_xticklabels([]) inset_axes.set_yticklabels([]) x_zoom = [-120e3,-30e3] y_zoom = [-10,10] inset_axes.set_xlim(x_zoom) inset_axes.set_ylim(y_zoom) mark_inset(axes, inset_axes, loc1=2, loc2=4, fc='none', ec="0.5") # mpl.ion() mpl.draw()
def chickling_pd_zoom(shotno, date=time.strftime("%Y%m%d")): fname, data = file_finder(shotno,date) data_1550 = data[0]['phasediff_co2'][100:] plot_time = np.linspace(0,1,data_1550.size) fig, ax = plt.subplots() ax.plot(plot_time, data_1550) ax.set_ybound(max(data_1550)+0.6, min(data_1550)-0.01) plt.title("Phase Difference for shot " + str(shotno) + " Date " + str(date)) plt.xlabel("Time, s") plt.ylabel("Phase Difference, Radians") x_zoom_bot = int(data_1550.size*(10/100)) x_zoom_top = int(data_1550.size*(15/100)) x1, x2, y1, y2 = 0.1, 0.15, max(data_1550[x_zoom_bot:x_zoom_top])+0.01, min(data_1550[x_zoom_bot:x_zoom_top])-0.01 axins = inset_axes(ax, 4.3,1, loc=9) axins.plot(plot_time[x_zoom_bot:x_zoom_top], data_1550[x_zoom_bot:x_zoom_top]) axins.set_xlim(x1, x2) if y1 < y2: axins.set_ylim(y1, y2) else: axins.set_ylim(y2, y1) mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5",lw=2) plt.show()
def show_insets(image, insets_coords, size=(6, 3)): fig = pyplot.figure(figsize=size) line_colors = colors.LinearSegmentedColormap.from_list("line_colors", ["red", "blue"], len(insets_coords)) gs = gridspec.GridSpec(len(insets_coords), 2) main_ax = fig.add_subplot(gs[:, 0]) main_extent = (0, image.shape[1], image.shape[0], 0) main_ax_img = main_ax.imshow(image, interpolation="nearest", extent=main_extent, origin="upper") main_ax_img.set_cmap("binary_r") pyplot.setp(main_ax.get_yticklabels(), visible=False) pyplot.setp(main_ax.get_xticklabels(), visible=False) for inset_index, inset_coords in enumerate(insets_coords): inset_ax = fig.add_subplot(gs[inset_index, 1]) inset_ax_img = inset_ax.imshow(image, interpolation="nearest", extent=main_extent, origin="upper") inset_ax_img.set_cmap("binary_r") inset_ax.set_ylim(inset_coords[0].stop, inset_coords[0].start) inset_ax.set_xlim(inset_coords[1].start, inset_coords[1].stop) pyplot.setp(inset_ax.get_yticklabels(), visible=False) pyplot.setp(inset_ax.get_xticklabels(), visible=False) mark_inset(main_ax, inset_ax, loc1=1, loc2=3, fc="none", ec=line_colors(inset_index)) gs.tight_layout(fig) return fig
def render_input_spectrum(): folder = "/cosma/home/durham/rhgk18/ls_structure/pks" bao = folder+"/wig.txt" nbao = folder+"/nowig.txt" pkbao = np.loadtxt(bao) pknbao = np.loadtxt(nbao) fig, ax = plt.subplots() ax.loglog(pkbao[:,0] ,pkbao[:,1] , color='r', label='With BAO') ax.loglog(pknbao[:,0] ,pknbao[:,1] , color='b', label='Without BAO') ax.set_xlabel("Wavenumber, $k$ [$h/Mpc$]", size=28) ax.set_ylabel("Power, $P(k)$ [$(Mpc/h)^3$]", size=28) ax.legend(prop={'size':28}) axins = zoomed_inset_axes(ax, 5, loc=3) axins.loglog(pkbao[:,0] ,pkbao[:,1] , color='r', label='iWith BAO') axins.loglog(pknbao[:,0] ,pknbao[:,1] , color='b', label='iWithout BAO') x1, x2, y1, y2 = 0.02, 0.1, 5000, 30000 axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) plt.xticks(visible=False) plt.yticks(visible=False) mark_inset(ax, axins, loc1=2, loc2=1, fc="none", ec="0.5") plt.show()
def QQplot(obs, Q, pos, color=None, ax=None, axins=True): if not color: color='blue' if ax is None: ax = plt.gca() mean = np.mean(obs, axis=0) # obs = np.random.multivariate_normal(mean, S, 3000) md2 = np.diag(np.dot(np.dot(obs - mean, Q), (obs -mean).T)) sorted_md2 = np.sort(md2) v = (np.arange(1, obs.shape[0] + 1) - 0.375) / (obs.shape[0] + 0.25) quantiles = scipy.stats.chi2.ppf(v, df=obs.shape[1]) # axins = inset_axes(ax, width="60%", height=1., loc=2) if axins: axins = inset_axes(ax, width="60%", height=1., loc=2) axins.axis(pos) axins.get_xaxis().tick_bottom() axins.get_yaxis().tick_left() # Remove the tick marks; they are unnecessary with the tick lines we just plotted. axins.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="off", left="off", right="off", labelleft="off") mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") axins.xaxis.set_major_locator(MaxNLocator(nbins=1, prune='lower')) axins.scatter(quantiles, sorted_md2, color=colorscheme[color], alpha=0.3) axins.plot(quantiles, quantiles, color=colorscheme['green'], lw=2.5) ax.scatter(quantiles, sorted_md2, color=colorscheme[color], alpha=0.3) ax.plot(quantiles, quantiles, color=colorscheme['green'], lw=2.5) _clean_axes(ax)
def plot_linear_kernel_pairs(pairs): xdata, ydata = zip(*pairs) maxval = max(max(xdata), max(ydata)) fig, ax = plt.subplots() ax.plot(xdata, ydata, '.') ax.plot([0, maxval], [0, maxval], '--') plt.xlabel("Linear Ridge Mean Absolute Error (kcal/mol)") plt.ylabel("Kernel Ridge Mean Absolute Error (kcal/mol)") # 15 is the zoom, loc is nuts axins = zoomed_inset_axes(ax, 15, loc=5) axins.plot(xdata, ydata, '.') axins.plot([0, maxval], [0, maxval], '--') # sub region of the original image axins.set_xlim(1, 6) axins.set_ylim(1, 6) # draw a bbox of the region of the inset axes in the parent axes and # connecting lines between the bbox and the inset axes area mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") plt.draw() plt.show()
def plot_target_pred(train_xdata, test_xdata, train_ydata, test_ydata, loc=5): maxval = max(train_xdata.max(), test_xdata.max(), train_ydata.max(), test_ydata.max()) minval = min(train_xdata.min(), test_xdata.min(), train_ydata.min(), test_ydata.min()) fig, ax = plt.subplots() ax.plot(train_xdata, train_ydata, '.', label="Train") ax.plot(test_xdata, test_ydata, '.', label="Test") plt.legend(loc="best") ax.plot([minval, maxval], [minval, maxval], '--') plt.xlabel("Target Value (kcal/mol)") plt.ylabel("Predicted Value (kcal/mol)") axins = zoomed_inset_axes(ax, 30, loc=loc) # 30 is zoom, loc is .... nuts axins.plot(train_xdata, train_ydata, '.', label="Train") axins.plot(test_xdata, test_ydata, '.', label="Test") axins.plot([minval, maxval], [minval, maxval], '--') # sub region of the original image middle = test_xdata.mean() - 170 x1, x2, y1, y2 = -15+middle, 15+middle, -15+middle, 15+middle axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) mark_inset(ax, axins, loc1=2, loc2=3, fc="none", ec="0.5") plt.draw() plt.show()
def plot_us(lats, lons, save_name=None): fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) big_map = Basemap(resolution='h', lat_0=36, lon_0=-107.5, llcrnrlat=32, llcrnrlon=-125, urcrnrlat=43, urcrnrlon=-110) big_map.drawcoastlines() big_map.drawstates() big_map.drawcountries() big_map.drawmapboundary(fill_color='#7777ff') big_map.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0) x, y = big_map(lons, lats) big_map.plot(x[0], y[0], 'ro', markersize=2) axins = zoomed_inset_axes(ax, 20, loc=1) ll_lat, ll_lon = 37.8, -122.78 ur_lat, ur_lon = 38.08, -122.43 axins.set_xlim(ll_lon, ur_lon) axins.set_ylim(ur_lon, ur_lat) small_map = Basemap(resolution='h', llcrnrlat=ll_lat, llcrnrlon=ll_lon, urcrnrlat=ur_lat, urcrnrlon=ur_lon, ax=axins) small_map.drawcoastlines() small_map.drawmapboundary(fill_color='#7777ff') small_map.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0) x, y = small_map(lons, lats) small_map.plot(x, y, 'ro', markersize=3) mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") if save_name: fig.savefig(save_name)
def plotBinned(cls_in,dcls_in,l_out,bins,output_prefix,title=None,theory=None,dtheory=None,delta=None,cosmic=None): fig=plt.figure(1) plt.clf() ax=fig.add_subplot(111) good_l=np.logical_and( l_out > 25 , l_out <= 250) if not (theory is None) : ax.plot(l_out,theory,'r-') if not (cosmic is None) : ax.fill_between(l_out,(theory-cosmic),(theory+cosmic),alpha=.5,facecolor='red') #plt.fill_between(l_out,(theory-dtheory),(theory+dtheory),alpha=.5,facecolor='red') if not (dtheory is None) : ax.errorbar(l_out,theory,yerr=dtheory,color='red') ax.errorbar(l_out,cls_in,yerr=dcls_in,color='black',fmt='k.',linestyle='None') if not (delta is None) : ax.fill_between(l_out,cls_in-delta,cls_in+delta,color='gray',alpha=0.5) #plt.xlim([0,np.max(l_out+bins)]) #plt.ylim([np.min(b_cl['llcl']-b_dcl['llcl']),np.max(b_cl['llcl']+b_dcl['llcl'])]) ax.set_xlabel('$\ell$') ax.set_ylabel('$\\frac{\ell(\ell+1)}{2\pi}C_{\ell}\ \\frac{\mu K^{2}}{m^{4}}$') #ax.set_xlim([0,np.max(l_out+bins)]) # ax.autoscale(axis='y',tight=True) if title: ax.set_title(title) else: ax.set_title('Binned Cls {:02d}'.format(bins)) axins = inset_axes(ax,width="50%",height="30%",loc=9) if not (theory is None) : axins.plot(l_out[good_l],theory[good_l],'r-') if not (cosmic is None) : axins.fill_between(l_out[good_l],(theory-cosmic)[good_l],(theory+cosmic)[good_l],alpha=.5,facecolor='red') #plt.fill_between(l_out,(theory-dtheory),(theory+dtheory),alpha=.5,facecolor='red') if not (dtheory is None) : axins.errorbar(l_out[good_l],theory[good_l],yerr=dtheory[good_l],color='red') axins.errorbar(l_out[good_l],cls_in[good_l],yerr=dcls_in[good_l],color='black',fmt='k.',linestyle='None') if not (delta is None) : axins.fill_between(l_out[good_l],(cls_in-delta)[good_l],(cls_in+delta)[good_l],color='gray',alpha=0.5) axins.set_xlim(25,255) axins.set_yscale('log') #axins.set_ylim(ymax=1e5) #axins.set_ylim(-1e5,1e5) mark_inset(ax,axins,loc1=2,loc2=4,fc='none',ec='0.1') #axins.set_xlim([25,250]) axins.autoscale('y',tight=True) plt.draw() #plt.show(block=True) fig.savefig(output_prefix+'_linear_{:02d}.eps'.format(bins),format='eps') fig.savefig(output_prefix+'_linear_{:02d}.png'.format(bins),format='png') ax.set_yscale('log') fig.savefig(output_prefix+'_log_{:02d}.eps'.format(bins),format='eps') fig.savefig(output_prefix+'_log_{:02d}.png'.format(bins),format='png')
def plot_default_topo(bmap,x, y, data): assert isinstance(bmap, Basemap) fig = plt.figure(figsize=(10, 6)) gs = GridSpec(1, 2, width_ratios=[4, 1], height_ratios=[3, 1]) ax = fig.add_subplot(gs[0, 1]) bmap.etopo() img = bmap.contourf(x, y, data, norm=LogNorm(), alpha=0.8, ax=ax) cb = bmap.colorbar(img) cb.ax.set_title(r"${\rm km^2}$") bmap.drawcoastlines(linewidth=0.3) bmap.drawmeridians(np.arange(-180, 180, 20)) bmap.drawparallels(np.arange(-90, 110, 20)) bmap.readshapefile("data/shp/wri_basins2/wribasin", "basin", color="k", linewidth=2, ax=ax) lower_left_lat_lon = (-50, 45) axins = fig.add_subplot(gs[0, 0]) # plt.axes([-0.15, 0.1, 0.6, 0.8]) # zoomed_inset_axes(ax, 2, loc=1) # zoom = 6 #bmap.etopo(ax=axins) bm_zoom = plot_changes_in_seasonal_means.get_arctic_basemap_nps(round=False, resolution="l") lower_left_xy = bmap(*lower_left_lat_lon) upper_right_xy = bmap(-160, 55) bm_zoom.etopo(ax=axins) #axins.set_xlim(lower_left_xy[0], lower_left_xy[0] + 400000) #axins.set_ylim(lower_left_xy[1], lower_left_xy[1] + 5000000) print(lower_left_xy) print(upper_right_xy) #bm_zoom.etopo(ax=axins) assert isinstance(axins, Axes) img = bm_zoom.contourf(x, y, data, norm=LogNorm(), alpha=0.8, ax=axins) bm_zoom.drawcoastlines(linewidth=0.3) bm_zoom.readshapefile("data/shp/wri_basins2/wribasin", "basin", color="k", linewidth=2, ax=axins) axins.set_xlim(lower_left_xy[0], upper_right_xy[0]) axins.set_ylim(lower_left_xy[1], upper_right_xy[1]) # draw a bbox of the region of the inset axes in the parent axes and # connecting lines between the bbox and the inset axes area mark_inset(ax, axins, loc1=1, loc2=4, fc="none", ec="0.5") fig.tight_layout() fig.savefig("simple2.png", bbox_inches="tight") plt.show()
def test_gettightbbox(): fig, ax = plt.subplots(figsize=(8, 6)) l, = ax.plot([1, 2, 3], [0, 1, 0]) ax_zoom = zoomed_inset_axes(ax, 4) ax_zoom.plot([1, 2, 3], [0, 1, 0]) mark_inset(ax, ax_zoom, loc1=1, loc2=3, fc="none", ec='0.3') remove_ticks_and_titles(fig) bbox = fig.get_tightbbox(fig.canvas.get_renderer()) np.testing.assert_array_almost_equal(bbox.extents, [-17.7, -13.9, 7.2, 5.4])
def makeplot(refl, winds, w, stride, map, gs, title, file_name, box=None): pylab.figure() axmain = pylab.axes((0, 0.025, 1, 0.9)) gs_x, gs_y = gs nx, ny = refl.shape xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny)) pylab.contourf(xs, ys, refl, levels=np.arange(10, 80, 10)) pylab.colorbar() pylab.contour(xs, ys, w, levels=np.arange(-10, 0, 2), colors='#666666', style='--') pylab.contour(xs, ys, w, levels=np.arange(2, 12, 2), colors='#666666', style='-') u, v = winds wind_slice = tuple([ slice(None, None, stride) ] * 2) pylab.quiver(xs[wind_slice], ys[wind_slice], u[wind_slice], v[wind_slice]) if box: lb_y, lb_x = [ b.start for b in box ] ub_y, ub_x = [ b.stop for b in box ] box_xs = gs_x * np.array([ lb_x, lb_x, ub_x, ub_x, lb_x]) box_ys = gs_y * np.array([ lb_y, ub_y, ub_y, lb_y, lb_y]) map.plot(box_xs, box_ys, '#660099') axins = zoomed_inset_axes(pylab.gca(), 4, loc=4) pylab.sca(axins) pylab.contourf(xs[box], ys[box], refl[box], levels=np.arange(10, 80, 10)) pylab.contour(xs[box], ys[box], w[box], levels=np.arange(-10, 0, 2), colors='#666666', style='--') pylab.contour(xs[box], ys[box], w[box], levels=np.arange(2, 12, 2), colors='#666666', style='-') pylab.quiver(xs[box], ys[box], u[box], v[box]) drawPolitical(map) pylab.xlim([lb_x * gs_x, ub_x * gs_x - 1]) pylab.ylim([lb_y * gs_y, ub_y * gs_y - 1]) mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k') pylab.sca(axmain) drawPolitical(map) pylab.suptitle(title) pylab.savefig(file_name) pylab.close() return
def test_inset_axes(): def get_demo_image(): from matplotlib.cbook import get_sample_data import numpy as np f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 return z, (-3, 4, -4, 3) fig, ax = plt.subplots(figsize=[5, 4]) # prepare the demo image Z, extent = get_demo_image() Z2 = np.zeros([150, 150], dtype="d") ny, nx = Z.shape Z2[30:30 + ny, 30:30 + nx] = Z # extent = [-3, 4, -4, 3] ax.imshow(Z2, extent=extent, interpolation="nearest", origin="lower") # creating our inset axes with a bbox_transform parameter axins = inset_axes(ax, width=1., height=1., bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes) axins.imshow(Z2, extent=extent, interpolation="nearest", origin="lower") axins.yaxis.get_major_locator().set_params(nbins=7) axins.xaxis.get_major_locator().set_params(nbins=7) # sub region of the original image x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9 axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) plt.xticks(visible=False) plt.yticks(visible=False) # draw a bbox of the region of the inset axes in the parent axes and # connecting lines between the bbox and the inset axes area mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") asb = AnchoredSizeBar(ax.transData, 0.5, '0.5', loc='lower center', pad=0.1, borderpad=0.5, sep=5, frameon=False) ax.add_artist(asb)
def plotConfusion(confusion, grid, title, file_name, inset=None, fudge=16): pylab.figure() axmain = pylab.axes() tick_labels = [ "Missing", "Correct\nNegative", "False\nAlarm", "Miss", "Hit" ] min_label = -1 xs, ys = grid.getXY() pylab.pcolormesh(xs, ys, confusion, cmap=confusion_cmap, vmin=min_label, vmax=(min_label + len(tick_labels) - 1)) tick_locs = np.linspace(-1, min_label + len(tick_labels) - 2, len(tick_labels)) tick_locs += (tick_locs[1] - tick_locs[0]) / 2 bar = pylab.colorbar() bar.locator = FixedLocator(tick_locs) bar.formatter = FixedFormatter(tick_labels) pylab.setp(pylab.getp(bar.ax, 'ymajorticklabels'), fontsize='large') bar.update_ticks() grid.drawPolitical() if inset: lb_y, lb_x = [ b.start for b in inset ] ub_y, ub_x = [ b.stop + fudge for b in inset ] inset_exp = (slice(lb_y, ub_y), slice(lb_x, ub_x)) axins = zoomed_inset_axes(pylab.gca(), 2, loc=4) pylab.sca(axins) pylab.pcolormesh(xs[inset_exp], ys[inset_exp], confusion[inset_exp], cmap=confusion_cmap, vmin=min_label, vmax=(min_label + len(tick_labels) - 1)) grid.drawPolitical() gs_x, gs_y = grid.getGridSpacing() pylab.xlim([lb_x * gs_x, (ub_x - 1) * gs_x]) pylab.ylim([lb_y * gs_y, (ub_y - 1) * gs_y]) mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k') pylab.sca(axmain) pylab.suptitle(title) pylab.savefig(file_name) pylab.close() return
def draw_inset(plt, m, pos, lat, lon): ax = plt.subplot(111) zoom = 50 axins = zoomed_inset_axes(ax, zoom, loc=1) m.plot(lon, lat, '.b--', zorder=10, latlon=True) m.scatter(lon, lat, # longitude first! latlon=True, # lat and long in degrees zorder=11) # on top of all x1, y1 = m(lon[1] - 0.005, lat[0] - 0.0025) x2, y2 = m(lon[1] + 0.005, lat[0] + 0.0025) axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) plt.xticks(visible=False) plt.yticks(visible=False) # draw a bbox of the region of the inset axes in the parent axes and # connecting lines between the bbox and the inset axes area mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
def plot_calibration(c, insert = True): fig = plt.figure() ax = plt.gca() for baseline, correlation in c.time_domain_correlations_values.items(): correlation_max_val = correlation[np.argmax(correlation)] correlation_max_time = c.time_domain_correlations_times[baseline][np.argmax(correlation)] lines = ax.plot( c.time_domain_correlations_times[baseline] * 1e9, correlation / correlation_max_val, label = baseline) #ax.plot([correlation_max_time, correlation_max_time], [0, correlation_max_val], color = lines[0].get_color()) ax.set_ylim(top=1.2) ax.xaxis.set_ticks(np.arange( -200, 200, 2)) if insert == True: #axins = zoomed_inset_axes(ax, 5, loc=1) axins = zoomed_inset_axes(ax, 9, loc=1) for baseline, correlation in c.time_domain_correlations_values.items(): correlation_max_val = correlation[np.argmax(correlation)] correlation_max_time = c.time_domain_correlations_times[baseline][np.argmax(correlation)] lines = axins.plot( c.time_domain_correlations_times[baseline] * 1e9, correlation / correlation_max_val, label = baseline, linewidth=2) #axins.plot([correlation_max_time, correlation_max_time], [0, correlation_max_val], color = lines[0].get_color()) #axins.set_xlim(-0.4, 2.9) axins.set_xlim(-0.4, 0.4) #axins.set_ylim(0.90, 1.04) axins.set_ylim(0.96, 1.03) #axins.xaxis.set_ticks(np.arange(-0.4, 2.9, 0.4)) axins.xaxis.set_ticks(np.arange(-0.4, 0.4, 0.2)) mark_inset(ax, axins, loc1=2, loc2=3, fc='none', ec='0.5') plt.xticks(visible=True) plt.yticks(visible=False) ax.set_title("Time domain cross correlations with broad band noise\n arriving through full RF chain AFTER calibration") ax.set_xlabel("Time delay (ns)") ax.set_ylabel("Cross correlation value (normalised)") ax.legend(loc=2) #ax.legend() plt.show()
def plot_site(options): options['prefix'] = 'site' fig = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Probability $p_s$', ylabel=r'Reachability~$\reachability$', aspect='auto') fig_vs = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Fraction of Forwarded Packets~$\forwarded$', ylabel=r'Reachability~$\reachability$', aspect='auto') if options['grayscale']: colors = options['graycm'](pylab.linspace(0, 1.0, 3)) else: colors = fu_colormap()(pylab.linspace(0, 1.0, 3)) nodes = 105 axins = None if options['inset_loc'] >= 0: axins = zoomed_inset_axes(fig_vs.ax, options['inset_zoom'], loc=options['inset_loc']) axins.set_xlim(options['inset_xlim']) axins.set_ylim(options['inset_ylim']) axins.set_xticklabels([]) axins.set_yticklabels([]) mark_inset(fig_vs.ax, axins, loc1=2, loc2=3, fc="none", ec="0.5") for i, (name, label) in enumerate(names): data = parse_site_only(options['datapath'][0], name) rs = numpy.array([r for p, r, std, conf, n, fw, fw_std, fw_conf in data if r <= options['limit']]) fws = numpy.array([fw for p, r, std, conf, n, fw, fw_std, fw_conf in data if r <= options['limit']])/(nodes-1) ps = numpy.array([p for p, r, std, conf, n, fw, fw_std, fw_conf in data]) #[0:len(rs)]) yerr = numpy.array([conf for p,r,std,conf, n, fw, fw_std, fw_conf in data]) #[0:len(rs)]) patch_collection = PatchCollection([conf2poly(ps, list(rs+yerr), list(rs-yerr), color=colors[i])], match_original=True) patch_collection.set_alpha(0.3) patch_collection.set_linestyle('dashed') fig.ax.add_collection(patch_collection) fig.ax.plot(ps, rs, label=label, color=colors[i]) fig_vs.ax.plot(fws, rs, label=label, color=colors[i]) if axins: axins.plot(fws, rs, color=colors[i]) fig.ax.set_ylim(0, options['limit']) fig.legend_title = 'Graph' fig.save('graphs') fig_vs.legend_title = 'Graph' fig_vs.ax.set_xlim(0,1) fig_vs.ax.set_ylim(0,1) fig_vs.save('vs_pb')
def plot_figure(self, ax, xaxis, yaxis, title='', legend='', drawline=True, legend_outside=False, marker=None, linestyle=None, xlabel='', ylabel='', xlog=False, ylog=False, zoom=False, zoom_ax=None, zoom_xaxis=[], zoom_yaxis=[], legend_pos='best', xlabel_format=0, xlimit=0, ylimit=0, legend_markscale=1.0): if drawline: ax.plot(xaxis, yaxis, marker=marker if marker else '+', ls=linestyle if linestyle else '-', label=legend) else: #draw dots ax.plot(xaxis, yaxis, marker=marker if marker else 'o', markerfacecolor='r', ms=4, ls='None', label=legend) #ax.vlines(xaxis, [0], yaxis) if xlog: ax.set_xscale('log') if ylog: ax.set_yscale('log') if xlimit > 0: ax.set_xlim(0, ax.get_xlim()[1] if ax.get_xlim()[1]<xlimit else xlimit) if ylimit > 0: ax.set_ylim(0, ax.get_ylim()[1] if ax.get_ylim()[1]<ylimit else ylimit) ax.set_title(title) ax.legend(loc=legend_pos, markerscale=legend_markscale) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) # zoom if zoom: new_zoom_ax = False if zoom_ax is None: new_zoom_ax = True zoom_ax = inset_axes(ax, width="70%", # width = 50% of parent_bbox height="70%", # height : 1 inch loc=7) # center right if drawline: zoom_ax.plot(zoom_xaxis, zoom_yaxis, marker=marker if marker else '+', ls=linestyle if linestyle else '-') else: #draw dots zoom_ax.plot(zoom_xaxis, zoom_yaxis, marker=marker if marker else 'o', markerfacecolor='r', ms=4, ls='None') #zoom_ax.vlines(zoom_xaxis, [0], zoom_yaxis) if new_zoom_ax: zoom_ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) mark_inset(ax, zoom_ax, loc1=2, loc2=4, fc="none", ec="0.5") return ax, zoom_ax
def graph(data_, j_size, title=None): fig, ax = plt.subplots() data = pd.read_csv(data_, index_col = 0) jitter_ = jitter(-j_size, j_size, len(list(data.iterrows())[0][1])) max_1 = 0 max_2 = 0 for i, d in enumerate(data.iterrows()): if max(list(d[1])) > max_1 and i > 2: max_1 = max(list(d[1])) elif max(list(d[1])) > max_2 and i < 3: max_2 = max(list(d[1])) plt.scatter(x = np.array([i]*len(jitter_)+jitter_), y = list(d[1])) plt.xlim(-0.1, 5.1) # apply the x-limits c1 = 1 while max_1/(c1*10) > 1: c1 *= 10 c2 = 1 while max_2/(c2*10) > 1: c2 *= 10 cb = max(c1,c2) cs = min(c1,c2) max1 = max(max_1, max_2) max2 = min(max_1, max_2) plt.ylim(-cb, (max1/cb+2)*cb) from mpl_toolkits.axes_grid1.inset_locator import inset_axes if c2 > c1: axins = inset_axes(ax, 4,3, loc=5) else: axins = inset_axes(ax, 4,3, loc=6) axins.yaxis.tick_right() for i, d in enumerate(data.iterrows()): plt.scatter(x = np.array([i]*len(jitter_)+jitter_), y = list(d[1])) if c2 > c1: axins.set_xlim(2.9, 5.1) # apply the x-limits else: axins.set_xlim(-0.1, 2.1) plt.ylim(-cs, (max2/cs+2)*cs) from mpl_toolkits.axes_grid1.inset_locator import mark_inset mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") plt.show()
def nice_plot_e_of_T(): Ts1 = np.arange(273.15-10, 273.15-5, 1.) Ts2 = np.arange(273.15-3, 273.15-1, .1) Ts3 = np.arange(273.15-1, 273.15+1, .0001) Ts4 = np.arange(273.15+1, 273.15+5, .1) Ts5 = np.arange(273.15+5, 273.15+50, 1.) Ts = np.concatenate((Ts1, Ts2, Ts3, Ts4, Ts5)) # water content at T=273.65, p=85000. wc = water_content(273.65, 85000., saturations_A) ie = [] for T in Ts: # for each T, determine the p required to maintain same mass (sl,si,sg),p = saturation_with_wc(T,wc, saturations_A) ie.append(internal_energy_per_mol(T,p, saturations_A)) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(Ts - 273.15,np.array(ie), 'b') ax.set_xlim(-10,20) ax.set_ylim(-8000,2000) plt.xlabel("temperature [C]") plt.ylabel("energy density (water) [J/mol]") axins = inset_axes(ax, 3, 3, loc=4) axins.plot(Ts - 273.15,np.array(ie), 'b') axins.set_xlim(-.01,.01) axins.set_ylim(-7000,500) axins.set_xticks([-0.01, 0, 0.01]) axins.tick_params(labeltop=1, labelbottom=0) axins.set_yticks([-6000,-4000,-2000,0]) mark_inset(ax, axins, loc1=1, loc2=3, fc="none", ec="0.5") plt.show()
def plot_network(net, inset={}, path=None, with_secnet=False): """ """ fig = plt.figure(figsize=(40, 40), dpi=72) ax = fig.add_subplot(111) # Draw nodes DrawNodes(net, ax, label='S', color='dodgerblue', size=2000) DrawNodes(net, ax, label='T', color='green', size=25) DrawNodes(net, ax, label='R', color='black', size=2.0) if with_secnet: DrawNodes(net, ax, label='H', color='crimson', size=2.0) # Draw edges DrawEdges(net, ax, label='P', color='black', width=2.0) DrawEdges(net, ax, label='E', color='dodgerblue', width=2.0) if with_secnet: DrawEdges(net, ax, label='S', color='crimson', width=1.0) ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) # Inset figures for sub in inset: axins = zoomed_inset_axes(ax, inset[sub]['zoom'], loc=inset[sub]['loc']) axins.set_aspect(1.3) # Draw nodes DrawNodes(inset[sub]['graph'], axins, label='S', color='dodgerblue', size=2000) DrawNodes(inset[sub]['graph'], axins, label='T', color='green', size=25) DrawNodes(inset[sub]['graph'], axins, label='R', color='black', size=2.0) if with_secnet: DrawNodes(inset[sub]['graph'], axins, label='H', color='crimson', size=2.0) # Draw edges DrawEdges(inset[sub]['graph'], axins, label='P', color='black', width=2.0) DrawEdges(inset[sub]['graph'], axins, label='E', color='dodgerblue', width=2.0) if with_secnet: DrawEdges(inset[sub]['graph'], axins, label='S', color='crimson', width=1.0) axins.tick_params(bottom=False, left=False, labelleft=False, labelbottom=False) mark_inset(ax, axins, loc1=inset[sub]['loc1'], loc2=inset[sub]['loc2'], fc="none", ec="0.5") # Legend for the plot leghands = [ Line2D([0], [0], color='black', markerfacecolor='black', marker='o', markersize=0, label='primary network'), Line2D([0], [0], color='dodgerblue', markerfacecolor='dodgerblue', marker='o', markersize=0, label='high voltage feeder'), Line2D([0], [0], color='white', markerfacecolor='green', marker='o', markersize=20, label='transformer'), Line2D([0], [0], color='white', markerfacecolor='dodgerblue', marker='o', markersize=20, label='substation') ] if with_secnet: leghands.insert( 1, Line2D([0], [0], color='crimson', markerfacecolor='crimson', marker='o', markersize=0, label='secondary network')) leghands.insert( -1, Line2D([0], [0], color='white', markerfacecolor='red', marker='o', markersize=20, label='residence')) ax.legend(handles=leghands, loc='best', ncol=1, prop={'size': 25}) if path != None: fig.savefig("{}{}.png".format(path, '-51121-dist'), bbox_inches='tight') return
1e-3, color='lavender', label='chemical accuracy') axins.grid(b=True, which='major', color='black', linestyle='--', linewidth=0.5) axins.grid(b=True, which='minor', color='black', linestyle='-.', linewidth=0.2) axins.set_xlim(x1, x2) axins.xaxis.tick_top() axins.set_ylim(y1, y2) axins.yaxis.tick_right() axins.set_yscale('log') # axins.xaxis.set_minor_locator(MultipleLocator(125)) # axins.xaxis.set_major_locator(MultipleLocator(250)) mark_inset(ax, axins, loc1=2, loc2=3, fc="none", ec="0", linewidth=.75) # ax.legend(loc=3)#, bbox_to_anchor=(1,0.4)) ax.legend(loc=9, fontsize=10.5) #, bbox_to_anchor=(1,0.4)) plt.show() print('macaroni')
def sigmoid(x): def plot_binned_stat(allIouVsCls, val_to_plot, bins=10, pltAll = 0, linestyle = ':', plttype = 'stat',applysigx = True , applysigy = False, plt_unitline=False): color=cm.rainbow(np.linspace(0,1, len(allIouVsCls.keys()))) legendK = [] if pltAll: legendK = allIouVsCls.keys() for i, cls in enumerate(allIouVsCls): xval = FN.sigmoid(torch.FloatTensor(allIouVsCls[cls][val_to_plot[0]])).numpy() if applysigx else allIouVsCls[cls][val_to_plot[0]] yval = FN.sigmoid(torch.FloatTensor(allIouVsCls[cls][val_to_plot[1]])).numpy() if applysigy else allIouVsCls[cls][val_to_plot[1]] if plttype == 'stat': aClsVsRec = binned_statistic(xval, yval,statistic='mean', bins=bins) aClsVsRec_std = binned_statistic(xval, yval,statistic=np.std, bins=bins) #plt.plot((aClsVsRec[1][:-1]+aClsVsRec[1][1:])/2, aClsVsRec[0],color=color[i],marker='o',linestyle=linestyle); plt.errorbar((aClsVsRec[1][:-1]+aClsVsRec[1][1:])/2, aClsVsRec[0], yerr = aClsVsRec_std[0], color=color[i],marker='o',linestyle=linestyle); else: plt.scatter(xval, yval,alpha=0.5,color=color[i],s=20) if pltAll < 2: legendK = legendK + ['all'] allX = np.concatenate([allIouVsCls[cls][val_to_plot[0]] for cls in allIouVsCls]) allY = np.concatenate([allIouVsCls[cls][val_to_plot[1]] for cls in allIouVsCls]) xval = FN.sigmoid(torch.FloatTensor(allX)).numpy() if applysigx else allX yval = FN.sigmoid(torch.FloatTensor(allY)).numpy() if applysigy else allY if plttype == 'stat': aClsVsRec = binned_statistic(xval, yval,statistic='mean', bins=bins) aClsVsRec_std = binned_statistic(xval, yval,statistic=np.std, bins=bins) #plt.plot((aClsVsRec[1][:-1]+aClsVsRec[1][1:])/2, aClsVsRec[0],color=color[-1],marker='o',linestyle='-', linewidth=2); plt.errorbar((aClsVsRec[1][:-1]+aClsVsRec[1][1:])/2, aClsVsRec[0], yerr = aClsVsRec_std[0], color=color[-1],marker='o',linestyle='-', linewidth=2); else: plt.scatter(xval,yval,alpha=0.4,color=color[-1],s=20) plt.xlabel(val_to_plot[0]) plt.ylabel(val_to_plot[1]) plt.legend(legendK) if plt_unitline: plt.plot(xval,xval, 'k-'); plt.show() fname = 'removeEvalResults/fullres/train_checkpoint_stargan_coco_fulleditor_LowResMask_pascal_RandDiscrWdecay_wgan_30pcUnion_noGT_reg_biasM_randRot_fixedD_randDisc_smM_fixInp_imnet_IN_maxPool_V2_180_1227' tr_res = json.load(open(fname,'r')) selected_attrs = ['person', 'bird', 'cat', 'cow', 'dog', 'horse', 'sheep', 'airplane', 'bicycle', 'boat', 'bus', 'car', 'motorcycle', 'train', 'bottle', 'couch', "dining table", "potted plant", 'chair','tv'] attToIdx = {att:i for i,att in enumerate(selected_attrs)} res = tr_res allIouVsCls = {} for key,img in res['images'].items(): for cls in img['perclass']: if cls not in allIouVsCls: allIouVsCls[cls] = {'iou':[], 'recall':[], 'precision':[], 'ocls':[],'acls':[],'gtsize':[], 'predsize':[], 'false_damage':[], 'n_obj':[], 'diff':[]} allIouVsCls[cls]['iou'].append(img['perclass'][cls]['iou']) allIouVsCls[cls]['recall'].append(img['perclass'][cls]['rec']) allIouVsCls[cls]['precision'].append(img['perclass'][cls]['prec']) allIouVsCls[cls]['ocls'].append(img['real_scores'][attToIdx[cls]]) allIouVsCls[cls]['acls'].append(img['perclass'][cls]['remove_scores'][attToIdx[cls]]) allIouVsCls[cls]['rSucc'].append(float(img['perclass'][cls]['remove_scores'][attToIdx[cls]]<0.)) allIouVsCls[cls]['diff'].append(img['real_scores'][attToIdx[cls]] - img['perclass'][cls]['remove_scores'][attToIdx[cls]]) allIouVsCls[cls]['gtsize'].append(img['perclass'][cls]['gtSize']) allIouVsCls[cls]['predsize'].append(img['perclass'][cls]['predSize']) #allIouVsCls[cls]['false_damage'].append(np.max([img['real_scores'][oclsId] - img['perclass'][cls]['remove_scores'][oclsId] for oclsId in img['real_label'] if selected_attrs[oclsId]!=cls])/(len(img['real_label'])-1+1e-6) ) allIouVsCls[cls]['false_damage'].append(np.max([img['real_scores'][oclsId] - img['perclass'][cls]['remove_scores'][oclsId] for oclsId in img['real_label'] if selected_attrs[oclsId]!=cls]) if len(img['real_label'])>1 else np.nan) allIouVsCls[cls]['n_obj'].append(len(img['real_label'])) val_to_plot = ['ocls','recall'] 'person' ,'bird' , 'cat' , 'cow' , 'dog' , 'horse' , 'sheep' , 'airplane' , 'bicycle' ,'boat' , 'bus' , 'car' , 'motorcycle' , 'train' , 'bottle' , 'couch' , 'dining table' , 'potted plant', 'chair' , 'tv' cat2id= {} data = {} ; data['images'] = {} for ann in train_ann: annSp = ann.split() imgid = int(annSp[0].split('.')[0]) cls = annSp[1].lower() if imgid not in data['images']: finfo = subprocess.check_output(['file', 'flickr_logos_27_dataset_images/'+annSp[0]]) data['images'][imgid] = {'bboxAnn': [], 'id': imgid, 'filename':annSp[0], 'split':'train','imgSize': map(int, finfo.split(',')[-2].split('x'))} if cls not in cat2id: cat2id[cls] = len(cat2id) bbox = map(int,annSp[-4:]) img_w,img_h = data['images'][imgid]['imgSize'] bbox = [float(bbox[0])/float(img_w), float(bbox[1])/float(img_h), float(bbox[2]-bbox[0])/float(img_w), float(bbox[3] - bbox[1])/float(img_h)] data['images'][imgid]['bboxAnn'].append({'bbox': bbox, 'cid': cat2id[cls]}) data['categories'] = [{'id':cat2id[cat], 'name':cat} for cat in cat2id] for ann in val_ann: annSp = ann.split() imgid = int(annSp[0].split('.')[0]) cls = annSp[1].lower() if imgid not in data['images']: finfo = subprocess.check_output(['file', 'flickr_logos_27_dataset_images/'+annSp[0]]) data['images'][imgid] = {'bboxAnn': [], 'id': imgid, 'filename':annSp[0], 'split':'train','imgSize': map(int, finfo.split(',')[-2].split('x'))} if cls not in cat2id: cat2id[cls] = len(cat2id) bbox = [0., 0., 1., 1.] data['images'][imgid]['bboxAnn'].append({'bbox': bbox, 'cid': cat2id[cls]}) for ann in val_ann: annSp = ann.split() imgid = int(annSp[0].split('.')[0]) cls = annSp[1].lower() data['images'][imid2index[imgid]]['split'] = 'val' cat2id= {} data = {} ; data['images'] = {} for ann in tqdm(train_ann): annSp = ann.split() if annSp[4]: imgid = int(annSp[2].split('.')[0]) cls = annSp[1].lower() if imgid not in data['images']: finfo = subprocess.check_output(['file', 'images/'+annSp[2]]) data['images'][imgid] = {'bboxAnn': [], 'id': imgid, 'filename':annSp[2], 'split':'train','imgSize': map(int, finfo.split(',')[-2].split('x'))} if cls not in cat2id: cat2id[cls] = len(cat2id) bbox = map(int,annSp[-4:]) img_w,img_h = data['images'][imgid]['imgSize'] bbox = [float(bbox[0])/float(img_w), float(bbox[1])/float(img_h), float(bbox[2]-bbox[0])/float(img_w), float(bbox[3] - bbox[1])/float(img_h)] data['images'][imgid]['bboxAnn'].append({'bbox': bbox, 'cid': cat2id[cls]}) data['categories'] = [{'id':cat2id[cat], 'name':cat} for cat in cat2id] for fname in tqdm(notPresentImgs): finfo = subprocess.check_output(['file', 'images/'+fname]) imgid = int(fname.split('.')[0]) data['images'].append({'bboxAnn': [], 'id': imgid, 'filename':fname, 'split':'train','imgSize': map(int, finfo.split(',')[-2].split('x'))}) import matplotlib.pyplot as plt import numpy as np import numpy as np import seaborn from PIL import Image from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_inset fig, ax = plt.subplots(); ax.imshow(img, origin='upper', extent=[0,128, 128,0]); axins = zoomed_inset_axes(ax, zoom=3, loc=7) extent = [50, 60, 70, 60] axins.imshow(img, interpolation="nearest", origin='upper', extent=[0,128, 0,128]) axins.set_xlim(*extent[:2]) axins.set_ylim(*extent[2:]) axins.yaxis.get_major_locator().set_params(nbins=7) axins.xaxis.get_major_locator().set_params(nbins=7) plt.xticks(visible=False) plt.yticks(visible=False) mark_inset(ax, axins, loc1=1, loc2=3, fc="none", ec="0.5") ax.set_axis_off() plt.draw(); plt.show() fig, ax = plt.subplots(frameon=False); ax.imshow(img, origin='lower'); axins = zoomed_inset_axes(ax, zoom=3, loc=7) extent = [55, 65, 44, 54] axins.imshow(img, interpolation="nearest", origin='lower') axins.set_xlim(*extent[:2]) axins.set_ylim(*extent[2:]) axins.yaxis.get_major_locator().set_params(nbins=7) axins.xaxis.get_major_locator().set_params(nbins=7) #axins.set_axis_off() plt.xticks(visible=False) plt.yticks(visible=False) mark_inset(ax, axins, loc1=2, loc2=3, fc="none", ec="r") ax.set_axis_off() plt.draw(); plt.show() import numpy as np import json from scipy.special import expit import matplotlib.pyplot as plt def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=90) plt.yticks(tick_marks, classes) fmt = '.1f' thresh = cm.max() / 2. #for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): # plt.text(j, i, format(cm[i, j], fmt), # horizontalalignment="center", # color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('Removed Object') plt.xlabel('Change in Classifier Scores after removal')
def plot_2d_scan_unbinned(self, to_file=True, nll_func=None, iminuit_object=None): """ Plot the result of the one-dimensional profiled likelihood scan. :param to_file: bool """ try: mt_, nll_func = self.iminuit_objects[ f"2D_unbinned__{self.sfu.__name__}_{self.bfu.__name__}"] except KeyError: try: self.calc_1d_unbinned_iminuit() mt_, nll_func = self.iminuit_objects[ f"2D_unbinned__{self.sfu.__name__}_{self.bfu.__name__}"] except KeyError: mt_, nll_func = iminuit_object, nll_func if mt_ is None or nll_func is None: raise NotImplementedError @np.vectorize def nll_vec(alpha, mass): return nll_func(alpha, mass) p_alpha_ = PlotHelper.get_error_points_from_iminuit_obj(mt_, "alpha") p_mass_ = PlotHelper.get_error_points_from_iminuit_obj(mt_, "mass") if self.verbose: print("Start plotting: Initialize", flush=True, end="\r") alpha_ = np.sort( np.unique(np.append(np.array(p_alpha_), np.linspace(0.0, 0.8, 50)))) nll_alpha = nll_vec(alpha_, mt_.np_values()[1]) nll_alpha = nll_alpha - np.amin(nll_alpha) if self.verbose: print("Plotting: Got alpha main window", flush=True, end="\r") mass_ = np.sort( np.unique( np.append( np.array(p_mass_), np.linspace(p_mass_[0] - 0.25, p_mass_[-1] + 0.25, 50)))) nll_mass = nll_vec(mt_.np_values()[0], mass_) nll_mass = nll_mass - np.amin(nll_mass) if self.verbose: print("Plotting: Got mass main window", flush=True, end="\r") z_ = np.sqrt( nll_func(0.0, mt_.np_values()[1]) - nll_func(mt_.np_values()[0], mt_.np_values()[1])) f = plt.figure(figsize=(14, 8)) f.subplots_adjust(left=0.15, bottom=0.07, right=0.98, top=0.95, wspace=0.23, hspace=1.0) gs = gridspec.GridSpec(1, 1, figure=f) gs0 = gridspec.GridSpecFromSubplotSpec(7, 2, subplot_spec=gs[0]) ax1 = f.add_subplot(gs0[:-3, :]) PlotHelper.plot_nll_scan_main_window(ax_obj_=ax1, x_=alpha_, y_=nll_alpha, z_=z_) ax_in = inset_axes(ax1, width='50%', height='40%', loc="upper right") PlotHelper.plot_nll_scan_inside_window(ax_obj_=ax_in, x_=alpha_, y_=nll_alpha, x_ticks_=p_alpha_) mark_inset(ax1, ax_in, loc1=2, loc2=4, fc="none", ec="grey", lw=0.5, alpha=0.5) if self.verbose: print("Plotting: Starting contour", flush=True, end="\r") ax2 = f.add_subplot(gs0[4:7, :-1]) PlotHelper.contour_own(ax_obj_=ax2, nll_obj_=nll_vec, m_obj_=mt_, var1_="alpha", var2_="mass") if self.verbose: print("Plotting: End Contour", flush=True, end="\r") ax3 = f.add_subplot(gs0[4:7, -1]) PlotHelper.plot_nll_scan_inside_window( ax_obj_=ax3, x_=mass_, y_=nll_mass, x_ticks_=p_mass_, label_= r"$- 2 \ln \left( \frac{\mathcal{L}}{\mathcal{L}_{\rm{min}}} \right)-\rm{profile}$", x_label=r"$m_{\rm{H}}$", y_label= r"$- 2 \ln \left( \frac{\mathcal{L}}{\mathcal{L}_{\rm{min}}} \right)$" ) file_ = os.path.join( self.save_dir, f"2D_scan_unbinned_{self.sfu.__name__}_{self.bfu.__name__}.png") plt.savefig(file_) if to_file else plt.show()
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes axins = zoomed_inset_axes(axesb, 3.0, loc=4) for i in nhj.keys(): axins.plot(nhjb[i][1], nhja[i][1], "o", markersize=4.0) x1, x2, y1, y2 = 350, 470, 900, 1100 # specify the limits axins.set_xlim(x1, x2) # apply the x-limits axins.set_ylim(y1, y2) # apply the y-limits plt.yticks(visible=False) plt.xticks(visible=False) from mpl_toolkits.axes_grid1.inset_locator import mark_inset mark_inset(axesb, axins, loc1=1, loc2=2, fc="none", ec="0.0") ############################################## # ax_inset=fig.add_axes([0.35,0.17,0.65,0.5]) # ax_inset.xaxis.set_tick_params(labelsize=11) # ax_inset.yaxis.set_tick_params(labelsize=11) # for i in nhj.keys(): # ax_inset.plot(nhjb[i][1],nhja[i][1],"o",markersize=4.0) # ax_inset.set_ylim(900,1100) # ax_inset.set_xlim(350,480) ###################################### # axesb.axvline(nhj[i][0][0],0.0,nhj[i][1][0], color='k', linestyle='--') # axesb.stem(xtj,ytj,linefmt='--', markerfmt='bo', basefmt='r-')
weight="bold", textcoords='offset points', horizontalalignment='right', verticalalignment='bottom', ) #axins.annotate('NAA (24000 Hz)', xy=(29, 24000), # xycoords='data', # xytext=(0, 10),color="w",weight="bold", textcoords='offset points', # horizontalalignment='right', verticalalignment='bottom', # ) plt.xticks(visible=False) plt.yticks(visible=False) # draw a bbox of the region of the inset axes in the parent axes and # connecting lines between the bbox and the inset axes area mark_inset(ax, axins, loc1=1, loc2=2, fc="none", ec="1") axins2 = inset_axes( ax, width="30%", # width = 30% of parent_bbox height=1.5, # height : 1 inch loc=3) axins2.plot(Time, signal, color='r', linewidth=2) t1, t2 = 22., 23.2 axins2.set_xlim(t1, t2) axins2.annotate( 'Spherics', xy=(22.4, 20000), xycoords='data',
def roc_curve_bootstrap_with_readers(y, preds, savepath=None, n_bootstrap=5000, seed=12345, readers=None, inset=True): """Evaluates ROC curve using bootstrapping Also reports confidence intervals and prints them. Parameters ---------- y : numpy.array Ground truth preds : numpy.array Predictions savepath: str Where to save the figure with ROC curve n_bootstrap: Number of bootstrap samples to draw seed : int Random seed """ auc = trunc(roc_auc_score(y, preds), 5) np.random.seed(seed) aucs = [] tprs = [] base_fpr = np.linspace(0, 1, 1001) for i in range(n_bootstrap): ind = np.random.choice(y.shape[0], y.shape[0]) if y[ind].sum() == 0: continue aucs.append(roc_auc_score(y[ind], preds[ind])) fpr, tpr, _ = roc_curve(y[ind], preds[ind]) tpr = np.interp(base_fpr, fpr, tpr) tpr[0] = 0.0 tprs.append(tpr) tprs = np.array(tprs) mean_tprs = np.mean(tprs, 0) std = np.std(tprs, axis=0) tprs_upper = np.minimum(mean_tprs + std, 1) tprs_lower = mean_tprs - std if savepath: tmp = savepath.split('/') tmp2 = tmp[-1] tmp3 = tmp2.split('_') ts = tmp3[0] else: ts = 'test' with open(f'analysis/{ts}_roc.pkl', 'wb') as f: pickle.dump(aucs, f) pickle.dump(tpr, f) pickle.dump(fpr, f) # fig = plt.figure(figsize=(6, 6)) fig, ax = plt.subplots(figsize=(6,6)) fpr, tpr, _ = roc_curve(y, preds, drop_intermediate=False) # plt.fill_between(base_fpr, tprs_lower, tprs_upper, color='grey', alpha=0.2) ax.plot(fpr, tpr, color='midnightblue', label='DeepWrist, AUROC: %0.2f'%(trunc(auc, 2))) ax.plot([0, 1], [0, 1], '--', color='black', label='Random Guess') if readers is not None: for key in readers: data = readers[key] ax.plot([1.0 - data[1]], [data[0]], marker=data[2], label=f'{key} ({trunc(data[1], 2)}, {trunc(data[0], 2)})', color=data[3]) ax.set_xlim(-0.01, 1) ax.set_ylim(0, 1.01) ax.legend(loc=0, bbox_to_anchor=(0.4, 0., 0.4, 0.4), fontsize=8) plt.grid() ax.set_xlabel('1 - Specificity') ax.set_ylabel('Sensitivity') if inset: ax_ins = zoomed_inset_axes(ax, 1.8, loc=10) ax_ins.plot(fpr, tpr, color='midnightblue') ax_ins.plot([0, 1], [0, 1], '--', color='black') if readers is not None: for key in readers: data = readers[key] # ax.plot([data[1]], [data[0]], marker=data[2], label="%s (%0.2f, %0.2f)"%(key, trunc(data[1], 2), trunc(data[0], 2)), color=data[3]) if inset: ax_ins.plot([1.0 - data[1]], [data[0]], marker=data[2], color=data[3]) if inset: x1, x2, y1, y2 = -0.01, 0.46, 0.9, 1.01 ax_ins.set_xlim(x1, x2) ax_ins.set_ylim(y1, y2) ax_ins.set_xticks([]) ax_ins.set_yticks([]) plt.xticks(visible=True) plt.yticks(visible=True) if inset: mark_inset(ax, ax_ins, loc1=1, loc2=2, fc='none', ec="0.5") plt.draw() # plt.tight_layout() if savepath is not None: plt.savefig(savepath, bbox_inches='tight') plt.close(fig) CI_l, CI_h = np.percentile(aucs, 2.5), np.percentile(aucs, 97.5) return auc, CI_l, CI_h
def pr_curve_bootstrap_with_readers(y, preds, savepath=None, readers=None, n_bootstrap=5000, seed=12345, inset=True): precision, recall, _ = precision_recall_curve(y, preds) np.random.seed(seed) auc = average_precision_score(y, preds) aucs = [] for i in range(n_bootstrap): ind = np.random.choice(y.shape[0], y.shape[0]) if y[ind].sum() == 0: continue aucs.append(average_precision_score(y[ind], preds[ind])) # fig = plt.figure(figsize=(6, 6)) fig, ax = plt.subplots(figsize=(6,6)) positives = float(np.sum(y)) total = float(len(y)) baseline = positives / total baseline = trunc(baseline, 2) # plt.fill_between(base_fpr, tprs_lower, tprs_upper, color='grey', alpha=0.2) ax.plot(recall, precision, color='midnightblue', label=f'DeepWrist, AUPR: {trunc(auc, 2)}') ax.plot([0, 1], [baseline, baseline], '--', color='black', label=f'Random Guess (Prevalence: {baseline})') if savepath: tmp = savepath.split('/') tmp2 = tmp[-1] tmp3 = tmp2.split('_') ts = tmp3[0] else: ts = 'test' with open(f'analysis/{ts}_pr.pkl', 'wb') as f: pickle.dump(aucs, f) pickle.dump(precision, f) pickle.dump(recall, f) if readers is not None: for key in readers: data = readers[key] ax.plot([data[1]], [data[0]], marker=data[2], label="%s (%0.2f, %0.2f)"%(key, trunc(data[1], 2), trunc(data[0], 2)), color=data[3]) # ax_ins.plot([data[1]], [data[0]], marker=data[2], color=data[3]) ax.set_xlim(0, 1.01) ax.set_ylim(0, 1.01) ax.set_xlabel('Recall') ax.set_ylabel('Precision') ax.grid() ax.legend(fontsize=8) if inset: ax_ins = zoomed_inset_axes(ax, 2.3, loc=8) ax_ins.plot(recall, precision, color='midnightblue') ax_ins.plot([0, 1], [baseline, baseline], '--', color='black') if readers is not None: for key in readers: data = readers[key] # ax.plot([data[1]], [data[0]], marker=data[2], label="%s (%0.2f, %0.2f)"%(key, trunc(data[1], 2), trunc(data[0], 2)), color=data[3]) if inset: ax_ins.plot([data[1]], [data[0]], marker=data[2], color=data[3]) if inset: x1, x2, y1, y2 = 0.8, 1.01, 0.77, 1.01 ax_ins.set_xlim(x1, x2) ax_ins.set_ylim(y1, y2) ax_ins.set_xticks([]) ax_ins.set_yticks([]) plt.xticks(visible=True) plt.yticks(visible=True) if inset: mark_inset(ax, ax_ins, loc1=2, loc2=4, fc='none', ec="0.5") plt.draw() # plt.tight_layout() if savepath is not None: plt.savefig(savepath, bbox_inches='tight', dpi=300) plt.close(fig) CI_l, CI_h = np.percentile(aucs, 2.5), np.percentile(aucs, 97.5) return auc, CI_l, CI_h
1, loc=2, bbox_to_anchor=(0.22, 0.435), bbox_transform=ax.figure.transFigure) # no zoom axinsMg.plot(wavelengths, observed_flux, 'k', wavelengths, model_flux, 'r') x1, x2, y1, y2 = 5150, 5200, 0.6, 1.2 # specify the limits axinsMg.set_xlim(x1, x2) # apply the x-limits axinsMg.set_ylim(y1, y2) # apply the y-limits axinsMg.xaxis.set_major_locator(ticker.MaxNLocator(3)) plt.title('Mg') #plt.yticks(visible=False) #plt.xticks(visible=False) from mpl_toolkits.axes_grid1.inset_locator import mark_inset mark_inset(ax, axinsMg, loc1=1, loc2=2, fc="none", ec="0.5") #K AxinsK = inset_axes(ax, 3, 1, loc=2, bbox_to_anchor=(0.5, 0.435), bbox_transform=ax.figure.transFigure) # no zoom AxinsK.plot(wavelengths, observed_flux, 'k', wavelengths, model_flux, 'r') AxinsK.xaxis.set_major_locator(ticker.MaxNLocator(4)) x1, x2, y1, y2 = 7650, 7720, 0.6, 1.2 # specify the limits AxinsK.set_xlim(x1, x2) # apply the x-limits AxinsK.set_ylim(y1, y2) # apply the y-limits plt.title('K')
def zoom_taliban_attack_types(attacks): """ Zooms in the particular location of the attacks perpetrated by the Taliban group showing the different attack types. """ group = 'Taliban' fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111) cmap = plt.get_cmap('inferno') plt.title('Attack types perpetrated by the Taliban group\n') # create the map map = Basemap(projection='cyl', lat_0=0, lon_0=0) map.drawmapboundary() map.fillcontinents(color='lightgray', zorder=0) # create the plot structure temp_markers, _MAX = get_group_markers(attacks, group) xs, ys = map(temp_markers['Longitude'], temp_markers['Latitude']) scat = map.scatter(xs, ys, s=temp_markers['Size'], c=temp_markers['Color'], cmap=cmap, marker='o', alpha=0.5, zorder=10) axins = zoomed_inset_axes(ax, 9, loc=2) axins.set_xlim(25, 40) axins.set_ylim(60, 75) plt.xticks(visible=False) plt.yticks(visible=False) map2 = Basemap(llcrnrlon=55, llcrnrlat=25, urcrnrlon=75, urcrnrlat=40, ax=axins) map2.drawmapboundary() map2.fillcontinents(color='lightgray', zorder=0) map2.drawcoastlines() map2.drawcountries() temp_markers, label_color_dict_attack_type = get_group_attack_types_markers( attacks, group) map2.scatter(xs, ys, s=temp_markers['Size'] / 5., c=temp_markers['Color'], alpha=0.5) mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") handles = create_handles(label_color_dict_attack_type, ax) labels = [h.get_label() for h in handles] ax.legend(loc='upper left', bbox_to_anchor=(1, 1), handles=handles, labels=labels) plt.savefig('taliban_zoom_attack_types.pdf', bbox_inches='tight') plt.show()
def parse_encyclopedia(path, filename=None, q_value=0.05, IO=True): """Helper to generate a list of peptides an analyze from an encyclopedia output. Filters the input to the q-value specified by the user (default of 0.05) Typical use: peptides = gen_peptide_list('./') **assumes that the encyclopedia file you want to work with is the only file in the directory you are using Optional arguments: ** q_value=[float] | specify the q-value cutoff to use to filter peptides (0.0 will take all peptides in the input) ** filename | directly specify the full path and filename to analyze instead of assuming you will use the first one (alphabetically) in the directory ** IO | True will show outputs, false will supress Return: Returns a pandas dataframe indexed by the peptide sequence and bearing columns of 'mz' and 'z' (mass/charge, charge) """ #check for optional arguments then read proper file if filename is None: filename = glob.glob(path + '/*.encyclopedia.txt')[0] if IO: print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('reading peptides from encyclopedia file ' + filename) #generate pandas file, filter, parse peptides, save encyc_rts values, save charge values, calculate mz, save proteins encyc = pandas.read_csv(filename, sep='\t') all_entries = encyc[encyc['q-value'] < q_value] peptides = [i[2:-2] for i in all_entries['peptide']] encyc_rts = [float(i.split(':')[1]) / 60.0 for i in all_entries['PSMId']] zs = [i.split('+')[-1] for i in all_entries['PSMId']] prot_names = [i for i in all_entries['proteinIds']] mzs = [] for index, pepseq in enumerate(peptides): mzs.append(calc_mz(pepseq, int(zs[index]))) #mzs = [calc_mz(pair[0], int(zs[pair[1]])) for pair in enumerate(peptides))] assert len(peptides) == len(encyc_rts) assert len(peptides) == len(zs) assert len(peptides) == len(prot_names) assert len(peptides) == len(mzs) #convert to a dictionary pdl = {} for i, p in enumerate(peptides): pdl[p] = [encyc_rts[i], zs[i], prot_names[i], mzs[i]] # show plots for q-value criteria if IO: print(str(encyc.shape[0]) + ' peptides identified') print(str(len(peptides)) + ' peptides meet q-value criteria') print( str(encyc.shape[0] - len(peptides)) + ' peptides fail q-value criteria') fig, ax = pylab.subplots( ) # create a new figure with a default 111 subplot ax.hist(encyc['q-value'].dropna(), bins=100) axins = zoomed_inset_axes( ax, 2, loc=1) # zoom-factor: 2.5, location: upper-left axins.hist(encyc['q-value'].dropna(), bins=100) axins.set_xlim(0, q_value * 2) # apply the x-limits axins.set_ylim(0, ax.get_ylim()[1] / 4) # apply the x-limits axins.vlines([q_value], 0, ax.get_ylim()[1] / 4, colors='red', linestyle='dashed', label='q-cuttoff') mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") ax.set_xlabel('q-value') ax.set_ylabel('peptides') pylab.show() print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') # convert to a pandas dataframe mz_df = pandas.DataFrame.from_dict(pdl, orient='index') mz_df = mz_df.rename(index=str, columns={ 0: 'encyc_rt', 1: 'z', 2: 'proteinIds', 3: 'mz' }) return mz_df
def plot_corr_dist( Xa, Xp, inset=True, xlabel='$F_{dft}$' + r' $(kcal \times mol^{-1} \times \AA^{-1})$', ylabel='$F_{dft}$' + r' $(kcal \times mol^{-1} \times \AA^{-1})$', figsize=[13, 10], cmap=mpl.cm.viridis): Fmx = Xa.max() Fmn = Xa.min() label_size = 14 mpl.rcParams['xtick.labelsize'] = label_size mpl.rcParams['ytick.labelsize'] = label_size fig, ax = plt.subplots(figsize=figsize) # Plot ground truth line ax.plot([Fmn, Fmx], [Fmn, Fmx], '--', c='r', linewidth=3) # Set labels ax.set_xlabel(xlabel, fontsize=22) ax.set_ylabel(ylabel, fontsize=22) #cmap = mpl.cm.viridis #cmap = mpl.cm.brg # Plot 2d Histogram bins = ax.hist2d(Xa, Xp, bins=200, norm=LogNorm(), range=[[Fmn, Fmx], [Fmn, Fmx]], cmap=cmap) # Build color bar #cbaxes = fig.add_axes([0.91, 0.1, 0.03, 0.8]) cb1 = fig.colorbar(bins[-1], cmap=cmap) cb1.set_label('Count', fontsize=16) # Annotate with errors PMAE = hdt.calculatemeanabserror(Xa, Xp) PRMS = hdt.calculaterootmeansqrerror(Xa, Xp) ax.text(0.75 * ((Fmx - Fmn)) + Fmn, 0.43 * ((Fmx - Fmn)) + Fmn, 'MAE=' + "{:.3f}".format(PMAE) + '\nRMSE=' + "{:.3f}".format(PRMS), fontsize=20, bbox={ 'facecolor': 'white', 'alpha': 0.5, 'pad': 5 }) if inset: axins = zoomed_inset_axes(ax, 2.2, loc=2) # zoom = 6 sz = 6 axins.hist2d(Xa, Xp, bins=50, range=[[Fmn / sz, Fmx / sz], [Fmn / sz, Fmx / sz]], norm=LogNorm(), cmap=cmap) axins.plot([Xa.min(), Xa.max()], [Xa.min(), Xa.max()], '--', c='r', linewidth=3) # sub region of the original image x1, x2, y1, y2 = Fmn / sz, Fmx / sz, Fmn / sz, Fmx / sz axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) axins.yaxis.tick_right() plt.xticks(visible=True) plt.yticks(visible=True) mark_inset(ax, axins, loc1=1, loc2=3, fc="none", ec="0.5") Ferr = Xa - Xp std = np.std(Ferr) men = np.mean(Ferr) axh = plt.axes([.49, .16, .235, .235]) axh.hist(Ferr, bins=75, range=[men - 4 * std, men + 4 * std], normed=True) axh.set_title('Difference distribution') #plt.draw() plt.show()
def plot_road_network(net, subs, inset={}, path=None): """ """ fig = plt.figure(figsize=(40, 40), dpi=72) ax = fig.add_subplot(111) sub_x = [subs[s]['cord'][0] for s in subs] sub_y = [subs[s]['cord'][1] for s in subs] # Draw nodes ax.scatter(sub_x, sub_y, c='dodgerblue', s=2000) DrawNodes(net, ax, label='T', color='green', size=25) DrawNodes(net, ax, label='R', color='black', size=2.0) # Draw edges d = {'edges':list(net.edges()), 'geometry':[LineString((net.nodes[e[0]]['cord'],net.nodes[e[1]]['cord'])) \ for e in net.edges()]} df_edges = gpd.GeoDataFrame(d, crs="EPSG:4326") df_edges.plot(ax=ax, edgecolor="black", linewidth=2.0, linestyle="dashed") ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) # Inset figures for sub in inset: axins = zoomed_inset_axes(ax, inset[sub]['zoom'], loc=inset[sub]['loc']) axins.set_aspect(1.3) # Draw nodes ax.scatter([subs[sub]['cord'][0]], [subs[sub]['cord'][1]], c='dodgerblue', s=2000) DrawNodes(inset[sub]['graph'], axins, label='T', color='green', size=25) DrawNodes(inset[sub]['graph'], axins, label='R', color='black', size=2.0) # Draw edges d = {'edges':list(inset[sub]['graph'].edges()), 'geometry':[LineString((inset[sub]['graph'].nodes[e[0]]['cord'], inset[sub]['graph'].nodes[e[1]]['cord'])) \ for e in inset[sub]['graph'].edges()]} df_edges = gpd.GeoDataFrame(d, crs="EPSG:4326") df_edges.plot(ax=axins, edgecolor="black", linewidth=2.0, linestyle="dashed") axins.tick_params(bottom=False, left=False, labelleft=False, labelbottom=False) mark_inset(ax, axins, loc1=inset[sub]['loc1'], loc2=inset[sub]['loc2'], fc="none", ec="0.5") # Legend for the plot leghands = [ Line2D([0], [0], color='black', markerfacecolor='black', marker='o', markersize=0, label='road network'), Line2D([0], [0], color='white', markerfacecolor='green', marker='o', markersize=20, label='transformer'), Line2D([0], [0], color='white', markerfacecolor='black', marker='o', markersize=20, label='road node'), Line2D([0], [0], color='white', markerfacecolor='dodgerblue', marker='o', markersize=20, label='substation') ] ax.legend(handles=leghands, loc='best', ncol=1, prop={'size': 25}) if path != None: fig.savefig("{}{}.png".format(path, '-51121-road'), bbox_inches='tight') return
def run_expr( dens_func_P, dens_func_Q, log_likelihood_ratio_func, num_composition, use_cornish_fisher=False, left=-np.inf, right=np.inf, title=None, ax=None, log_scale=False, zoom_in=False, ): print("$$$$$ n:{}".format(num_composition)) moments_P, errs = edgeworth.compute_moments(log_likelihood_ratio_func, dens_func_P, max_order=4, left=left, right=right) kappas_P = edgeworth.compute_cumulants(moments_P) moments_Q, errs = edgeworth.compute_moments(log_likelihood_ratio_func, dens_func_Q, max_order=4, left=left, right=right) kappas_Q = edgeworth.compute_cumulants(moments_Q) print("\t\tCumulants of Q: {}".format(kappas_Q)) print("\t\tCumulants of P: {}".format(kappas_P)) sigma_square_P = [kappas_P[1]] * num_composition sigma_square_Q = [kappas_Q[1]] * num_composition kappa_3_P = [kappas_P[2]] * num_composition kappa_3_Q = [kappas_Q[2]] * num_composition kappa_4_P = [kappas_P[3]] * num_composition kappa_4_Q = [kappas_Q[3]] * num_composition mu_f = ((moments_Q[0] - moments_P[0]) / np.sqrt(kappas_P[1]) * np.sqrt(num_composition)) alpha = np.linspace(1e-7, 1 - 1e-7, 100) print("\t\tmu_f:{}".format(mu_f)) start = time.time() f_clt = edgeworth.compute_gdp_clt(alpha, mu_f) clt_time = time.time() - start print("\t\tCLT used {} seconds.".format(clt_time)) f_edgeworth = [] start = time.time() for aa in alpha: val = edgeworth.approx_f_edgeworth( aa, sigma_square_P, sigma_square_Q, kappa_3_P, kappa_3_Q, kappa_4_P, kappa_4_Q, mu_f, use_cornish_fisher=use_cornish_fisher, ) f_edgeworth.append(val) edgeworth_time = time.time() - start print("\t\tEdgeworth used {} seconds.".format(edgeworth_time)) f_edgeworth = np.array(f_edgeworth) epsilon = np.linspace(-6, 6, 100) start = time.time() f_numerical, f_eps_delta, deltas = edgeworth.approx_f_numerical( dens_func_Q, log_likelihood_ratio_func, num_composition, epsilon, alpha=alpha, left=left, right=right, ) numerical_time = time.time() - start print("\t\tNumerical used {} seconds.".format(numerical_time)) if ax is not None: line1, = ax.plot(alpha, f_numerical, linewidth=4, color="k", linestyle="-") line2, = ax.plot(alpha, f_edgeworth, linewidth=4, color="r") line3, = ax.plot(alpha, f_clt, linewidth=4, color="b", linestyle="--") ax.set_xlabel(r"Type I Error", fontsize=30) ax.set_ylabel(r"Type II Error", fontsize=30) ax.xaxis.set_tick_params(size=18, labelsize=30) ax.yaxis.set_tick_params(size=18, labelsize=30) if title is not None: ax.set_title(title, fontdict={"fontsize": 30}) if log_scale: ax.set_yscale("log") if zoom_in: from mpl_toolkits.axes_grid1.inset_locator import ( zoomed_inset_axes, mark_inset, ) axins = zoomed_inset_axes( ax, 1.8, loc=1) # zoom-factor: 2.5, location: upper-left axins.plot(alpha, f_numerical, linewidth=4, color="k", linestyle="-") axins.plot(alpha, f_edgeworth, linewidth=4, color="r") axins.plot(alpha, f_clt, linewidth=4, color="b", linestyle="--") axins.set_xticks([]) axins.set_yticks([]) x1, x2, y1, y2 = 0.0, 0.35, 0, 0.4 # specify the limits axins.set_xlim(x1, x2) # apply the x-limits axins.set_ylim(y1, y2) # apply the y-limits mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") else: if num_composition == 1: ax.legend(["numerical", "Edgeworth", "CLT"], prop={"size": 30}) pickle_out = open("laplace_primal_n{}.pickle".format(num_composition), "wb") pickle.dump( { "f_numerical": f_numerical, "f_edgeworth": f_edgeworth, "f_eps_delta": f_eps_delta, "f_clt": f_clt, "epsilon": epsilon, "deltas": deltas, "clt_time": clt_time, "edgeworth_time": edgeworth_time, "numerical_time": numerical_time, }, pickle_out, ) pickle_out.close() return clt_time, edgeworth_time, numerical_time, alpha, f_edgeworth
def plot_mean_pol(mPols, log_x=False, log_y=False, show=True): txt = 'Polarization' fig = plt.figure(num=None, figsize=(8, 5), dpi=150, facecolor='w', edgecolor='k') ax1 = fig.add_subplot(111) model = 'Vicsek' if mPols[0].input.neighbor_norm == True else 'Flying XY' title = '{}, {} Model'.format(txt, model) #ax1.set_title(title, fontsize=14, fontweight='bold') ax1.set_xlabel('$D$', fontsize=22, fontweight='bold', labelpad=-2) ax1.set_ylabel(r'$<\Pi>$', fontsize=22, fontweight='bold') mPols_list = seperate_by_npart(mPols) #ax1.set_xlim([0,0.6]) cmap = plt.get_cmap('jet') colors = [cmap(i) for i in np.linspace(0, 0.9, len(mPols_list))] # #inset = True inset = False if inset: colors = ['b'] * 10 axins = zoomed_inset_axes(ax1, 7, loc=1, bbox_to_anchor=(0.65, 0.9), bbox_transform=ax1.figure.transFigure) axins.axis([0.23, 0.5, 0, 0.1]) axins.get_xaxis().set_visible(False) axins.get_yaxis().set_visible(False) mark_inset(ax1, axins, loc1=2, loc2=4, fc="none", ec="0.5") linestyles = ['-', '--', '-.', ':'] for n, mPols in enumerate(mPols_list): dirs = [val.output_dir for val in mPols] # dirs x = [val.input.noise for val in mPols] # noise y = [val.mValue for val in mPols] # mPol if inset: ax1.plot(x, y, linestyle=linestyles[n % len(linestyles)], linewidth=2.5, label=r'N = {}'.format(mPols[0].input.npart), color=colors[n], picker=True) else: ax1.plot(x, y, linestyle=linestyles[n % len(linestyles)], linewidth=0, label=r'N = {}'.format(mPols[0].input.npart), marker='o', markersize=8, color=colors[n], picker=True) if inset: axins.plot( x, y, linestyle=linestyles[n % len(linestyles)], linewidth=3, label=r'N = {}'.format( mPols[0].input.npart), #marker='o', markersize = 4, color=colors[n], picker=False) def onpick_polar(event): ind = event.ind thisline = event.artist line_index = ax1.lines.index(thisline) #print 'Plotting ', plot_output_dirs[line_index][ind] time = None direc = mPols_list[line_index][ind].output_dir if not isdir(direc): direc = direc.split(os.sep)[-1] if not isdir(direc): raise FileNotFoundError('Error: directory not found!') if event.mouseevent.button == 2: input = read_input_from_dir(direc) pol = calc_property(direc, 'Pols', Pol_data_calc, read=False) plot_property_vs_time([pol]) return True if event.mouseevent.button == 3: input = mPols_list[line_index][ind].input time = get_value_box( title='Drawing snapshot for D={}, maximum time = {:.2f}'. format(input.noise, mPols_list[line_index][ind].simlen), prompt='Choose time:') try: time = float(time) if time == 0: return except: time = None snap = snapshot(mPols_list[line_index][ind].output_dir, time=time) plot_snap( snap, save=True) #, color = 'w', backgroundcolor='k', clusters=True) if (log_x): ax1.set_xscale('log') if (log_y): ax1.set_yscale('log') ax1.legend(loc='upper right') ax1.set_ylim([0, 1]) if inset: axins.xaxis.tick_top() fig.canvas.mpl_connect('pick_event', onpick_polar) filename = 'Polarization_vs_noise{}.png'.format(model) fig.savefig(filename, dpi=fig.dpi) if show: plt.show() return
axins.text(x, r.f(x) - 0.05, "{}".format(n), color="r", fontsize="10", verticalalignment="top", horizontalalignment="center", clip_on=True, zorder=100) else: axins.text(x, r.f(x) + 0.05, "{}".format(n), color="r", fontsize="10", verticalalignment="bottom", horizontalalignment="center", clip_on=True, zorder=100) axins.plot(xfine, xfine * 0, ls=":", color="0.5") mark_inset(ax, axins, loc1=3, loc2=4, fc="none", ec="0.5", zorder=10) f = plt.gcf() f.set_size_inches(7.20, 7.20) plt.tight_layout() plt.savefig("newton_%2.2d.pdf" % (n))
#y = np.linspace(0,1,128) #X,Y = np.meshgrid(x,y,indexing='ij') #x_skip = 8 #y_skip = 4 #plt.pcolormesh(x,y,sigma.T,cmap='RdBu_r') #plt.quiver(X[::x_skip,::y_skip],Y[::x_skip,::y_skip],u[::x_skip,::y_skip],v[::x_skip,::y_skip],pivot='center',units='width',headaxislength=5,scale=7) #axins.set_xlim(155*1./2,157.5*1./2) #axins.set_ylim(0,1) yfrac = yy-np.floor(yy) mat = yfrac>0.5 axins.imshow(mat.T,vmin=-0.5, vmax=1.5, extent=[55,60,55,60],interpolation='nearest',origin='lower',cmap='binary',alpha=0.8) #plt.pcolormesh(xx,yy,mat,cmap='bone') #plt.clim([-1.5,1.5]) #axins.set_xlim(-10,-20) #axins.set_ylim(-10,-20) #axins.set_xlim(80,90) #axins.set_ylim(80,90) axins.xaxis.set_major_locator(nullloc) axins.yaxis.set_major_locator(nullloc) mark_inset(axmain[2],axins,2,4,fc='none',ec='0.5') plt.suptitle('Acoustic wave propagation in layered periodic media',fontsize=25,color='#EEEEEE') plt.figtext(0.5,0.05,'Units scaled to medium period', fontsize=15, horizontalalignment='center',color='#EEEEEE') plt.figtext(0.5,0.075,'$x$', fontsize=25, horizontalalignment='center',color='#EEEEEE') plt.figtext(0.05,0.5,'$y$', fontsize=25, verticalalignment='center',color='#EEEEEE') plt.savefig('_dispersion.png',dpi=100, facecolor=fig.get_facecolor(), edgecolor='none') plt.close()
bins=10, normed=True, alpha=0.7) ax2.plot(p, x, 'k', linewidth=2) ax2.set(xlabel='fraction of observations', ylabel='feet') # cumulative ax3.scatter(annual_highs['HT'], annual_highs['cumprob']) ax3.plot(x, cp, 'k', linewidth=2) ax3.set(xlabel='feet', ylabel='cumulative probability') # zoom in for 2nd subplot ax4.scatter(annual_highs['HT'], annual_highs['cumprob']) ax4.plot(x, cp, 'k') ax4.set(xlim=(50, 60), ylim=(0.9, 1.0), xlabel='feet', ylabel='cumulative probability') ax4.axhline(0.99, linestyle='dashed') ax4.axvline(one_hundred_year_flood, linestyle='dashed') ax4.annotate(xy=(one_hundred_year_flood + 0.1, 0.98), s='100-year = ' + "%0.1f ft" % one_hundred_year_flood) mark_inset(ax3, ax4, loc1=1, loc2=3, fc="none", ec="0.5") # set title plt.suptitle('Annual High Water Mark - Brays Bayou', x=0.5, y=0.925, fontsize=15) plt.show()
[datetime.date(i, j, 1) for i in range(2013, 2019) for j in [1, 5, 9]]) axins.plot( model_data[model_data['Date'] < split_date]['Date'][window_len:].astype( datetime.datetime), training_set['cl_Close**'][window_len:], label='Actual') axins.plot( model_data[model_data['Date'] < split_date]['Date'][window_len:].astype( datetime.datetime), ((np.transpose(cl_model.predict(LSTM_training_inputs)) + 1) * training_set['cl_Close**'].values[:-window_len])[0], label='Predicted') axins.set_xlim([datetime.date(2017, 3, 1), datetime.date(2017, 5, 1)]) axins.set_ylim([10, 60]) axins.set_xticklabels('') mark_inset(ax1, axins, loc1=1, loc2=3, fc="none", ec="0.5") plt.savefig( "C:/wamp64/www/crypto-predict_website/images/trainset_timepoint.png") #plt.show() #TEST THIS #date2017 = [datetime.time(2017, i+1, 1) for i in range(12)] #date2018 = [datetime.time(2018, i+1, 1) for i in range(12)] #total_date = [datetime.combine(date2017, date2018)] fig, ax1 = plt.subplots(1, 1) ax1.set_xticks( ([datetime.date(i, j, 1) for i in range(2013, 2019) for j in [1, 5, 9]])) ax1.set_xticklabels( ([datetime.date(i, j, 1) for i in range(2013, 2019) for j in [1, 5, 9]])) ax1.plot(
def map_ssp_view(self): """plot all the ssp in the database""" view_rows = self._get_all_ssp_view_rows() if view_rows is None: raise DbError("Unable to retrieve ssp view rows > Empty database?") if len(view_rows) == 0: raise DbError("Unable to retrieve ssp view rows > Empty database?") # prepare the data ssp_x = list() ssp_y = list() ssp_label = list() for vr in view_rows: ssp_x.append(vr[b'cast_position'].x) ssp_y.append(vr[b'cast_position'].y) ssp_label.append(vr[b'pk']) ssp_x_min = min(ssp_x) ssp_x_max = max(ssp_x) ssp_x_mean = (ssp_x_min + ssp_x_max) / 2 ssp_x_delta = max(0.05, abs(ssp_x_max - ssp_x_min)/5) ssp_y_min = min(ssp_y) ssp_y_max = max(ssp_y) ssp_y_mean = (ssp_y_min + ssp_y_max) / 2 ssp_y_delta = max(0.05, abs(ssp_y_max - ssp_y_min)/5) log.info("data boundary: %.4f, %.4f (%.4f) / %.4f, %.4f (%.4f)" % (ssp_x_min, ssp_x_max, ssp_x_delta, ssp_y_min, ssp_y_max, ssp_y_delta)) # make the world map fig = plt.figure() #plt.title("SSP Map (%s profiles)" % len(view_rows)) ax = fig.add_subplot(111) plt.ioff() wm = self._world_draw_map() # x, y = wm(ssp_x_mean, ssp_y_mean) # wm.scatter(x, y, s=18, color='y') if ssp_x_mean > 0: ssp_loc = 2 else: ssp_loc = 1 max_delta_range = max(abs(ssp_x_min-ssp_x_max),abs(ssp_y_min-ssp_y_max)) log.info("maximum delta range: %s" % max_delta_range) if max_delta_range > 15: ins_scale = 6 elif max_delta_range > 12: ins_scale = 9 elif max_delta_range > 6: ins_scale = 12 elif max_delta_range > 3: ins_scale = 15 else: ins_scale = 18 ax_ins = zoomed_inset_axes(ax, ins_scale, loc=ssp_loc) ax_ins.set_xlim((ssp_x_min - ssp_x_delta), (ssp_x_max + ssp_x_delta)) ax_ins.set_ylim((ssp_y_min - ssp_y_delta), (ssp_y_max + ssp_y_delta)) m = self._inset_draw_map(llcrnrlon=(ssp_x_min - ssp_x_delta), llcrnrlat=(ssp_y_min - ssp_y_delta), urcrnrlon=(ssp_x_max + ssp_x_delta), urcrnrlat=(ssp_y_max + ssp_y_delta), ax_ins=ax_ins) x, y = m(ssp_x, ssp_y) m.scatter(x, y, marker='o', s=16, color='r') m.scatter(x, y, marker='.', s=1, color='k') if ssp_x_mean > 0: mark_inset(ax, ax_ins, loc1=1, loc2=4, fc="none", ec='y') else: mark_inset(ax, ax_ins, loc1=2, loc2=3, fc="none", ec='y') ax_ins.tick_params(color='y', labelcolor='y') for spine in ax_ins.spines.values(): spine.set_edgecolor('y') #fig.tight_layout() plt.show()
def scatter_plot_energies(x2d, energies, visualization_options, min_energy, max_energy, x1_sub=-2.06, zoom_on_plot=True, x2_sub=-1.70, y1_sub=0.96, y2_sub=1.37): """Plots the 2D PCA of the data with the associated energies Args: x2d (numpy array): 2d matrix containing the points given by a 2D PCA on the data matrix energies (numpy array): array of all the Delta G(Rxn A) energies of the molecules visualization_options (dict): contains the options for visualization (plotting) zoom_on_plot (bool): if True, defines a region inside the actual plot on which it is possible to zoom to have better details min_energy (float): minimum energy present in all the energies max_energy (float): maximum energy present in all the energies x1_sub (float): top left x coordinate for defining a box on which the plot is zoomed on x2_sub (float): bottom right x coordinate for defining a zone on which the plot is zoomed on y1_sub (float): top left y coordinate for defining a box on which the plot is zoomed on y2_sub (float): bottom right y coordinate for defining a box on which the plot is zoomed on """ # Set given plot values locally figsize = viz.get_option(visualization_options, 'figsize') fontsize = viz.get_option(visualization_options, 'fontsize') colormap = viz.get_option(visualization_options, 'colormap') # === Main plot === # Title of plot energy_fig = plt.figure(figsize=figsize) ax = energy_fig.add_subplot(111) ax.set_title( r"2D PCA with the associated $\Delta G (\textrm{Rxn}$ $A)$ energies", fontsize=fontsize) scatter = ax.scatter(x2d[:, 0], x2d[:, 1], c=energies, cmap=colormap, alpha=0.05, s=10, vmin=min_energy, vmax=max_energy) colorbar = plt.colorbar(scatter, label=r"$\Delta G (\textrm{Rxn}$ $A)$ [kcal/mol]") colorbar.set_alpha(0.5) colorbar.draw_all() if zoom_on_plot: # === Zoomed plot === axin = zoomed_inset_axes(ax, 4, loc=2) axin.scatter(x2d[:, 0], x2d[:, 1], c=energies, cmap=colormap, alpha=0.1, s=10, vmin=min_energy, vmax=max_energy) # subregion of the original image axin.set_xlim(x1_sub, x2_sub) axin.set_ylim(y1_sub, y2_sub) plt.xticks(visible=False) plt.yticks(visible=False) # Draw a frame around the subplot mark_inset(ax, axin, loc1=1, loc2=3, fc="none", ec="0.5") plt.tight_layout() if viz.do_plot(visualization_options): viz.visualize(energy_fig, 'energies', visualization_options)
def color_nodes(net, inset={}, path=None, vmax=1.05): fig = plt.figure(figsize=(35, 30), dpi=72) ax = fig.add_subplot(111) # Draw edges DrawEdges(net, ax, label=['P', 'E', 'S'], color='black', width=1.0) # Draw nodes d = { 'nodes': net.nodes(), 'geometry': [Point(net.nodes[n]['cord']) for n in net.nodes()], 'voltage': [net.nodes[n]['voltage'] for n in net.nodes()] } df_nodes = gpd.GeoDataFrame(d, crs="EPSG:4326") divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.001) df_nodes.plot(ax=ax, column='voltage', markersize=40.0, cmap=cm.plasma, vmin=0.80, vmax=vmax, cax=cax, legend=True) cax.set_ylabel("Voltage(in pu)", fontsize=30) cax.tick_params(labelsize=30) ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) # Inset figures for sub in inset: axins = zoomed_inset_axes(ax, inset[sub]['zoom'], loc=inset[sub]['loc']) axins.set_aspect(1.3) # Draw nodes and edges DrawEdges(inset[sub]['graph'], axins, label=['P', 'E', 'S'], color='black', width=1.0) d = {'nodes':inset[sub]['graph'].nodes(), 'geometry':[Point(inset[sub]['graph'].nodes[n]['cord']) \ for n in inset[sub]['graph'].nodes()], 'voltage':[inset[sub]['graph'].nodes[n]['voltage'] \ for n in inset[sub]['graph'].nodes()]} df_nodes = gpd.GeoDataFrame(d, crs="EPSG:4326") df_nodes.plot(ax=axins, column='voltage', markersize=30.0, cmap=cm.plasma, vmin=0.80, vmax=vmax) axins.tick_params(bottom=False, left=False, labelleft=False, labelbottom=False) mark_inset(ax, axins, loc1=inset[sub]['loc1'], loc2=inset[sub]['loc2'], fc="none", ec="0.5") if path != None: fig.savefig("{}{}.png".format(path, '-dist-voltage'), bbox_inches='tight') return
color=[0.4660, 0.6740, 0.1880], label="Frequenza di risonanza teorica") plt.plot([rlc.f_ris_regressione, rlc.f_ris_regressione], [min(rlc._amp_teo), max(rlc._amp_teo)], '--', linewidth=1.8, color=[0, 0.4470, 0.7410], label="Frequenza di risonanza per regressione") if (idx == 2): zoom.set_xlim(1e4, 3e4) zoom.set_ylim(-10, 2) else: zoom.set_xlim(1.5e4, 2e4) zoom.set_ylim(-15, 0.5) plt.grid(which='both') mark_inset(primary_ax, zoom, loc1=2, loc2=4, fc="none", ec="0.5") # Grafico fase plt.subplot(2, 1, 2) rlc.plot_teorica_fase() plt.errorbar(rlc.freq, rlc.fase, rlc.sigmaFase, rlc.sigmaFreq, '.', ecolor=[0.6350, 0.0780, 0.1840], color=[0.6350, 0.0780, 0.1840], markersize=10, linewidth=1.8, label="Valori sperimentali") plt.plot([rlc.f_ris_teo, rlc.f_ris_teo],
lw=.5, linestyle='-', label=label_legend ) axins_a.plot(t, u_ssls[:, 1], color=sto_color, lw=1, linestyle='-' ) np.save('OneLongPathSolutionSto' + eps_prefix + '.npy', np.transpose(np.array([t, u_ssls[:, 0], u_ssls[:, 1]]))) # plt.yticks([y1-100, y2-100], visible=True) plt.xticks([t1-200, t2-200], visible=True) mark_inset( ax2, axins_a, loc1=3, loc2=4, fc="none", ec="0.5" ) ax1.legend(loc='upper center', bbox_to_anchor=(0.5, 1.315), ncol=4, fancybox=False, shadow=False) plt.tight_layout() plt.savefig(file_name1, resolution=1000)
def plotConc(concData, lonData, latData, saveLoc, modelRun, prtype, ip1, spc, cmapType, bins, minVal, maxVal, extension, name, removed,buff): """ Plots and saves concentration data. Will plot difference data if difference data was passed. """ # useful things for determining projection details lowLon = np.amin(lonData) lowLat = np.amin(latData) highLon = np.amax(lonData) highLat = np.amax(latData) maxDim = maxDimensions(lowLon,highLon,lowLat,highLat,buff) midLon = (highLon+lowLon)/2 midLat = (highLat + lowLat)/2 # Uncomment the following lines for an alternative midLatLon calculation #mids = midLatLon(lonData,latData) #midLon = mids['midLon'] #midLat = mids['midLat'] max_width = maxDim['xDist'] max_height = maxDim['yDist'] # Initialize the figure # Create the map based on projection type if (prtype=='ortho') or (prtype == 'nsper') or (prtype == 'laea') or (prtype == 'aeqd') or (prtype == 'gnom') or (prtype == 'lcc'): concMap = Basemap(projection=prtype, resolution = 'c', lon_0=midLon, lat_0=midLat, width=max_width, height=max_height) elif prtype == 'stere': concMap = Basemap(projection=prtype, lon_0=midLon,lat_0=midLat,width=max_width,height=max_height) elif (prtype == 'cyl') or (prtype == 'merc'): concMap = Basemap(projection=prtype, resolution='c', llcrnrlat=lowLat, urcrnrlat=highLat, llcrnrlon=lowLon, urcrnrlon=highLon) elif (prtype == 'aea') or (prtype == 'eqdc'): concMap = Basemap(projection = prtype, lon_0=midLon, lat_0=midLat, llcrnrlat=lowLat, urcrnrlat=highLat, llcrnrlon=lowLon, urcrnrlon=highLon) else: print('Error: Could not generate map. Try a different projection.') # Can check the available basemap types and add to existing if statements # Add in other map details mapColor = cmapType mapBins = bins # if stripping the borders of the data.... if removed != 0: ni = len(lonData) nj = len(lonData[0]) n_pil = removed x, y = concMap(lonData[n_pil:ni-n_pil,n_pil:nj-n_pil], latData[n_pil:ni-n_pil,n_pil:nj-n_pil]) concMap.pcolormesh(x,y,concDiff[n_pil:ni-n_pil,n_pil:nj-n_pil],cmap=plt.cm.get_cmap(mapColor,mapBins)) else: x, y = concMap(lonData, latData) concMap.pcolormesh(x, y, concData, cmap=plt.cm.get_cmap(mapColor, mapBins)) concMap.drawcoastlines(color='lightgray') concMap.drawcountries(color='gray') concMap.drawstates(color='gray') # Comment out the following to remove lonlat lines concMap.drawmeridians(np.arange(0,360,10), labels=[0,0,0,1], fontsize=6) concMap.drawparallels(np.arange(-180,180,10), labels=[1,0,0,0],fontsize=6) # Add colorbar and details #TODO: Fix the set label option for the colorbar, right now the colorbar doesn't have a title cbar = plt.colorbar(extend = extension, shrink=0.5) cbar.set_label=('Concentration: '+spc) plt.clim(minVal, maxVal) # Add subplot concData2 = [50:200, 50:200] fig, ax = plt.subplots(figsize=[3,3]) axins = zoomed_inset_axes(ax, 5, loc=1) axins.imshow(concData2, interpolation='nearest', origin='lower') mark_inset(ax,axins,loc1=2,loc2=4,fc="none",ec="o.5") # Name and save the figure hy = ((os.popen('r.ip1 {}'.format(ip1))).read()).lstrip() plt.title('{}, {} \n hy: {}, Spc: {}'.format(name,modelRun, hy,spc)) fig.savefig(os.path.join(saveLoc, modelRun) + '_' + spc + '_' + name + '.png', dpi=300, bbox_inches='tight', pad_inches=0.3) plt.close('all')
levels=levels, axes=axes, cmap='coolwarm'), ax=axes) cbar.set_label(r"Dislocation $[\mathrm m]$") op.annotate_plot(axes) axes.axis(False) # Add zoom axins = zoomed_inset_axes(axes, 2.5, bbox_to_anchor=[750, 525]) # zoom-factor: 2.5 tricontourf(eta0, levels=51, axes=axins, cmap='coolwarm') axins.axis(False) axins.set_xlim(xlim) axins.set_ylim(ylim) mark_inset(axes, axins, loc1=1, loc2=1, fc="none", ec="0.5") # Save fname = "dislocation_{:d}_{:s}".format(level, categories) if not loaded: fname += '_ig' savefig(fname, "plots", extensions=["jpg"], tight=False) # --- Setup tsunami propagation problem b = Function(P1).assign(op.set_bathymetry(P1)) g = Constant(op.g) dtc = Constant(op.dt) n = FacetNormal(mesh) u, eta = TrialFunctions(TaylorHood)
def test_fill_facecolor(): fig, ax = plt.subplots(1, 5) fig.set_size_inches(5, 5) for i in range(1, 4): ax[i].yaxis.set_visible(False) ax[4].yaxis.tick_right() bbox = Bbox.from_extents(0, 0.4, 1, 0.6) # fill with blue by setting 'fc' field bbox1 = TransformedBbox(bbox, ax[0].transData) bbox2 = TransformedBbox(bbox, ax[1].transData) # set color to BboxConnectorPatch p = BboxConnectorPatch(bbox1, bbox2, loc1a=1, loc2a=2, loc1b=4, loc2b=3, ec="r", fc="b") p.set_clip_on(False) ax[0].add_patch(p) # set color to marked area axins = zoomed_inset_axes(ax[0], 1, loc='upper right') axins.set_xlim(0, 0.2) axins.set_ylim(0, 0.2) plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) mark_inset(ax[0], axins, loc1=2, loc2=4, fc="b", ec="0.5") # fill with yellow by setting 'facecolor' field bbox3 = TransformedBbox(bbox, ax[1].transData) bbox4 = TransformedBbox(bbox, ax[2].transData) # set color to BboxConnectorPatch p = BboxConnectorPatch(bbox3, bbox4, loc1a=1, loc2a=2, loc1b=4, loc2b=3, ec="r", facecolor="y") p.set_clip_on(False) ax[1].add_patch(p) # set color to marked area axins = zoomed_inset_axes(ax[1], 1, loc='upper right') axins.set_xlim(0, 0.2) axins.set_ylim(0, 0.2) plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) mark_inset(ax[1], axins, loc1=2, loc2=4, facecolor="y", ec="0.5") # fill with green by setting 'color' field bbox5 = TransformedBbox(bbox, ax[2].transData) bbox6 = TransformedBbox(bbox, ax[3].transData) # set color to BboxConnectorPatch p = BboxConnectorPatch(bbox5, bbox6, loc1a=1, loc2a=2, loc1b=4, loc2b=3, ec="r", color="g") p.set_clip_on(False) ax[2].add_patch(p) # set color to marked area axins = zoomed_inset_axes(ax[2], 1, loc='upper right') axins.set_xlim(0, 0.2) axins.set_ylim(0, 0.2) plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) mark_inset(ax[2], axins, loc1=2, loc2=4, color="g", ec="0.5") # fill with green but color won't show if set fill to False bbox7 = TransformedBbox(bbox, ax[3].transData) bbox8 = TransformedBbox(bbox, ax[4].transData) # BboxConnectorPatch won't show green p = BboxConnectorPatch(bbox7, bbox8, loc1a=1, loc2a=2, loc1b=4, loc2b=3, ec="r", fc="g", fill=False) p.set_clip_on(False) ax[3].add_patch(p) # marked area won't show green axins = zoomed_inset_axes(ax[3], 1, loc='upper right') axins.set_xlim(0, 0.2) axins.set_ylim(0, 0.2) axins.get_xaxis().set_ticks([]) axins.get_yaxis().set_ticks([]) mark_inset(ax[3], axins, loc1=2, loc2=4, fc="g", ec="0.5", fill=False)
def color_edges(net, inset={}, path=None): fig = plt.figure(figsize=(35, 30), dpi=72) ax = fig.add_subplot(111) # Draw nodes DrawNodes(net, ax, label=['S', 'T', 'R', 'H'], color='black', size=2.0) # Draw edges d = { 'edges': net.edges(), 'geometry': [net[e[0]][e[1]]['geometry'] for e in net.edges()], 'flows': [net[e[0]][e[1]]['flow'] for e in net.edges()] } df_edges = gpd.GeoDataFrame(d, crs="EPSG:4326") fmin = np.log(0.2) fmax = np.log(800.0) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.001) df_edges.plot(column='flows', ax=ax, cmap=cm.plasma, vmin=fmin, vmax=fmax, cax=cax, legend=True) cax.set_ylabel('Flow along edge in kVA', size=30) labels = [100, 200, 300, 400, 500, 600, 700, 800] cax.set_yticklabels(labels) cax.tick_params(labelsize=20) ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) # Inset figures for sub in inset: axins = zoomed_inset_axes(ax, inset[sub]['zoom'], loc=inset[sub]['loc']) axins.set_aspect(1.3) # Draw nodes and edges DrawNodes(inset[sub]['graph'], axins, label=['S', 'T', 'R', 'H'], color='black', size=2.0) d = {'edges':inset[sub]['graph'].edges(), 'geometry':[inset[sub]['graph'][e[0]][e[1]]['geometry'] \ for e in inset[sub]['graph'].edges()], 'flows':[np.exp(inset[sub]['graph'][e[0]][e[1]]['flow']) \ for e in inset[sub]['graph'].edges()]} df_edges = gpd.GeoDataFrame(d, crs="EPSG:4326") df_edges.plot(column='flows', ax=axins, cmap=cm.plasma) axins.tick_params(bottom=False, left=False, labelleft=False, labelbottom=False) mark_inset(ax, axins, loc1=inset[sub]['loc1'], loc2=inset[sub]['loc2'], fc="none", ec="0.5") if path != None: fig.savefig("{}{}.png".format(path, '-dist-flows'), bbox_inches='tight') return
def cluster_membership(catalogfile, velcut, magcut, outdir, N_gauss, prob, rotate=True): """ Calculates cluster membership probabilities for each star given the population parameters in parameter file (from plot_posteriors_1D). Assumes parameter file will be found in <outdir>/plots/pop_parameters.txt Assumes catalogfile is untrimmed velcut: velocity error cut (mas/yr) magcut: phot error cut (mag) N_gauss: number of gaussians Identifies stars with a cluster membership probability GREATER THAN prob as high-prob members Produces new catalog cluster.fits which only contains cluster members. THIS HAS POSITIONS/PMs IN PIXELS. Membership probabilities are added in last column. Also makes new catalog *_prob_#.fits which is the original catalog with the cluster probabilities added on. This is the catalog we will work with extensively in the analysis Plots: Membership histogram, Spatial/velocity distributions of high-prob members Assumes gaussian 1 is the cluster gaussian If rotate = True, rotates velocities to RA/DEC to calculate membership probs. NOT COMPATABLE WITH MAKING VPD!!! """ # Extract catalog data d = loadData(catalogfile, velcut, magcut, rotate=rotate) star_xpos_pix = d["x_2010_F160W"] star_ypos_pix = d["y_2010_F160W"] star_Vx = d["fit_vx"] star_Vy = d["fit_vy"] star_Sigx = d["fit_vxe"] star_Sigy = d["fit_vye"] # Transform velocities into reference frame of the cluster # Using velocity determined from UPDATED doit.py: # star_Vx -= cluster_Vx_doit # star_Vy -= cluster_Vy_doit # Extract the necessary parameters from the parameter file params = Table.read(outdir + "/plots/pop_parameters.txt", format="ascii") pscale = astrometry.scale["WFC"] * 1e3 pi_fit = np.zeros(N_gauss, dtype=float) vx_fit = np.zeros(N_gauss, dtype=float) vy_fit = np.zeros(N_gauss, dtype=float) sigA_fit = np.zeros(N_gauss, dtype=float) sigB_fit = np.zeros(N_gauss, dtype=float) theta_fit = np.zeros(N_gauss, dtype=float) for kk in range(N_gauss): # Extract the necessary parameters from the parameter file pname = params["Param"] pi_idx = np.where(pname == ("pi_" + str(kk)))[0] vx_idx = np.where(pname == ("vx_" + str(kk)))[0] vy_idx = np.where(pname == ("vy_" + str(kk)))[0] sigA_idx = np.where(pname == ("sigA_" + str(kk)))[0] sigB_idx = np.where(pname == ("sigB_" + str(kk)))[0] theta_idx = np.where(pname == ("theta_" + str(kk)))[0] pi_fit[kk] = params["Mu"][pi_idx][0] vx_fit[kk] = params["Mu"][vx_idx][0] vy_fit[kk] = params["Mu"][vy_idx][0] sigA_fit[kk] = params["Mu"][sigA_idx][0] sigB_fit[kk] = params["Mu"][sigB_idx][0] theta_fit[kk] = params["Mu"][theta_idx][0] # Calculate cluster membership probability assuming # 1st gaussian is the cluster. prob_all = np.zeros((N_gauss, len(d)), dtype=float) for kk in range(N_gauss): prob_all[kk, :] = prob_ellipse( star_Vx, star_Vy, star_Sigx, star_Sigy, pi_fit[kk], vx_fit[kk], vy_fit[kk], sigA_fit[kk], sigB_fit[kk], theta_fit[kk], ) # Calculate cluster membership probability p_cluster = prob_all[0, :] / prob_all.sum(axis=0) # Plot distribution of cluster membership probabilities xbins = np.arange(0, 1.01, 0.05) py.close("all") fig, ax = py.subplots(num=1) n, bins, patch = py.hist(p_cluster, bins=xbins) py.axis([0, 1, 0, 4000]) py.xlabel("Cluster Membership Probability") py.ylabel(r"N$_{stars}$") axins = inset_axes(ax, width="75%", height=3, loc=1) py.hist(p_cluster, bins=xbins) py.axvline(prob, color="red", linestyle="--", linewidth=2) axins.set_xlim(0.1, 1.0) axins.set_ylim(0, 800) mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") outfile = outdir + "/plots/membership_hist_rot.png" py.savefig(outfile) # Collect the stars where P(membership > prob) # Highlight these stars in VPD members_ind = np.array(np.where(bins >= prob)[0]) members_ind = members_ind[:-1] members = n[members_ind].sum() print "Number of cluster members: " + str(members) # Plot spatial and VPD positions of ID'ed cluster members memberID = np.where(p_cluster >= prob)[0] # Change positions into arcsecs from cluster center for plotting purposes cl_x = star_xpos_pix[memberID].mean() cl_y = star_xpos_pix[memberID].mean() star_xpos_plot = (star_xpos_pix - cl_x) * pscale / 1e3 star_ypos_plot = (star_ypos_pix - cl_y) * pscale / 1e3 # --Now for spatial/velocity positions of high prob members---# outfile = outdir + "/plots/members_" + str(prob) + "_rot.png" py.close(2) py.figure(2, figsize=(12, 6)) py.clf() py.subplot(121) py.subplots_adjust(left=0.1) ax = py.gca() py.plot(star_xpos_plot, star_ypos_plot, "k.", ms=6, alpha=0.2) py.plot(star_xpos_plot[memberID], star_ypos_plot[memberID], "r.", ms=8, alpha=0.5) py.axis([125, -125, -125, 125]) py.xlabel("X Position Offset (arcsec)") py.ylabel("Y Position Offset (arcsec)") py.subplot(122) py.plot(star_Vx, star_Vy, "k.", ms=4, alpha=0.5) py.axis([6, -6, -6, 6]) py.xlabel(r"$\mu_{\alpha}$cos$\delta$ (mas yr$^{-1}$)") py.ylabel(r"$\mu_{\delta}$ (mas yr$^{-1}$)") py.plot(star_Vx[memberID], star_Vy[memberID], "r.", ms=4, alpha=0.3) # # Test orientation # # tmp1 = prob_all[2, :] / prob_all[2, :].sum() # sdx = tmp1.argsort() # tmp = tmp1[sdx].cumsum() # sig_lev_1 = tmp1[sdx[np.where(tmp > 0.01)[0][0]]] # sig_lev_2 = tmp1[sdx[np.where(tmp > 0.10)[0][0]]] # sig_lev_3 = tmp1[sdx[np.where(tmp > 0.50)[0][0]]] # f3 = np.where(tmp1 > sig_lev_1)[0] # f2 = np.where(tmp1 > sig_lev_2)[0] # f1 = np.where(tmp1 > sig_lev_3)[0] # py.plot(star_Vx[f3], star_Vy[f3], 'g.', ms=4, alpha=0.2) # py.plot(star_Vx[f2], star_Vy[f2], 'b.', ms=4, alpha=0.2) # py.plot(star_Vx[f1], star_Vy[f1], 'c.', ms=4, alpha=0.2) outfile = outdir + "/plots/membership_VPD_" + str(prob) + ".png" py.savefig(outfile) # Add column for membership probability in original cluster table d["Membership"] = p_cluster # HACK for BRITE cluster members. mag = d["m_2005_F814W"] color = d["m_2005_F814W"] - d["m_2013_F160W"] idx = np.where((mag < 18.8) & ((color > 3.1) & (color < 4.8)))[0] d["Membership"][idx] = 1.0 # Finally, make a new catalog with only cluster members outfile = "{0}/catalog_membership_{1}_rot.fits".format(outdir, N_gauss) print "Writing: ", outfile d.write(outfile, format="fits", overwrite=True) outfile = "{0}/catalog_cluster_only_{1}_{2:.1f}_rot.fits".format(outdir, N_gauss, prob) print "Writing: ", outfile d_clust = d[memberID] d_clust.write(outfile, format="fits", overwrite=True) return
plt.rcParams.update({'font.size': 16}) ret = plt.hist(log_returns, bins=100, density=True, color="dodgerblue", label="Empirical Distribution") xmin, xmax = plt.xlim() x = np.linspace(xmin, xmax, 100) p = norm.pdf(x, mu, std) plt.plot(x, p, 'k', linewidth=2, label="Gaussian Fit") plt.legend(loc=2) plt.title("IBEX-35 Log Returns Distribution") plt.xlabel("$R_{(t)}$") axins1 = zoomed_inset_axes(ax, zoom=5, loc=1) axins1.hist(log_returns, bins=100, density=True, color="dodgerblue", label="Fat Tails") axins1.plot(x, p, 'k') axins1.legend(loc=1) x1, x2, y1, y2 = 0.035, 0.060, 0.05, 2 axins1.set_xlim(x1, x2) axins1.set_ylim(y1, y2) plt.yticks(visible=False) mark_inset(ax, axins1, loc1=4, loc2=3, fc="none", ec="0.5") plt.savefig("gaussian_distributionibex.pdf")
ax2.plot(porcurve(pordepth, porfit), pordepth, 'k-', label='Curve fit', linewidth=3) ax3.plot(sedtemp(np.arange(concunique[-1,0]), bottom_temp), np.arange(concunique[-1,0]), 'k-', linewidth=3) ax4.plot(picks[:,1]/1000000, picks[:,0], 'ro', label='Picks') ax4.plot(sedtimes/1000000, seddepths, 'k-', label='Curve fit', linewidth=2) # Inset in concentration plot y2 = np.ceil(concunique[dp-1,0]) x2 = max(concunique[:dp,1])+2 x1 = min(concunique[:dp,1])-2 axins1 = inset_axes(ax1, width="50%", height="30%", loc=5) axins1.plot(concunique[:,1], concunique[:,0], 'go') axins1.plot(concunique[0:dp,1], concunique[0:dp,0], 'bo', label="Used for curve fit") axins1.plot(conc_interp_fit_plot, np.linspace(concunique[0,0], concunique[dp-1,0], num=50), 'k-') axins1.set_xlim(x1-1, x2+1) axins1.set_ylim(0, y2) mark_inset(ax1, axins1, loc1=1, loc2=2, fc="none", ec="0.5") # Additional formatting ax1.legend(loc='best', fontsize='small') ax2.legend(loc='best', fontsize='small') ax4.legend(loc='best', fontsize='small') ax1.set_ylabel('Depth (mbsf)') ax1.set_xlabel('Concentration (mM)') ax2.set_xlabel('Porosity') ax3.set_xlabel('Temperature (\u00b0C)') ax4.set_xlabel('Age (Ma)') ax1.locator_params(axis='x', nbins=4) ax2.locator_params(axis='x', nbins=4) ax3.locator_params(axis='x', nbins=4) ax4.locator_params(axis='x', nbins=4) axins1.locator_params(axis='x', nbins=3)
topp = 193 ax2 = plt.axes([ax2left, bott, ax2right - ax2left, topp]) ax2.xaxis.set_major_formatter(fmt) ax2.yaxis.set_major_formatter(fmt) ax2.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax2.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax2.set_xlim(left=ax2left, right=ax2right) ax2.set_ylim(bottom=bott, top=topp) # Manually set the position and relative size of the inset axes within ax1 ip = InsetPosition(ax1, [0.4, 0.1, 0.55, 0.4]) ax2.set_axes_locator(ip) # Mark the region corresponding to the inset axes on ax1 and draw lines # in grey linking the two axes. mark_inset(ax1, ax2, loc1=1, loc2=2, fc="none", ec='0.5') ax2.plot(1000 * ant, 1e6 * anr, label='Theoretical') plt.plot(vof2['t'], vof2['x'], label='VOF') plt.plot(vof4['t'], vof4['x'], label='VOF (2x ref.)') plt.plot(vof6['t'], vof6['x'], label='VOF (3x ref.)') ax2.legend(loc=4) ax2.set_yticks(np.arange(bott, topp, 4)) ax2.set_xticks(np.arange(ax2left, ax2right, 3)) #ax2.set_xticklabels(ax2.get_xticks(), backgroundcolor='w') leg = ax1.legend(loc=2, prop={'size': 17}) for line in leg.get_lines(): line.set_linewidth(3.0) for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label] + ax1.get_xticklabels() + ax1.get_yticklabels()):
def plotmustarsigma(self, outputid = 0, zoomperc = 0.05, loc = 2): ''' Plot the mu* vs sigma chart to interpret the combined effect of both. Parameters ----------- zoomperc : float (0-1) the percentage of the output range to show in the zoomplot, if 'none', no zoom plot is added loc : int matplotlib.pyplot.legend: location code (0-10) outputid : int the output to use whe multiple are compared; starts with 0 Returns --------- fig : matplotlib.figure.Figure object figure containing the output ax1 : axes.AxesSubplot object the subplot txtobjects : list of textobjects enbales the ad hoc replacement of labels when overlapping Notes ------- Visualization as proposed by [M2]_ ''' mustar2use = self.mustar[outputid*self._ndim:(outputid+1)*self._ndim] sigma2use = self.sigma[outputid*self._ndim:(outputid+1)*self._ndim] fig = plt.figure() ax1 = fig.add_subplot(111) axs, txtobjects = scatterwithtext(ax1, mustar2use, sigma2use, self._namelist, 'ks', markersize = 8) ax1.set_xlabel(r'$\mu^*$', fontsize=20) ax1.set_ylabel(r'$\sigma$', fontsize=20) ax1.grid() ax1.yaxis.grid(linestyle = '--', color = '0.75') ax1.xaxis.grid(linestyle = '--', color = '0.75') ax1.set_xlim((0.0, mustar2use.max()+mustar2use.max()*0.1)) ax1.set_ylim((0.0, sigma2use.max()+sigma2use.max()*0.1)) majloc1 = MaxNLocator(nbins=4, prune='lower') ax1.yaxis.set_major_locator(majloc1) majloc2 = MaxNLocator(nbins=4) ax1.xaxis.set_major_locator(majloc2) if zoomperc != 'none': #the zooming box size is ad hoc and can be improved axins = zoomed_inset_axes(ax1, np.floor(1./zoomperc/2.5), loc = loc) axins.plot(mustar2use, sigma2use, 'ks', markersize = 3) transOffset2 = offset_copy(axins.transData, fig=plt.gcf(), x = -0.05, y=0.10, units='inches') #plot in the subplot ct2=0 txtobjects2=[] for x, y in zip(mustar2use, sigma2use): if x < mustar2use.max()*zoomperc and y < sigma2use.max()*zoomperc: axins.plot((x,),(y,), 'ks', markersize = 3) ls = axins.text(x, y, '%s' %self._namelist[ct2], transform=transOffset2, color='k') txtobjects2.append(ls) ct2+=1 #zoomplot with labels right axins.yaxis.set_ticks_position('right') #set the limits of the zoom plot axins.set_xlim((0.0, mustar2use.max()*zoomperc)) axins.set_ylim((0.0, sigma2use.max()*zoomperc)) #only minor number of ticks for cleaner overview majloc3 = MaxNLocator(nbins=3, prune='lower') axins.yaxis.set_major_locator(majloc3) majloc4 = MaxNLocator(nbins=3, prune='lower') axins.xaxis.set_major_locator(majloc4) #smaller size for the ticklabels (different is actually not needed) for tickx in axins.xaxis.get_major_ticks(): tickx.label.set_fontsize(10) for label in axins.yaxis.get_majorticklabels(): label.set_fontsize(10) label.set_rotation('vertical') #create the subarea-plot in main frame and connect mark_inset(ax1, axins, loc1=2, loc2=4, fc='none', ec='0.8') axins.grid() axins.yaxis.grid(linestyle = '--', color = '0.85') axins.xaxis.grid(linestyle = '--', color = '0.85') return fig, ax1, txtobjects
def plot_accuracy(self, dataset, net_name, schemes, groups, cases, inset=True): """ Plots accuracy over training for different experimental cases. Args: dataset net_name schemes cases (list): Experimental cases to include in figure. Returns: None. """ # pull data acc_df = self.stats_processor.load_accuracy_df(dataset, net_name, schemes, cases) # process a bit acc_df = acc_df.query(f"group in {groups}") index_cols = ["dataset", "net_name", "train_scheme", "case", "epoch"] acc_df.set_index(index_cols, inplace=True) df_stats = acc_df.groupby(index_cols).agg( {"val_acc": [np.mean, np.std]}) # group df_groups = df_stats.groupby(index_cols[:-1]) # plot fig, ax = plt.subplots(figsize=(14, 8)) clrs = sns.color_palette("hls", len(df_groups.groups)) y_arr = [] yerr_arr = [] for group, clr in zip(df_groups.groups, clrs): d, n, s, c = group group_data = df_groups.get_group(group) # error bars = 2 standard devs yvals = group_data["val_acc"]["mean"].values * 100 yerr = group_data["val_acc"]["std"].values * 1.98 * 100 ax.plot(range(len(yvals)), yvals, label=f"{s} {c}", c=clr) ax.fill_between(range(len(yvals)), yvals - yerr, yvals + yerr, alpha=0.1, facecolor=clr) # for the insert... y_arr.append(yvals) yerr_arr.append(yerr) # zoomed inset if inset: axins = zoomed_inset_axes(ax, zoom=10, loc=8) for yvals, yerr, clr in zip(y_arr, yerr_arr, clrs): nlast = 10 x = [i for i in range(len(yvals) - nlast, len(yvals))] y_end = yvals[-nlast:] yerr_end = yerr[-nlast:] axins.plot(x, y_end, c=clr) axins.fill_between(x, y_end - yerr_end, y_end + yerr_end, alpha=0.1, facecolor=clr) mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") axins.xaxis.set_ticks([]) ax.set_title( f"Classification accuracy during training: {net_name} on {dataset}", fontsize=20) ax.set_xlabel("Epoch", fontsize=16) ax.set_ylabel("Validation accuracy (%)", fontsize=16) ax.set_ylim([0, 100]) ax.legend(fontsize=14) plt.tight_layout() # optional saving if not self.save_fig: print("Not saving.") plt.show() return sub_dir = ensure_sub_dir(self.data_dir, f"figures/accuracy/") case_names = ", ".join(cases) schemes = ", ".join(schemes) filename = f"{dataset}_{net_name}_{schemes}_{case_names} accuracy" filename = os.path.join(sub_dir, filename) print(f"Saving... {filename}") plt.savefig(f"{filename}.svg") plt.savefig(f"{filename}.png", dpi=300)
def test_fill_facecolor(): fig, ax = plt.subplots(1, 5) fig.set_size_inches(5, 5) for i in range(1, 4): ax[i].yaxis.set_visible(False) ax[4].yaxis.tick_right() bbox = Bbox.from_extents(0, 0.4, 1, 0.6) # fill with blue by setting 'fc' field bbox1 = TransformedBbox(bbox, ax[0].transData) bbox2 = TransformedBbox(bbox, ax[1].transData) # set color to BboxConnectorPatch p = BboxConnectorPatch( bbox1, bbox2, loc1a=1, loc2a=2, loc1b=4, loc2b=3, ec="r", fc="b") p.set_clip_on(False) ax[0].add_patch(p) # set color to marked area axins = zoomed_inset_axes(ax[0], 1, loc='upper right') axins.set_xlim(0, 0.2) axins.set_ylim(0, 0.2) plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) mark_inset(ax[0], axins, loc1=2, loc2=4, fc="b", ec="0.5") # fill with yellow by setting 'facecolor' field bbox3 = TransformedBbox(bbox, ax[1].transData) bbox4 = TransformedBbox(bbox, ax[2].transData) # set color to BboxConnectorPatch p = BboxConnectorPatch( bbox3, bbox4, loc1a=1, loc2a=2, loc1b=4, loc2b=3, ec="r", facecolor="y") p.set_clip_on(False) ax[1].add_patch(p) # set color to marked area axins = zoomed_inset_axes(ax[1], 1, loc='upper right') axins.set_xlim(0, 0.2) axins.set_ylim(0, 0.2) plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) mark_inset(ax[1], axins, loc1=2, loc2=4, facecolor="y", ec="0.5") # fill with green by setting 'color' field bbox5 = TransformedBbox(bbox, ax[2].transData) bbox6 = TransformedBbox(bbox, ax[3].transData) # set color to BboxConnectorPatch p = BboxConnectorPatch( bbox5, bbox6, loc1a=1, loc2a=2, loc1b=4, loc2b=3, ec="r", color="g") p.set_clip_on(False) ax[2].add_patch(p) # set color to marked area axins = zoomed_inset_axes(ax[2], 1, loc='upper right') axins.set_xlim(0, 0.2) axins.set_ylim(0, 0.2) plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) mark_inset(ax[2], axins, loc1=2, loc2=4, color="g", ec="0.5") # fill with green but color won't show if set fill to False bbox7 = TransformedBbox(bbox, ax[3].transData) bbox8 = TransformedBbox(bbox, ax[4].transData) # BboxConnectorPatch won't show green p = BboxConnectorPatch( bbox7, bbox8, loc1a=1, loc2a=2, loc1b=4, loc2b=3, ec="r", fc="g", fill=False) p.set_clip_on(False) ax[3].add_patch(p) # marked area won't show green axins = zoomed_inset_axes(ax[3], 1, loc='upper right') axins.set_xlim(0, 0.2) axins.set_ylim(0, 0.2) axins.get_xaxis().set_ticks([]) axins.get_yaxis().set_ticks([]) mark_inset(ax[3], axins, loc1=2, loc2=4, fc="g", ec="0.5", fill=False)
if matched: axins = zoomed_inset_axes(ax, 5.5, loc=9) axins.plot((np.arange(range_domain[0], range_domain[1]) - EFFECTIVE_LENGTH // 2) * 0.375 / 1000, rd_db4[::-1, slice_velocity], label='with compensation') axins.plot((np.arange(range_domain[0], range_domain[1]) - EFFECTIVE_LENGTH // 2) * 0.375 / 1000, dd_db3[::-1, slice_velocity], label='without compensation') axins.set_xlim([4.115, 4.135]) axins.set_ylim([69.5, 72.75]) axins.grid(ls=':') plt.xticks(visible=False) # axins.yaxis.tick_right() mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") axins = zoomed_inset_axes(ax, 2.5, loc='upper left') axins.plot( (np.arange(range_domain[0], range_domain[1]) - EFFECTIVE_LENGTH // 2) * 0.375 / 1000, rd_db4[::-1, slice_velocity], label='with compensation') axins.plot( (np.arange(range_domain[0], range_domain[1]) - EFFECTIVE_LENGTH // 2) * 0.375 / 1000, dd_db3[::-1, slice_velocity], label='without compensation') axins.set_xlim([3.56, 3.68]) axins.set_ylim([43.5, 51]) axins.grid(ls=':')
main_axes = grid[0] main_axes.locator_params(nbins=5) cb_axes = grid.cbar_axes[0] # colorbar axes im = main_axes.imshow(d, origin="lower", cmap=plt.cm.gray_r, vmin=4.e-05, vmax=0.00018, interpolation="nearest") cb_axes.colorbar(im) cb_axes.axis["right"].toggle(ticklabels=False) axins = zoomed_inset_axes(main_axes, zoom=3, loc=1, axes_class=pywcsgrid2.Axes, axes_kwargs=dict(wcs=h)) im2 = axins.imshow(d, origin="lower", interpolation="nearest", vmin=9.e-05, vmax=18.e-05, cmap=plt.cm.gray_r) axins.set_xlim(120, 160) axins.set_ylim(120, 160) axins.set_ticklabel_type("delta") axins.axis[:].invert_ticklabel_direction() mark_inset(main_axes, axins, loc1=2, loc2=4, fc="none", ec="0.5") plt.show()
fontsize=18, va='center', ha='center', clip_on=False) # INSET VIP MAP axins = zoomed_inset_axes(ax1, 9.2, loc=1, borderpad=.06) axins.set_xlim(lons2[0], lons2[1]) axins.set_ylim(lats2[0], lats2[1]) m2 = Basemap(llcrnrlon=lons2[0], llcrnrlat=lats2[0], urcrnrlon=lons2[1], urcrnrlat=lats2[1], resolution='f') m2.drawmapboundary(fill_color='azure', linewidth=2.0) m2.pcolormesh(lons, lats, DHW_max, vmin=0, vmax=16, cmap=dhw_noaa, latlon=True) polygon_patch(m2, axins) axins.plot(121, 14.5, 'D', ms=8, mfc=dhw_noaa.colors[9, :], mec='k') axins.text(121.09, 14.5, 'Manila', style='italic', fontsize=11, va='center') axins.text(121.08, 13.1, 'Mindoro', fontsize=14, ha='center', va='center') axins.text(121.2, 14.08, 'Luzon', fontsize=14, ha='center', va='center') mark_inset(ax1, axins, loc1=2, loc2=3, fc="none", ec="0", lw=2) plt_box(axins) plt.savefig('Fig1_Max_DHW_98.png') plt.show()
ax_n = plt.axes( [0.13, 0.275, 0.135, 0.45]) Qh_n = hf_n[:,4]/(-2 * hfi_n[:,4]) X_n = hf_n[:,1] Y_n = hf_n[:,2] Qh_n = np.rot90(np.resize(Qh_n, ( np.size(np.unique(X_n)), np.size(np.unique(Y_n))))) ax_n.set_yticks([]) ax_n.set_xticks([]) Data = np.log10(Qh_n) ax_n.imshow(Data, vmin=4, vmax=7, extent=[np.min(X_n),np.max(X_n),np.min(Y_n),np.max(Y_n)], interpolation='none') #ax.imshow(Data, vmin=0, vmax=10, extent=[np.min(X_n),np.max(X_n),np.min(Y_n),np.max(Y_n)]) mark_inset(ax, ax_n, loc1=1, loc2=4, fc='none', ec='1') ax_n.set_xlim([-0.06, -0.03]) ax_n.set_ylim([-0.03, 0.03]) #for i in range(len(pol[:,0])): # drawEllipse(pol[i,0],pol[i,1], pol[i,2], pol[i,3], 0.001, ax_n) ax_p = plt.axes([0.72, 0.275, 0.135, 0.45]) Qh_p = hf_p[:,4]/(-2 * hfi_p[:,4]) X_p = hf_p[:,1] Y_p = hf_p[:,2] E_p = hf_p[:,4] Qh_p = np.rot90(np.resize(Qh_p, ( np.size(np.unique(X_p)), np.size(np.unique(Y_p)))))
def plotProjection(kind, index, boxsize=1.): #index is which SIGO it is, ihalo refers to the numbering in halo100_indices ihalo = SIGOidx[index] print ihalo path = prefix + run + '/output/GasOnly_FOF/' s = gadget_readsnap(snap, snapbase='snap-groupordered_', snappath=path, hdf5=True, loadonly=['pos', 'vel', 'mass', 'vol', 'rho', 'u'], loadonlytype=[0], forcesingleprec=False) cms = cat_118kms.GroupPos cms = cms / (s.hubbleparam / s.time) cvel = cat_118kms.GroupVel cvel = cvel / s.time pxsize = 6. pysize = 6. psize = 2. offsetx = 1.1 offsety = .4 offset = .33 fig = pylab.figure(figsize=(np.array([pxsize, pysize]) * toinch), dpi=300) res = 256 #res = 128 #boxsize = .5 # 10kpc fact = 0.5 # projection length will be 2.0 * fact * boxsize iplot = 0 ix = iplot % 4 x = ix * (2. * psize + offsetx) / pxsize + offsetx / pysize y = offsety / pysize y = (2. * offsety) / pysize ax1 = axes([x, y, 2. * psize / pxsize, 2. * psize / pysize], frameon=True) y = (2. * psize + 3. * offset) / pysize + 0.15 * psize / pysize cax = axes([x, y, 2. * psize / pxsize, psize / pysize / 15.], frameon=False) s.pos = s.pos - cms[ihalo] s.vel = s.vel - cvel[ihalo] #convert to kpc igas, = np.where((np.abs(s.pos[:, 0]) < boxsize) & (np.abs(s.pos[:, 1]) < boxsize) & (np.abs(s.pos[:, 2]) < boxsize)) npart = len(igas) print "Gas density plot selected particles in box", len(igas) # this conversion seems strange but basically rho is first converted to 10 Msun / kpc^3 by # multiplying by then and then in cm^-2 with all the other factors (this holds also for the # other projection functions). The factor boxsize / res is the dl of the projection #ne = s.data['ne'][:] #metallicity = 0 #XH = s.data['gmet'][:, 0] #yhelium = (1 - XH - metallicity) / (4. * XH); #mu = (1 + 4 * yhelium) / (1 + yhelium + ne) mu = 1.22 #neutral primordial gas s.data['pos'] = s.pos[igas] s.data['type'] = s.type[igas] #s.data['rho'] = s.rho[igas].astype('float64') * 1.0e10 * MSUN / KPC**2.0 / mu / PROTONMASS * boxsize / res #put in 1/cm^2 s.data['rho'] = s.rho[igas].astype( 'float64') * 1.0e10 * MSUN / KPC**2.0 * boxsize / res #put in g/cm^2 s.data['vol'] = s.vol[igas] s.data['mass'] = s.mass[igas] #convert internal energy to temperature u = 1.0e10 * s.data['u'][ igas] #it's a velocity squared to be converted in cgs #turn into temp temp = GAMMA_MINUS1 / BOLTZMANN * u * PROTONMASS * mu if kind == "TEMP": s.data['u'] = temp #turn into sound speed cs = np.sqrt(GAMMA * BOLTZMANN * temp / mu / PROTONMASS) if kind == "CS": s.data['u'] = cs / 1.0e5 #convert to km/s s.data['vel'] = s.vel[igas] * 1.0e5 #convert to cgs #Turn first v_x into |v| velmag = np.linalg.norm(s.vel, axis=1) if kind == "VEL": s.data['u'] = velmag / 1.0e5 #convert to km/s mach = velmag / cs if kind == "MACH": s.data['u'] = mach if kind == "RHOC": rhocrit = gp['rhocritSIGO'][index] s.data['rho'] = s.rho / (rhocrit * boxsize / res * KPC) if kind == "RHO": s.data['rho'] = s.rho / mu / PROTONMASS # in 1/cm^2 if kind == "OVER": critical_density = 3.0 * .1 * .1 / 8.0 / np.pi / GCONST #.1 is to convert 100/Mpc to 1/kpc, this is in units of h^2 Omega0 = s.omega0 OmegaLambda = s.omegalambda atime = s.time critical_density *= Omega0 + atime**3 * OmegaLambda critical_density_gas = critical_density * baryonfraction critical_density_gas *= hubbleparam**2 / atime**3 * 1.0e10 * MSUN / KPC**2.0 * boxsize / res # in units of g/cm^2 s.data['rho'] = s.rho / critical_density_gas - 1. axes(ax1) dextoshow = 6 numthreads = 4 #Plot mass weighted slice #temperature if kind == "TEMP": s.plot_Aweightedslice("u", "mass", colorbar=False, res=res, proj=True, axes=[0, 1], box=[boxsize, boxsize], center=np.array([0., 0., 0.]), proj_fact=fact, logplot=True, rasterized=True, minimum=1.0, newfig=False, cmap='inferno', numthreads=8, vrange=[100, 10000]) #mach if kind == "MACH": s.plot_Aweightedslice("u", "mass", colorbar=False, res=res, proj=True, axes=[0, 1], box=[boxsize, boxsize], center=np.array([0., 0., 0.]), proj_fact=fact, logplot=True, rasterized=True, newfig=False, cmap='inferno', numthreads=8, vrange=[0.0001, 20]) if kind == "CS": s.plot_Aweightedslice("u", "mass", colorbar=False, res=res, proj=True, axes=[0, 1], box=[boxsize, boxsize], center=np.array([0., 0., 0.]), proj_fact=fact, logplot=True, rasterized=True, minimum=1.0, newfig=False, cmap='inferno', numthreads=8, vrange=[1, 50]) if kind == "VEL": s.plot_Aweightedslice("u", "mass", colorbar=False, res=res, proj=True, axes=[0, 1], box=[boxsize, boxsize], center=np.array([0., 0., 0.]), proj_fact=fact, logplot=True, rasterized=True, minimum=1.0, newfig=False, cmap='inferno', numthreads=8, vrange=[1, 50]) if kind == "RHOC": s.plot_Aweightedslice("rho", "mass", colorbar=False, res=res, proj=True, axes=[0, 1], box=[boxsize, boxsize], center=np.array([0., 0., 0.]), proj_fact=fact, logplot=True, rasterized=True, newfig=False, cmap='Spectral', numthreads=8, vrange=[1, 40]) #s.plot_Aweightedslice( "rho", "mass", colorbar=False, res=res, proj=True,axes=[0,1], box=[boxsize,boxsize], center=np.array([0.,0.,0.]), proj_fact=fact,logplot=True, rasterized=True, newfig=False, cmap='Spectral',numthreads=8,minimum=.7) if kind == "RHO": s.plot_Aweightedslice("rho", "mass", colorbar=False, res=res, proj=True, axes=[0, 1], box=[boxsize, boxsize], center=np.array([0., 0., 0.]), proj_fact=fact, logplot=True, rasterized=True, newfig=False, cmap='Spectral', numthreads=8, vrange=[1e17, 1e19]) #Make velocity field denom = np.sqrt((s.data['vel'][:, :2]**2).sum(axis=1)) vnorm = s.data['vel'] / denom[:, None] vmax = np.max(denom) vmin = np.min(denom) vnorm *= (denom[:, None] - vmin) / (vmax - vmin) ngbs = s.get_Aslice('rho', box=[boxsize, boxsize], axes=[0, 1], center=np.array([0., 0., 0.]), proj=False, proj_fact=fact, res=res)["neighbours"] ax1.quiver(s.pos[ngbs[:, :], 0], s.pos[ngbs[:, :], 1], vnorm[ngbs[:, :], 0], vnorm[ngbs[:, :], 1], scale_units='inches', scale=5., pivot='middle', width=0.002, edgecolors=(''), color='lightgray') #Make inset of SIGO axins = zoomed_inset_axes(ax1, 2, loc=1) axes(axins) s.plot_Aweightedslice("rho", "mass", colorbar=False, res=res, proj=True, axes=[0, 1], box=[boxsize, boxsize], center=np.array([0., 0., 0.]), proj_fact=fact, logplot=True, rasterized=True, newfig=False, cmap='Spectral', numthreads=8, vrange=[1e17, 1e19]) x1, x2, y1, y2 = -0.2, 0.2, -0.2, 0.2 axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) mark_inset(ax1, axins, loc1=2, loc2=4, fc="none", ec="0.5") plt.tick_params(axis='both', which='both', bottom=False, left=False, top=False, labelbottom=False, labelleft=False) axes(ax1) if kind == "OVER": s.plot_Aweightedslice("rho", "mass", colorbar=False, res=res, proj=True, axes=[0, 1], box=[boxsize, boxsize], center=np.array([0., 0., 0.]), proj_fact=fact, logplot=True, rasterized=True, minimum=1.0, newfig=False, cmap='Spectral', numthreads=8, vrange=[1e-1, 1e2]) #Make inset of SIGO axins = zoomed_inset_axes(ax1, 2, loc=1) axes(axins) s.plot_Aweightedslice("rho", "mass", colorbar=False, res=res, proj=True, axes=[0, 1], box=[boxsize, boxsize], center=np.array([0., 0., 0.]), proj_fact=fact, logplot=True, rasterized=True, newfig=False, cmap='Spectral', numthreads=8, vrange=[1e-1, 1e2]) x1, x2, y1, y2 = -0.2, 0.2, -0.2, 0.2 axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) mark_inset(ax1, axins, loc1=2, loc2=4, fc="none", ec="0.5") plt.tick_params(axis='both', which='both', bottom=False, left=False, top=False, labelbottom=False, labelleft=False) axes(ax1) #colorbar( cax=cax, orientation='horizontal') colorbar(cax=cax, orientation='horizontal', format=matplotlib.ticker.LogFormatterMathtext()) if kind == "TEMP": cax.set_title('$Temperature\\rm{\\,[K]}}$', size=8) if kind == "MACH": cax.set_title('$Mach$', size=8) if kind == "VEL": cax.set_title('$Vel\\rm{\\,[km/s]}}$', size=8) if kind == "CS": cax.set_title('$cs\\rm{\\,[km/s]}}$', size=8) if kind == "RHOC": cax.set_title('$\\rho/\\rho_{\\rm crit}$', size=8) if kind == "RHO": cax.set_title('$N\\rm{\\,[cm^{-2}]}$', size=8) if kind == "OVER": cax.set_title('$\\delta$', size=8) for label in cax.xaxis.get_ticklabels(): label.set_fontsize(8) #******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* for label in cax.xaxis.get_ticklabels(): label.set_fontsize(6) for label in ax1.xaxis.get_ticklabels(): label.set_fontsize(6) for label in ax1.yaxis.get_ticklabels(): label.set_fontsize(6) majorLocator = MultipleLocator(1.0) minorLocator = MultipleLocator(0.5) ax1.xaxis.set_major_locator(majorLocator) ax1.yaxis.set_major_locator(majorLocator) ax1.xaxis.set_minor_locator(minorLocator) ax1.yaxis.set_minor_locator(minorLocator) ax1.set_xlabel("$\\rm{x\\,[kpc]}$", size=7) ax1.set_ylabel("$\\rm{y\\,[kpc]}$", size=7) ax1.xaxis.labelpad = -0.25 ax1.yaxis.labelpad = -1 if kind == "TEMP": fig.savefig(jobdir + 'Temp_%s_%s_Cooling.pdf' % (name, str(ihalo)), transparent=True, dpi=300) if kind == "MACH": fig.savefig(jobdir + 'Mach_%s_%s_Cooling.pdf' % (name, str(ihalo)), transparent=True, dpi=300) if kind == "VEL": fig.savefig(jobdir + 'velnorm_%s_%s_Cooling.pdf' % (name, str(ihalo)), transparent=True, dpi=300) if kind == "CS": fig.savefig(jobdir + 'cs_%s_%s_Cooling.pdf' % (name, str(ihalo)), transparent=True, dpi=300) if kind == "RHOC": fig.savefig(jobdir + 'Rhocrit_%s_%s_Cooling.pdf' % (name, str(ihalo)), transparent=True, dpi=300) if kind == "RHO": fig.savefig(jobdir + 'Rho_%s_%s_Cooling.pdf' % (name, str(ihalo)), transparent=True, dpi=300) if kind == "OVER": fig.savefig(jobdir + 'Over_%s_%s_Cooling.pdf' % (name, str(ihalo)), transparent=True, dpi=300)