def plot_projection_check(gene: str, data_norm: Dict[str, pd.DataFrame], angles: np.ndarray, widths: np.ndarray, first_points_dict: Dict[str, int], mask: np.ndarray) -> None: D, projs_len = build_Design_Matrix(angles, widths, mask) boundaries = np.r_[0, np.cumsum(projs_len)] gs = plt.GridSpec(2, 6) imgs = [] for i, (name_angle, df_angle) in enumerate(data_norm.items()): projected_total = D.dot(mask.flat[:])[boundaries[i]:boundaries[i + 1]] x = get_x(data_norm[name_angle]).astype(int) y = data_norm[name_angle].ix[gene] x, y, not_provided = mixed_interpolator2(x, y) c = np.array(["g"] * len(x)) c[~not_provided] = np.array(["g", "r", "b", "y"])[get_plate(data_norm[name_angle])] # Set the plot ax = plt.subplot(gs[0, i + 1]) # Plot points ax.scatter(x, y, c=c, marker=".", lw=0, s=50) ax.plot(x, y, alpha=0.2, c="gray") scaling = np.percentile(y, 95) / projected_total.max() # Plot expected projection ax.plot(np.arange(projected_total.shape[0]) + first_points_dict[name_angle], projected_total * scaling, c="k", lw=1.2, alpha=0.5, zorder=1000) # Fix graphics ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax.set_title("%s" % name_angle) ax.set_xlim(-5, get_x(df_angle)[-1] + 5) ax.set_ylim(-0.2,) # Set the plot ax = plt.subplot(gs[1, i + 1]) # Identify the part of the Design matrix containing the strips relative to one angle s, e = boundaries[i], boundaries[i + 1] part_D = D[s:e] # identify the detected level of expression to multiply to the corresponding strips detected_at_slice = np.zeros(part_D.shape[0]) ix_detected = np.in1d(x - int(first_points_dict[name_angle]), np.arange(e - s)) # take care of the case where x has gaps ix_reference = (x - int(first_points_dict[name_angle]))[ix_detected] detected_at_slice[ix_reference] = y[ix_detected] # Perform the multiplication desigm_matrix@angle * level_expression@angle, then sum pixelwise and reshape as an image img0 = (0.5 * part_D * detected_at_slice[:, None]).sum(0).reshape(mask.shape) imgs.append(img0) ax.imshow(10 * img0 / img0.sum(), cmap="viridis", norm=PowerNorm(0.5)) # vmin=np.percentile(img0, 2), vmax=np.percentile(img0, 98), cmap="gray") # Plot the product of all the images in lognormalized colormap ax = plt.subplot(gs[0:2, 0]) res_img = np.ones_like(imgs[0]) for img in imgs: res_img *= img + 1e-5 ax.set_title(gene) ax.imshow(10 * res_img / res_img.sum(), cmap="viridis", norm=PowerNorm(0.25)) plt.tight_layout()
def __init__(self, fig, gs, ray_list, user_scale_value=0.1, scale_type='fit', yaxis_ticks_position='left', dsp_typ='hist2d', **kwargs): self.fig = fig self.fig.subplots.append(self) self.gs = gs self.ray_list = ray_list self.dsp_typ = dsp_typ if 'title' in kwargs: self.title = kwargs.pop('title', None) if 'norm' in kwargs: self.norm = kwargs.pop('norm', None) else: gamma = kwargs.pop('gamma', 0.5) vmax = kwargs.get('vmax') if 'vmax' in kwargs else None self.norm = PowerNorm(gamma, vmin=0., vmax=vmax) self.plot_kwargs = kwargs self.user_scale_value = user_scale_value self.scale_type = scale_type self.yaxis_ticks_position = yaxis_ticks_position self.update_data()
def plot_density(spn, data): import matplotlib.pyplot as plt import numpy as np x_max = data[:, 0].max() x_min = data[:, 0].min() y_max = data[:, 1].max() y_min = data[:, 1].min() nbinsx = int(x_max - x_min) / 1 nbinsy = int(y_max - y_min) / 1 xi, yi = np.mgrid[x_min:x_max:nbinsx * 1j, y_min:y_max:nbinsy * 1j] spn_input = np.vstack([xi.flatten(), yi.flatten()]).T marg_spn = marginalize(spn, set([0, 1])) zill = likelihood(marg_spn, spn_input) z = zill.reshape(xi.shape) # Make the plot # plt.pcolormesh(xi, yi, z) plt.imshow(z + 1, extent=(x_min, x_max, y_min, y_max), cmap=cm.hot, norm=PowerNorm(gamma=1. / 5.)) # plt.pcolormesh(xi, yi, z) plt.colorbar() plt.show()
def test_plot_topomap_cnorm(): """Test colormap normalization.""" if check_version("matplotlib", "3.2.0"): from matplotlib.colors import TwoSlopeNorm else: from matplotlib.colors import DivergingNorm as TwoSlopeNorm from matplotlib.colors import PowerNorm rng = np.random.default_rng(42) v = rng.uniform(low=-1, high=2.5, size=64) v[:3] = [-1, 0, 2.5] montage = make_standard_montage("biosemi64") info = create_info(montage.ch_names, 256, "eeg").set_montage("biosemi64") cnorm = TwoSlopeNorm(vmin=-1, vcenter=0, vmax=2.5) # pass only cnorm, no vmin/vmax plot_topomap(v, info, cnorm=cnorm) # pass cnorm and vmin msg = "vmin=-1.* is implicitly defined by cnorm, ignoring vmin=-10.*" with pytest.warns(RuntimeWarning, match=msg): plot_topomap(v, info, vmin=-10, cnorm=cnorm) # pass cnorm and vmax msg = "vmax=2.5 is implicitly defined by cnorm, ignoring vmax=10.*" with pytest.warns(RuntimeWarning, match=msg): plot_topomap(v, info, vmax=10, cnorm=cnorm) # try another subclass of mpl.colors.Normalize plot_topomap(v, info, cnorm=PowerNorm(0.5))
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) # change 'figure_width': 1920, 'figure_height': 1080 =(19.2,10.8) f = Figure(figsize=(8, 6)) a = f.add_subplot(111) f.subplots_adjust(left=None, bottom=None, right=1, top=1) hdu_list = fits.open(sky_image) hdu_list.info() img = hdu_list[0].data normalise = PowerNorm(gamma=power_normalise) a.imshow(img, origin='lower', cmap='gray', norm=normalise, vmax=max_saturation) # Embedding In Tk canvas = FigureCanvasTkAgg(f, self) canvas.draw() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) # Show ToolBar toolbar = NavigationToolbar2Tk(canvas, self) toolbar.update() # Activate Zoom toolbar.zoom(self) canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) hdu_list.close()
def plot(self, ax=None): """ Replot the data applying the currently selected postporcessings. """ # Reset to original data and generate a 2D slice from it self.data = self.original_data.copy() self.X = self.original_X.copy() self.Y = self.original_Y.copy() + self.y_shift if self.original_Z is not None: self.Z = self.original_Z.copy( ) # Not used here directly, but useful to do self.apply_cropping() self.sliced = pp.make_map(self.data, self.z, self.integrate) # Postprocessing self.apply_kspace_conversion() self.apply_normalization() self.apply_bg_subtraction() self.apply_derivative() if ax is None: ax = self.ax # Plot # NOTE ax.clear() sadly removes the cursor and polygon. But not # having it is a memory leak. Solution? ax.clear() vmax = max(self.sliced.min(), self.vmax * self.sliced.max()) self.mesh = ax.pcolormesh(self.X, self.Y, self.sliced, vmax=vmax, cmap=self.cmap, zorder=-9, norm=PowerNorm(gamma=self.gamma)) # Matplotlib stuff self.apply_plot_formatting()
def get_norm(self): """ This will create a matplotlib.colors.Normalize from selected idx, limits and powerscale """ idx = self.norm.currentIndex() if self.autoscale.isChecked(): cmin = cmax = None else: cmin = self.cmin_value cmax = self.cmax_value if NORM_OPTS[idx] == 'Power': if self.powerscale.hasAcceptableInput(): self.powerscale_value = float(self.powerscale.text()) return PowerNorm(gamma=self.powerscale_value, vmin=cmin, vmax=cmax) elif NORM_OPTS[idx] == "SymmetricLog10": return SymLogNorm( 1e-8 if cmin is None else max(1e-8, abs(cmin) * 1e-3), vmin=cmin, vmax=cmax) elif NORM_OPTS[idx] == "Log": cmin = MIN_LOG_VALUE if cmin is not None and cmin <= 0 else cmin return LogNorm(vmin=cmin, vmax=cmax) else: return Normalize(vmin=cmin, vmax=cmax)
def plotDensityMap(image, x, y, radius, pmem=0.5, title='Density Map', savename='./density_map.png'): """It generates density maps """ # radius = (np.max(x)+np.max(y))/21 ticks = [-radius, -radius / 2, 0, radius / 2, radius] # extent=(x.min(),x.max(),y.min(),y.max()) extent = [-radius, radius, -radius, radius] plt.clf() plt.title(title) plt.xlabel(r'$\Delta X $ [Mpc]') plt.ylabel(r'$\Delta Y $ [Mpc]') # plt.scatter(x,-y,c='white',s=10*(pmem)**2,alpha=0.7) # plt.scatter(x,y,c='white',s=10*(pmem)**2,alpha=0.7) plt.imshow(image, extent=extent, origin='lower', cmap=cm.inferno, norm=PowerNorm(gamma=1 / 2), interpolation='nearest') # plt.imshow(image,extent=extent,cmap=cm.inferno) plt.xticks(ticks) plt.yticks(ticks) plt.colorbar() plt.savefig(savename)
def plot_matrix(self, ax=None, show_energy=None, **kwargs): """Plot PDF matrix Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis show_energy : `~astropy.units.Quantity`, optional Show energy, e.g. threshold, as vertical line """ import matplotlib.pyplot as plt from matplotlib.colors import PowerNorm kwargs.setdefault('cmap', 'afmhot') kwargs.setdefault('origin', 'bottom') kwargs.setdefault('interpolation', 'nearest') kwargs.setdefault('norm', PowerNorm(gamma=0.5)) ax = plt.gca() if ax is None else ax image = self.pdf_matrix.transpose() cax = ax.imshow(image, extent=self._extent(), **kwargs) if show_energy is not None: ener_val = Quantity(show_energy).to(self.reco_energy.unit).value ax.hlines(ener_val, 0, 200200, linestyles='dashed') ax.set_ylabel('True energy (TeV)') ax.set_xlabel('Reco energy (TeV)') ax.set_xscale('log') ax.set_yscale('log') fig = ax.figure cbar = fig.colorbar(cax) return ax
def plot_image_radec(self, ax=None, number_bins=50): """Plot a sky counts image in RA/DEC coordinates. """ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.colors import PowerNorm ax = plt.gca() if ax is None else ax count_image, x_edges, y_edges = np.histogram2d( self.table[:]['RA'], self.table[:]['DEC'], bins=number_bins) ax.set_title('# Photons') ax.set_xlabel('RA') ax.set_ylabel('DEC') ax.plot(self.pointing_radec.ra.value, self.pointing_radec.dec.value, '+', ms=20, mew=3, color='white') im = ax.imshow(count_image, interpolation='nearest', origin='low', extent=[x_edges[0], x_edges[-1], y_edges[0], y_edges[-1]], norm=PowerNorm(gamma=0.5)) ax.invert_xaxis() ax.grid() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax)
def save_image(logits): # Image note logits and save fig, ax = plt.subplots(figsize=(14, 20)) ax.imshow(np.asarray(logits).reshape((200, 138)), norm=PowerNorm(0.4)) image_path = os.path.join( BASE_OUTPUT_FOLDER, "{name}_{maj_min}.png".format(name=name, maj_min=chord_descr)) fig.savefig(image_path)
def test_colorbar_powernorm_extension(): # Test that colorbar with powernorm is extended correctly f, ax = plt.subplots() cb = Colorbar(ax, norm=PowerNorm(gamma=0.5, vmin=0.0, vmax=1.0), orientation='vertical', extend='both') assert cb._values[0] >= 0.0
def plot_h_max(reconstructed_events, site='paranal', colormap=default_cmap, color=main_color, ax=None): df = reconstructed_events df = df.loc[df.mc_x_max > 0] thickness, altitude = get_atmosphere_profile_functions(site) mc_h_max = altitude(df.mc_x_max.clip(upper=1020).values * u.Unit('g/cm^2')) bins, bin_center, bin_widths = make_default_cta_binning( e_min=0.01 * u.TeV, e_max=200 * u.TeV, ) x = df.mc_energy.values b_50, bin_edges, binnumber = binned_statistic(x, df.h_max, statistic='median', bins=bins) b_84, _, _ = binned_statistic(x, df.h_max, statistic=lambda x: np.percentile(x, q=[84]), bins=bins) b_16, _, _ = binned_statistic(x, df.h_max, statistic=lambda x: np.percentile(x, q=[16]), bins=bins) log_emin, log_emax = np.log10(0.007), np.log10(300) if not ax: fig, ax = plt.subplots(1, 1) im = ax.hexbin(x, mc_h_max, xscale='log', extent=(log_emin, log_emax, 0, 17500), cmap=colormap, norm=PowerNorm(0.5)) add_colorbar_to_figure(im, fig, ax, label='Counts') ax.hlines(b_50[:-1], bins[:-2], bins[1:-1], lw=2, color=color, label='Median Prediction') ax.fill_between(bins[:-1], b_16, b_84, alpha=0.3, color=color, step='post') ax.set_xscale('log') ax.set_ylabel('Max Height / m') ax.set_xlabel('True Energy / TeV') ax.legend(framealpha=0.0) ax.set_xlim([0.007, 300]) plt.tight_layout(pad=0, rect=(0, 0, 1.003, 1)) return ax
def tvima(im, vmax=0, gamma=0.5, cmap='gist_stern'): if vmax == 0: vmax = im.max() plt.imshow(np.rot90(im, 2), cmap=cmap, vmax=vmax, norm=PowerNorm(gamma=gamma)) plt.colorbar() plt.show()
def plot_bias(self, ax=None, offset=None, e_true=None, migra=None, **kwargs): """Plot migration as a function of true energy for a given offset Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis offset : `~astropy.coordinates.Angle`, optional Offset e_true : `~gammapy.utils.energy.Energy`, optional True energy migra : `~numpy.array`, list, optional Migration nodes Returns ------- ax : `~matplotlib.axes.Axes` Axis """ from matplotlib.colors import PowerNorm import matplotlib.pyplot as plt kwargs.setdefault('cmap', 'afmhot') kwargs.setdefault('norm', PowerNorm(gamma=0.5)) ax = plt.gca() if ax is None else ax if offset is None: offset = Angle([1], 'deg') if e_true is None: e_true = self.e_true.nodes if migra is None: migra = self.migra.nodes z = self.data.evaluate(offset=offset, e_true=e_true, migra=migra) #y=e_true.value #x=migra #ax.pcolor(x, y, z, **kwargs) extent = [ e_true.value.min(), e_true.value.max(), migra.min(), migra.max(), ] ax.imshow(z.transpose(), extent=extent, origin='bottom', **kwargs) ax.semilogx() ax.set_xlabel('Energy (TeV)') ax.set_ylabel('E_Reco / E_true') return ax
def plot_containment(self, fraction=0.68, ax=None, show_safe_energy=False, add_cbar=True, **kwargs): """ Plot containment image with energy and theta axes. Parameters ---------- fraction : float Containment fraction between 0 and 1. add_cbar : bool Add a colorbar """ from matplotlib.colors import PowerNorm import matplotlib.pyplot as plt ax = plt.gca() if ax is None else ax kwargs.setdefault('cmap', 'afmhot') kwargs.setdefault('norm', PowerNorm(gamma=0.5)) kwargs.setdefault('origin', 'lower') kwargs.setdefault('interpolation', 'nearest') # kwargs.setdefault('vmin', 0.1) # kwargs.setdefault('vmax', 0.2) # Set up and compute data containment = self.containment_radius(self.energy_hi, self.theta, fraction) extent = [ self.theta[0].value, self.theta[-1].value, self.energy_lo[0].value, self.energy_hi[-1].value, ] # Plotting ax.imshow(containment.T.value, extent=extent, **kwargs) if show_safe_energy: # Log scale transformation for position of energy threshold e_min = self.energy_hi.value.min() e_max = self.energy_hi.value.max() e = (self.energy_thresh_lo.value - e_min) / (e_max - e_min) x = (np.log10(e * (e_max / e_min - 1) + 1) / np.log10(e_max / e_min) * (len(self.energy_hi) + 1)) ax.vlines(x, -0.5, len(self.theta) - 0.5) ax.text(x + 0.5, 0, 'Safe energy threshold: {0:3.2f}'.format(self.energy_thresh_lo)) # Axes labels and ticks, colobar ax.semilogy() ax.set_xlabel('Offset (deg)') ax.set_ylabel('Energy (TeV)') if add_cbar: ax_cbar = plt.colorbar(fraction=0.1, pad=0.01, shrink=0.9, mappable=ax.images[0], ax=ax) label = 'Containment radius R{0:.0f} (deg)'.format(100 * fraction) ax_cbar.set_label(label) return ax
def save_img_grid(generator, noise_vector_length, inv_transf, channel_axis, fname=None, Xterm=True, scale='lin', multichannel=False): """Plots a grid of generated images""" imgs_per_side = 2 samples = generator.predict( np.random.normal(size=(imgs_per_side**2, 1, noise_vector_length))) if multichannel: samples = np.take(samples, 0, axis=channel_axis) # take the scaled channel else: samples = np.squeeze(samples) genimg_sidelen = samples.shape[2] tot_len = imgs_per_side * genimg_sidelen gridimg = np.zeros((tot_len, tot_len)) cnt = 0 for i in range(imgs_per_side): for j in range(imgs_per_side): gridimg[i*genimg_sidelen:(i+1)*genimg_sidelen, j*genimg_sidelen:(j+1)*genimg_sidelen] \ = samples[cnt,:,:] cnt += 1 plt.figure(figsize=(5, 4)) if scale == 'pwr': imgmap = plt.pcolormesh(gridimg, norm=PowerNorm(gamma=0.2, vmin=0., vmax=2000), cmap='Blues') # Power normalized color scale else: imgmap = plt.imshow(gridimg, cmap='Blues', norm=Normalize(vmin=-1., vmax=1.)) # Linear color scale plt.colorbar(imgmap) plt.plot([tot_len // 2, tot_len // 2], [0, tot_len], 'k-', linewidth='0.6') plt.plot([0, tot_len], [tot_len // 2, tot_len // 2], 'k-', linewidth='0.6') plt.axis([0, tot_len, 0, tot_len]) plt.tick_params(axis='both', which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) plt.title('Generated Images') if Xterm: plt.draw() else: plt.savefig(fname, format='png') plt.close()
def plot_bias(self, ax=None, offset=None, add_cbar=False, **kwargs): """Plot migration as a function of true energy for a given offset. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis offset : `~astropy.coordinates.Angle`, optional Offset add_cbar : bool Add a colorbar to the plot. kwargs : dict Keyword arguments passed to `~matplotlib.pyplot.pcolormesh`. Returns ------- ax : `~matplotlib.axes.Axes` Axis """ from matplotlib.colors import PowerNorm import matplotlib.pyplot as plt kwargs.setdefault("cmap", "GnBu") kwargs.setdefault("norm", PowerNorm(gamma=0.5)) ax = plt.gca() if ax is None else ax if offset is None: offset = Angle(1, "deg") energy_true = self.data.axes["energy_true"] migra = self.data.axes["migra"] x = energy_true.edges.value y = migra.edges.value z = self.data.evaluate( offset=offset, energy_true=energy_true.center.reshape(1, -1, 1), migra=migra.center.reshape(1, 1, -1), ).value[0] caxes = ax.pcolormesh(x, y, z.T, **kwargs) if add_cbar: label = "Probability density (A.U.)" ax.figure.colorbar(caxes, ax=ax, label=label) ax.set_xlabel(fr"$E_\mathrm{{True}}$ [{energy_true.unit}]") ax.set_ylabel(r"$E_\mathrm{{Reco}} / E_\mathrm{{True}}$") ax.set_xlim(x.min(), x.max()) ax.set_ylim(y.min(), y.max()) ax.set_xscale("log") return ax
def plot_and_save_rgb_images(rgb_input, rgb_target, rgb_predict, name, save_name, logging_for_documentation, input_us=None, target_us=None, predict_us=None): input_us = prepare_us_for_overlay(us=input_us, rgb=rgb_input) target_us = prepare_us_for_overlay(us=target_us, rgb=rgb_target) predict_us = prepare_us_for_overlay(us=predict_us, rgb=rgb_predict) rgb_input = overlay_us_rgb(us=input_us, rgb=rgb_input) rgb_input = overlay_us_rgb(us=target_us, rgb=rgb_target) rgb_input = overlay_us_rgb(us=predict_us, rgb=rgb_predict) if logging_for_documentation: f, axarr = plt.subplots(1, 3, figsize=(18, 18)) axarr[0].imshow(input_us, extent=(-.5, rgb_input.shape[1] - .5, rgb_input.shape[0] - .5, -.5), cmap='gray') axarr[0].imshow(rgb_input, norm=PowerNorm(gamma=.5)) axarr[0].axis('off') axarr[0].set_title('Input') axarr[1].imshow(target_us, extent=(-.5, rgb_target.shape[1] - .5, rgb_target.shape[0] - .5, -.5), cmap='gray') axarr[1].imshow(rgb_target, norm=PowerNorm(gamma=.5)) axarr[1].axis('off') axarr[1].set_title('Target') axarr[2].imshow(predict_us, extent=(-.5, rgb_predict.shape[1] - .5, rgb_predict.shape[0] - .5, -.5), cmap='gray') axarr[2].imshow(rgb_predict, norm=PowerNorm(gamma=.5)) axarr[2].axis('off') axarr[2].set_title('Predict') else: plt.figure(figsize=(18, 18)) plt.subplot(1, 3, 1) plt.title('input' + '_' + name) plt.imshow(rgb_input, norm=PowerNorm(gamma=.5)) plt.subplot(1, 3, 2) plt.title('target' + '_' + name) plt.imshow(rgb_target, norm=PowerNorm(gamma=.5)) plt.subplot(1, 3, 3) plt.title('predict' + '_' + name) plt.imshow(rgb_predict, norm=PowerNorm(gamma=.5)) if save_name is not None: plt.savefig(save_name, bbox_inches='tight') plt.clf() plt.close('all')
def plot_image_radec(self, ax=None, number_bins=50): """Plot a sky counts image in RADEC coordinate. TODO: fix the histogramming ... this example shows that it's currently incorrect: gammapy-data-show ~/work/hess-host-analyses/hap-hd-example-files/run023000-023199/run023037/hess_events_023037.fits.gz events -p Maybe we can use the FOVCube class for this with one energy bin. Or add a separate FOVImage class. """ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.colors import PowerNorm ax = plt.gca() if ax is None else ax # max_x = max(self.table['RA']) # min_x = min(self.table['RA']) # max_y = max(self.table['DEC']) # min_y = min(self.table['DEC']) # # x_edges = np.linspace(min_x, max_x, number_bins) # y_edges = np.linspace(min_y, max_y, number_bins) count_image, x_edges, y_edges = np.histogram2d(self.table[:]['RA'], self.table[:]['DEC'], bins=number_bins) ax.set_title('# Photons') ax.set_xlabel('RA') ax.set_ylabel('DEC') ax.plot(self.pointing_radec.ra.value, self.pointing_radec.dec.value, '+', ms=20, mew=3, color='white') im = ax.imshow( count_image, interpolation='nearest', origin='low', extent=[x_edges[0], x_edges[-1], y_edges[0], y_edges[-1]], norm=PowerNorm(gamma=0.5)) ax.invert_xaxis() ax.grid() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax)
def plot_bias(self, ax=None, offset=None, add_cbar=False, **kwargs): """Plot migration as a function of true energy for a given offset. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis offset : `~astropy.coordinates.Angle`, optional Offset add_cbar : bool Add a colorbar to the plot. kwargs : dict Keyword arguments passed to `~matplotlib.pyplot.pcolormesh`. Returns ------- ax : `~matplotlib.axes.Axes` Axis """ import matplotlib.pyplot as plt from matplotlib.colors import PowerNorm kwargs.setdefault("cmap", "GnBu") kwargs.setdefault("norm", PowerNorm(gamma=0.5)) ax = plt.gca() if ax is None else ax if offset is None: offset = Angle(1, "deg") energy_true = self.axes["energy_true"] migra = self.axes["migra"] z = self.evaluate( offset=offset, energy_true=energy_true.center.reshape(1, -1, 1), migra=migra.center.reshape(1, 1, -1), ).value[0] with quantity_support(): caxes = ax.pcolormesh(energy_true.edges, migra.edges, z.T, **kwargs) energy_true.format_plot_xaxis(ax=ax) migra.format_plot_yaxis(ax=ax) if add_cbar: label = "Probability density (A.U.)" ax.figure.colorbar(caxes, ax=ax, label=label) return ax
def plot_bias(self, ax=None, offset=None, add_cbar=False, **kwargs): """Plot migration as a function of true energy for a given offset Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis offset : `~astropy.coordinates.Angle`, optional Offset add_cbar : bool Add a colorbar to the plot. kwargs : dict Keyword arguments passed to `~matplotlib.pyplot.pcolormesh`. Returns ------- ax : `~matplotlib.axes.Axes` Axis """ from matplotlib.colors import PowerNorm import matplotlib.pyplot as plt kwargs.setdefault('cmap', 'GnBu') kwargs.setdefault('norm', PowerNorm(gamma=0.5)) ax = plt.gca() if ax is None else ax if offset is None: offset = Angle([1], 'deg') e_true = self.e_true.bins migra = self.migra.bins x = e_true.value y = migra.value z = self.data.evaluate(offset=offset, e_true=e_true, migra=migra) caxes = ax.pcolormesh(x, y, z.T, **kwargs) if add_cbar: label = 'Probability density (A.U.)' cbar = ax.figure.colorbar(caxes, ax=ax, label=label) ax.semilogx() ax.set_xlabel('Energy ({unit})'.format(unit=e_true.unit)) ax.set_ylabel('E_Reco / E_true') ax.set_xlim(x.min(), x.max()) ax.set_ylim(y.min(), y.max()) return ax
def plot_matrix(self, ax=None, show_energy=None, add_cbar=False, **kwargs): """ Plot PDF matrix. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis show_energy : `~astropy.units.Quantity`, optional Show energy, e.g. threshold, as vertical line add_cbar : bool Add a colorbar to the plot. Returns ------- ax : `~matplotlib.axes.Axes` Axis """ import matplotlib.pyplot as plt from matplotlib.colors import PowerNorm kwargs.setdefault('cmap', 'GnBu') norm = PowerNorm(gamma=0.5) kwargs.setdefault('norm', norm) ax = plt.gca() if ax is None else ax e_true = self.e_true.bins e_reco = self.e_reco.bins x = e_true.value y = e_reco.value z = self.pdf_matrix caxes = ax.pcolormesh(x, y, z.T, **kwargs) if show_energy is not None: ener_val = Quantity(show_energy).to(self.reco_energy.unit).value ax.hlines(ener_val, 0, 200200, linestyles='dashed') if add_cbar: label = 'Probability density (A.U.)' cbar = ax.figure.colorbar(caxes, ax=ax, label=label) ax.set_xlabel('True energy ({unit})'.format(unit=e_true.unit)) ax.set_ylabel('Reco energy ({unit})'.format(unit=e_reco.unit)) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlim(x.min(), x.max()) ax.set_ylim(y.min(), y.max()) return ax
def plotDataAsMesh(self, interactive=True ): #XXX enable backend to use image for other purposes fig, ax = plt.subplots() side_length = np.arange(self.numMeasurements()) x_axis, y_axis = np.meshgrid(side_length, self.frequency_axis) mesh = ax.pcolormesh(x_axis, y_axis, self.data, norm=PowerNorm(0.4), cmap=cm.jet, shading='gouraud') fig.colorbar(mesh) ax.set_title("James Fruit Test, 27/11::4/12 - Mesh Plot") plt.show()
def plot_matrix(self, ax=None, show_energy=None, add_cbar=False, **kwargs): """Plot PDF matrix. Parameters ---------- ax : `~matplotlib.axes.Axes`, optional Axis show_energy : `~astropy.units.Quantity`, optional Show energy, e.g. threshold, as vertical line add_cbar : bool Add a colorbar to the plot. Returns ------- ax : `~matplotlib.axes.Axes` Axis """ import matplotlib.pyplot as plt from matplotlib.colors import PowerNorm kwargs.setdefault("cmap", "GnBu") norm = PowerNorm(gamma=0.5) kwargs.setdefault("norm", norm) ax = plt.gca() if ax is None else ax e_true = self.e_true.edges e_reco = self.e_reco.edges x = e_true.value y = e_reco.value z = self.pdf_matrix caxes = ax.pcolormesh(x, y, z.T, **kwargs) if show_energy is not None: ener_val = show_energy.to_value(self.reco_energy.unit) ax.hlines(ener_val, 0, 200200, linestyles="dashed") if add_cbar: label = "Probability density (A.U.)" cbar = ax.figure.colorbar(caxes, ax=ax, label=label) ax.set_xlabel(fr"$E_\mathrm{{True}}$ [{e_true.unit}]") ax.set_ylabel(fr"$E_\mathrm{{Reco}}$ [{e_reco.unit}]") ax.set_xscale("log") ax.set_yscale("log") ax.set_xlim(x.min(), x.max()) ax.set_ylim(y.min(), y.max()) return ax
def plot_hist2D(y_true, y_pred, net_name, fig_folder, num_bins=10, do_show=True): plt.figure() plt.hist2d(x=y_true, y=y_pred.flatten(), bins=num_bins, cmap='inferno', norm=PowerNorm(0.65)) plt.plot([1, 10], [1, 10], 'w-') plt.xlabel('True Energy (Log10)') plt.ylabel('Predicted Energy (Log10)') plt.colorbar() plt.title('Regression Performances ' + net_name) plt.legend(['Ideal Line']) plt.xlim(1.2, 4.5) plt.ylim(1.2, 4.5) plt.savefig(fig_folder + '/' + net_name + '_hist2D' + '.png') plt.savefig(fig_folder + '/' + net_name + '_hist2D' + '.eps') if do_show: plt.show() plt.close()
def plot_h_max_distance(reconstructed_events, site='paranal', colormap=default_cmap, color=main_color, ax=None): df = reconstructed_events df = df.loc[df.mc_x_max > 0] thickness, altitude = get_atmosphere_profile_functions(site) mc_h_max = altitude(df.mc_x_max.values * u.Unit('g/cm^2')).value y = mc_h_max - df.h_max bins, bin_center, bin_widths = make_default_cta_binning(e_min=0.003 * u.TeV, e_max=330 * u.TeV) x = df.mc_energy.values b_50, bin_edges, binnumber = binned_statistic(x, y, statistic='median', bins=bins) bin_centers = np.sqrt(bin_edges[1:] * bin_edges[:-1]) log_emin, log_emax = np.log10(bins.min().value), np.log10(bins.max().value) if not ax: fig, ax = plt.subplots(1, 1) im = ax.hexbin(x, y, xscale='log', extent=(log_emin, log_emax, 0.01, 3000), cmap=colormap, norm=PowerNorm(0.5)) add_colorbar_to_figure(im, fig, ax) ax.plot(bin_centers, b_50, lw=2, color=color, label='Median') ax.set_xscale('log') ax.set_ylabel('Distance to true H max / meter') ax.set_xlabel(r'$E_{True} / TeV$') ax.set_xlim([0.007, 300]) return ax
def plot_multi_vs_energy(x, y, out_file=None): x_bins, x_bin_center, _ = make_default_cta_binning(e_min=min(x) * u.TeV, e_max=max(x) * u.TeV) y_bins = np.arange(0, 30, 1) num_tel_events = np.sum(y) fig, ax = plt.subplots(1, 1, figsize=figsize) h, xedges, yedges, im = ax.hist2d(x, y / num_tel_events, label='stereo method', bins=(x_bins.to_value(u.TeV), y_bins), cmap=default_cmap, norm=PowerNorm(0.3)) ax.set_ylabel('Multiplicity') ax.set_xlabel('MC Energy') ax.set_xscale('log') #ax.set_title(f'Multiplicity\n samples: {len(y)}') add_colorbar_to_figure(im, fig, ax) if out_file: fig.savefig(out_file) return 0 return fig, ax
def img_to_file(int_cols, formulas, pvalues, img_folder): for c in int_cols: for formula_part in formulas: plt.subplots(figsize=(40, 5)) df = pvalues[c][formula_part] if not isinstance(df, pd.core.frame.DataFrame): df = pd.DataFrame(df, columns=[ 'Intercept', 'Agent[T.R]', c + formula_part, c + formula_part + ':Agent[T.R]', 'Warning' ]) df['Warning'] = df['Warning'].apply(lambda x: 1 if x is not None else 0) sns_plot = sns.heatmap( df.T, norm=PowerNorm(gamma=1. / 3.), cbar_kws={'ticks': [0.0, 0.01, 0.05, 0.1, 0.2, 0.5, 1.0]}) sns_plot.figure.savefig( os.path.join(img_folder, '{}{}.png'.format(c, formula_part)))
def print_distribution(distri, equalAxes=True): """ Prints a given distribution Parameters ---------- distri np.array The given distribution to print. equalAxes bool Boolean to enable/disable equal axis. """ fig, axs = plt.subplots(1, 1) fig.set_figheight(8) fig.set_figwidth(8) hist = axs.hist2d(distri[:, 0], distri[:, 1], bins=100, density=True, norm=PowerNorm(gamma=1. / 2.)) fig.colorbar(hist[3]) if equalAxes: axs.axis('equal')