def network_connection_dynamics( connection_counts: np.array, initial_steps: int, final_steps: int, savefig: bool ): """Plot number of positive connection in the excitatory pool Args: connection_counts (array) - 1D Array of number of connections in the network per time step initial_steps (int) - Plot for initial steps final_steps (int) - Plot for final steps savefig (bool) - If True plot will be saved as png file in the cwd Returns: plot object """ # Plot graph for entire simulation time period _, ax1 = plt.subplots(figsize=(12, 5)) ax1.plot(connection_counts, label="Connection dynamics") plt.margins(x=0) ax1.set_xticks(ax1.get_xticks()[::2]) ax1.set_title("Network connection dynamics") plt.ylabel("Number of active connections") plt.xlabel("Time step") plt.legend(loc="upper right") plt.tight_layout() # Inset plot for initial simulation steps ax2 = plt.axes([0, 0, 1, 1]) # Set the position and relative size of the inset axes within ax1 ip = InsetPosition(ax1, [0.25, 0.4, 0.3, 0.3]) ax2.set_axes_locator(ip) ax2.plot(connection_counts[0:initial_steps]) plt.margins(x=0) ax2.set_title("Initial %s time steps of Decay Phase" % initial_steps) ax2.set_xticks(ax2.get_xticks()[::2]) # End Inset plot ax3 = plt.axes([0, 0, 0, 0]) # Set the position and relative size of the inset axes within ax1 ip1 = InsetPosition(ax1, [0.6, 0.4, 0.3, 0.3]) ax3.set_axes_locator(ip1) # Plot the last 10000 time steps ax3.plot(connection_counts[-final_steps:]) plt.margins(x=0) ax3.set_title("Final %s time steps of Stable Phase" % final_steps) ax3.set_xticks(ax3.get_xticks()[::1]) if savefig: plt.savefig("connection_dynamics") return plt.show()
def network_connection_dynamics(connection_counts, initial_steps, final_steps, savefig): """Args: :param connection_counts(array) - 1D Array of number of connections in the network per time step :param initial_steps(int) - Plot for initial steps :param final_steps(int) - Plot for final steps :param savefig(bool) - If True plot will be saved as png file in the cwd Returns: plot object""" # Plot graph for entire simulation time period fig1, ax1 = plt.subplots(figsize=(12, 5)) ax1.plot(connection_counts, label='Connection dynamics') plt.margins(x=0) ax1.set_xticks(ax1.get_xticks()[::2]) ax1.set_title("Network connection dynamics") plt.ylabel('Number of active connections') plt.xlabel('Time step') plt.legend(loc='upper right') plt.tight_layout() # Inset plot for initial simulation steps ax2 = plt.axes([0, 0, 1, 1]) # Set the position and relative size of the inset axes within ax1 ip = InsetPosition(ax1, [0.25, 0.4, 0.3, 0.3]) ax2.set_axes_locator(ip) ax2.plot(connection_counts[0:initial_steps]) plt.margins(x=0) ax2.set_title('Initial %s time steps of Decay Phase' % initial_steps) ax2.set_xticks(ax2.get_xticks()[::2]) # End Inset plot ax3 = plt.axes([0, 0, 0, 0]) # Set the position and relative size of the inset axes within ax1 ip1 = InsetPosition(ax1, [0.6, 0.4, 0.3, 0.3]) ax3.set_axes_locator(ip1) # Plot the last 10000 time steps ax3.plot(connection_counts[-final_steps:]) plt.margins(x=0) ax3.set_title('Final %s time steps of Stable Phase' % final_steps) ax3.set_xticks(ax3.get_xticks()[::1]) # Uncomment to show decay and stable phase in colors # ax1.axvspan(0, 200000, alpha=0.1, color='red') # ax2.axvspan(0, 10000, alpha=0.1, color='red') # ax1.axvspan(200000, 1000000, alpha=0.1, color='green') if savefig: plt.savefig('connection_dynamics') return plt.show()
def plot_inset(*args, ax_lims=None, inset_pos=None, line_pos=None): fig, ax = plt.subplots() # create a new figure with a default 111 subplot ax.plot(*args) if inset_pos is None: inset_pos = [0.2, 0.4, 0.5, 0.5] if ax_lims is None: ax_lims = [0, 1, 0, 1] if line_pos is None: line_pos = [2, 3] ax2 = plt.axes([0, 0, 1, 1]) # Manually set the position and relative size of the inset axes within ax1 ip = InsetPosition(ax, inset_pos) ax2.set_axes_locator(ip) ax2.plot(*args) x1, x2, y1, y2 = ax_lims ax2.set_xlim(x1, x2) # apply the x-limits ax2.set_ylim(y1, y2) # apply the y-limits mark_inset(ax, ax2, loc1=line_pos[0], loc2=line_pos[1], fc="none", ec='0.5')
def createUIAlgorithm(self): algorithm = settings.application.algorithm.lower() defaultAlgoritmIdx = 0 if (algorithm == 'total'): defaultAlgoritmIdx = 0 elif (algorithm == 'parallel'): defaultAlgoritmIdx = 1 elif (algorithm == 'naive'): defaultAlgoritmIdx = 2 self.axAlgorithm.set_title('Algorithm', x=0, horizontalalignment='left') # create an axis to host to radio buttons. make its aspect ratio # equal so the radiobuttons stay round aspect = self.get_aspect(self.axAlgorithm) rect = [0, 0, 1.0 * aspect, 1.0] ip = InsetPosition(self.axAlgorithm, rect) self.axRadio = plt.axes(rect) self.axRadio.set_axes_locator(ip) self.axRadio.axis('off') self.radioAlgorithm = RadioButtons( self.axRadio, ('Total Energy', 'Parallel Energy', 'Naive (no filter)'), active=defaultAlgoritmIdx) self.radioAlgorithm.on_clicked(self.onClickAlgorithm)
def qq_plot_inset(a_samples, b_samples, ax_lims, inset_pos=None): # Plots qq_plot with inset zoomed in on the ax_lims section if inset_pos is None: inset_pos = [0.1, 0.3, 0.65, 0.65] percentages = np.linspace(0, 100, 100) quants_a = np.percentile(a_samples, percentages) quants_b = np.percentile(b_samples, percentages) fig, ax = plt.subplots() # create a new figure with a default 111 subplot ax.plot(quants_a, quants_b, ls="", marker='o') x = np.linspace(min(np.min(quants_a), np.min(quants_b)), max(np.max(quants_a), np.max(quants_b))) ax.plot(x, x, color="k", ls="--") ax2 = plt.axes([0, 0, 1, 1]) # Manually set the position and relative size of the inset axes within ax1 ip = InsetPosition(ax, inset_pos) ax2.set_axes_locator(ip) ax2.plot(quants_a, quants_b, ls="", marker='o') ax2.plot(x, x, color="k", ls="--") x1, x2, y1, y2 = ax_lims ax2.set_xlim(x1, x2) # apply the x-limits ax2.set_ylim(y1, y2) # apply the y-limits mark_inset(ax, ax2, loc1=2, loc2=4, fc="none", ec='0.5')
def createUIGaussianFilterControls(self): axcolor = 'lightgoldenrodyellow' rect = [0.82, -0.158, 0.14, 0.07] ax_btnapply = plt.axes(rect) ip = InsetPosition(self.axGauss, rect) #posx, posy, width, height ax_btnapply.set_axes_locator(ip) self.btnApply = Button(ax_btnapply, 'Apply') self.btnApply.on_clicked(self.onclickApply) rect = [0.82, -0.245, 0.14, 0.07] ax_btnreset = plt.axes(rect) ip = InsetPosition(self.axGauss, rect) #posx, posy, width, height ax_btnreset.set_axes_locator(ip) self.btnReset = Button(ax_btnreset, 'Reset', color='0.950', hovercolor='0.975') self.btnReset.on_clicked(self.onclickReset) rect = [0.1, -0.155, 0.55, 0.04] self.ax_window_size = plt.axes(rect, facecolor=axcolor) ip = InsetPosition(self.axGauss, rect) #posx, posy, width, height self.ax_window_size.set_axes_locator(ip) self.slider_window_size = Slider(self.ax_window_size, 'Window Size', 1, (self.gauss_params[0] + 1) * 2 + 1, valinit=self.gauss_params[0], valstep=2) self.slider_window_size.on_changed(self.updateGaussianFilter) rect = [0.1, -0.235, 0.55, 0.04] self.ax_sigma = plt.axes(rect, facecolor=axcolor) ip = InsetPosition(self.axGauss, rect) #posx, posy, width, height self.ax_sigma.set_axes_locator(ip) self.slider_sigma = Slider(self.ax_sigma, 'Sigma', 1, (self.gauss_params[1] + 1) * 2, valinit=self.gauss_params[1], valstep=1) self.slider_sigma.on_changed(self.updateGaussianFilter) self.updateGaussianFilter()
def onresize(self, event): # plt.tight_layout() # keep tha radio buttons round... if (self.axRadio is not None) and (self.axAlgorithm is not None): aspect = self.get_aspect(self.axAlgorithm) rect = [0, 0, 1.0 * aspect, 1.0] ip = InsetPosition(self.axAlgorithm, rect) self.axRadio.set_axes_locator(ip) self.axRadio.set_position(rect) self.resetLogLabels()
def axes_from_axes(ax: Axes, n: int, extent: Iterable = [0.2, 0.2, 0.6, 1.0], **kwargs) -> Axes: """Uses the location of an existing axes to create another axes in relative coordinates. IMPORTANT: Unlike ``inset_axes``, this function propagates ``*args`` and ``**kwargs`` to the ``pyplot.axes()`` function, which allows for the use of the projection ``keyword``. Parameters ---------- ax : Axes Existing axes n : int label, necessary, because matplotlib will replace nonunique axes extent : list, optional new position in axes relative coordinates, by default [0.2, 0.2, 0.6, 1.0] Returns ------- Axes New axes Notes ----- DO NOT CHANGE THE INITIAL POSITION, this position works DO NOT CHANGE! :Author: Lucas Sawade ([email protected]) :Last Modified: 2021.07.13 18.30 """ # Create new axes DO NOT CHANGE THIS INITIAL POSITION newax = plt.axes([0.0, 0.0, 0.25, 0.1], label=str(n), **kwargs) # Get new position ip = InsetPosition(ax, extent) # Set new position newax.set_axes_locator(ip) # return new axes return newax
def make_zoomed_cryoscope_fig(t, amp, title, ax=None, **kw): # x = ca.time x = t y = amp # y = ca.get_amplitudes() gc = np.mean(y[len(y)//5:4*len(y)//5]) if ax is not None: ax = ax f = plt.gcf() else: f, ax = plt.subplots() ax.plot(x, y/gc, label='Signal') ax.axhline(1.01, ls='--', c='grey', label=r'$\pm$1%') ax.axhline(0.99, ls='--', c='grey') ax.axhline(1.0, ls='-', c='grey', linewidth=.5) ax.axhline(1.001, ls=':', c='grey', label=r'$\pm$ 0.1%') ax.axhline(0.999, ls=':', c='grey') # ax.axvline(10e-9, ls='--', c='k') ax.set_ylim(.95, 1.02) set_xlabel(ax, 'Time', 's') set_ylabel(ax, 'Normalized Amplitude', '') # Create a set of inset Axes: these should fill the bounding box allocated to # them. ax2 = plt.axes([0, 0, 1, 1]) # Manually set the position and relative size of the inset axes within ax1 ip = InsetPosition(ax, [.29, .14, 0.65, .4]) ax2.set_axes_locator(ip) mark_inset(ax, ax2, 1, 3, color='grey') ax2.axhline(1.0, ls='-', c='grey', linewidth=.5) ax2.axhline(1.01, ls='--', c='grey', label=r'$\pm$1%') ax2.axhline(0.99, ls='--', c='grey') ax2.axhline(1.001, ls=':', c='grey', label=r'$\pm$ 0.1%') ax2.axhline(0.999, ls=':', c='grey') ax2.plot(x, y/gc, '-') formatter = ticker.FuncFormatter(lambda x, pos: round(x*1e9, 3)) ax2.xaxis.set_major_formatter(formatter) ax2.set_ylim(0.998, 1.002) ax2.set_xlim(0, min(150e-9, max(t))) ax.legend(loc=1) ax.set_title(title) ax.text(.02, .93, '(a)', color='black', transform=ax.transAxes)
def resetLogLabels(self): cnt = len(self.logTextLabels) for i in range(0, cnt): self.logTextLabels[i].remove() self.logTextLabels = [] bbox = self.axLog.get_window_extent() self.axLog.set_xlim(0, bbox.width) self.axLog.set_ylim(0, bbox.height) aspect = self.get_aspect(self.axLog) rect = [0, 0, 1.0 * aspect, 1.0] ip = InsetPosition(self.axLog, rect) if (self.axLogLabels is None): self.axLogLabels = plt.axes(rect) else: self.axLogLabels.set_position(rect) self.axLogLabels.set_axes_locator(ip) self.axLogLabels.axis('off') aspectLog = 1.0 / self.get_aspect(self.axLog) strText = 'Tyg' tmp, self.logTextHeight = settings.getTextExtent(self.axLog, strText) self.logTextHeight = self.logTextHeight * aspectLog # * self.fig.dpi # pre-create empty log label placeholders self.logTextLabels = [] y = (self.logTextHeight / 4.0) cy = bbox.height idx = len(self.logText) - 1 while (y < cy): str = self.logText[idx] if (idx >= 0) else '' idx = idx - 1 lbl = self.axLogLabels.text( 8.0, y, str, horizontalalignment='left', verticalalignment='bottom', color='dimgray', clip_on=True, transform=self.axLog.transData ) #, bbox={'facecolor':'lightgray', 'alpha':0.7, 'pad':0.0}) self.logTextLabels.append(lbl) y += self.logTextHeight
def __init__(self, ax, on_auto_clicked): self.ax = ax self.on_auto_clicked_callback = on_auto_clicked kwargs = { 'horizontalalignment': 'center', 'verticalalignment': 'center', 'transform': self.ax.transAxes } self.A_text = self.ax.text(.05, .5, "A =", fontsize=25, **kwargs) self.matrix_text = self.ax.text(.7, .5, "(No Matrix)", fontsize=25, **kwargs) self.trace_text = self.ax.text(.5, .15, "(No Data)", fontsize=14, **kwargs) self.det_text = self.ax.text(.5, .05, "(No Data)", fontsize=14, **kwargs) # AUTO Button setup warnings.filterwarnings( "ignore", message= "This figure includes Axes that are not compatible with tight_layout, so results might be incorrect." ) button_axes = plt.axes([0, 0, 1, 1]) ip = InsetPosition(self.ax, [0.2, 0.88, 0.6, 0.1]) button_axes.set_axes_locator(ip) self.auto_button = Button(button_axes, 'RUN AUTO ELLIPSE', color='gray') self.auto_button.on_clicked(lambda event: self.on_auto_clicked(event)) # Don't draw the axes self.ax.axis('off')
def plot_map(self): self.ax['m']['main'].axis("off") # inset location relative to main plot (ax) in normalized units inset_x = 0.5 inset_y = 0.5 inset_size = 0.8 inset_dim = [ inset_x - inset_size / 2, inset_y - inset_size / 2, inset_size, inset_size ] self.ax['m']['inset'] = plt.axes([0, 0, 1, 1], projection=PlateCarree()) self.ax['m']['inset'].add_feature(cfeature.LAND) self.ax['m']['inset'].add_feature(cfeature.OCEAN) self.ax['m']['inset'].add_feature(cfeature.COASTLINE) ip = InsetPosition(self.ax['m']['main'], inset_dim) self.ax['m']['inset'].set_axes_locator(ip) self.ax['m']['inset'].set_extent(self.mapextent)
def __call__(self, pos=None, on=True): ''' ''' if pos is None: pos = self.pos res = [] for axis in np.atleast_1d(self.ax): ax = self.fig.add_subplot(111, label=np.random.randn()) ax.set_axes_locator(InsetPosition(axis, pos)) for tick in ax.get_xticklabels() + ax.get_yticklabels(): tick.set_fontsize(5) if not on: ax.axis('off') res.append(ax) if len(res) == 1: # This is a single axis return res[0] else: # This is a list of axes return res
# Plot the dipolar signal fits and their confidence bands ax1.plot(t, n / 2 + Vfit, label=f'{1+n}', linewidth=1.5, color=colors[n]) ax1.fill_between(t, n / 2 + Vci[:, 0], n / 2 + Vci[:, 1], alpha=0.3, color=colors[n]) # Plot the distance distributions as insets for n in range(Nmax): # Get the distance distribution and its confidence intervals Pfit = fits[n].P Pci = fits[n].PUncert.ci(95) # Setup the inset plot axins = inset_axes(ax1, width="30%", height="30%", loc='upper left') ip = InsetPosition(ax1, [0.35, 0.15 + 0.24 * n, 0.6, 0.1]) axins.set_axes_locator(ip) axins.yaxis.set_ticklabels([]) # Plot the distance distributions and their confidence bands axins.plot(r, Pfit, color=colors[n]) axins.fill_between(r, Pci[:, 0], Pci[:, 1], alpha=0.4, color=colors[n]) axins.set_xlabel('r (nm)') # Plot the difference in AIC for each fit ax2 = fig.add_subplot(gs[0, -1]) ax2.plot(aic, np.arange(Nmax), 'k--', alpha=0.3) for n in range(Nmax): ax2.semilogx(aic[n], n, 'o', markersize=10) # Axes settings ax1.set_ylabel('V(t) (arb.u.)')
files.sort() #Para el color colors = cm.rainbow(np.linspace(0, 0.9, len(files))) index = 0 offset1 = 0.0 ##cosas para el subplot from mpl_toolkits.axes_grid1.inset_locator import (inset_axes, InsetPosition, mark_inset ) # left corner (loc=3) fig, ax = plt.subplots() ax2 = plt.axes([0, 0, 1, 1]) ip = InsetPosition(ax, [0.38, 0.4, 0.6, 0.55]) ax2.set_axes_locator(ip) mark_inset(ax, ax2, loc1=1, loc2=2, fc="none", ec='0.5', alpha=0.0) ############################# for filename in files: x, y = np.loadtxt(directory + filename, unpack=True) ax.plot(1239.8 / x, offset1 + (y - 870) / 44000, c=colors[index]) ax2.plot(1239.8 / x, offset1 + (y - 870) / 44000, c=colors[index]) offset1 += 0.0100 index += 1 pass #plt.legend(loc='upper left', ncol=1) ax.set_xlim(1.5119, 1.5398)
#Rabbi Splitting Rabbi_lh = 0.00193 * 2.0 Rabbi_hh = 0.00298 * 2.0 ###################################3 z = A + z * B + C * z**2 - (hh + slope_hh * z) z = 1000 * z #para poner en mEv index = 0 colors = ['red', 'blue', 'black'] ##cosas para el subplot fig, ax = plt.subplots() ax2 = plt.axes([0, 0, 1, 1]) ip = InsetPosition(ax, [0.59, 0.08, 0.4, 0.4]) ax2.set_axes_locator(ip) mark_inset(ax, ax2, loc1=1, loc2=2, fc="none", ec='0.5') fig_sin_fit, ax_sin_fit = plt.subplots() ax_sin_fit_2 = plt.axes([0, 0, 1, 1]) ip1 = InsetPosition(ax_sin_fit, [0.59, 0.08, 0.4, 0.4]) ax_sin_fit_2.set_axes_locator(ip1) mark_inset(ax_sin_fit, ax_sin_fit_2, loc1=1, loc2=2, fc="none", ec='0.5') ############################# for filename in files: data = np.loadtxt(filename) x = data[:, 0] heavy = hh + slope_hh * x
for j in range(npeaks): ax1.plot(peak[j][wi, 1], peak[j][wi, 2], 'o', c='C' + str(j)) ax1.set_ylabel(r'$\Delta \lambda$ (nm)') ax1.set_xlabel(r'$\lambda_{0}$ (nm)') ax1.set_title(r'$\Delta^{op}$ at w =' + str(w[wi]) + ' nm for ' + directory) axpbar = plt.axes([0, 0, 101, 101], zorder=2) axpbar.spines['bottom'].set_color('w') axpbar.spines['top'].set_color('w') axpbar.spines['left'].set_color('w') axpbar.spines['right'].set_color('w') axpbar.tick_params(axis='x', colors='w') axpbar.tick_params(axis='y', colors='w') axpbar.set_axes_locator(InsetPosition(ax1, [0.45, 0.91, 0.45, 0.05])) cb1 = ColorbarBase(axpbar, cmap=cmap, norm=cnorm, orientation='horizontal', ticks=[0.0, 0.25, 0.5, 0.75, 1.0]) cb1.outline.set_edgecolor('w') cb1.set_label(r'$\Delta^{op}$ (arb.)', color='w') ax2.plot(spectrum[:, 0], spectrum[:, 1] / np.max(spectrum[:, 1]), '-k') xs = np.linspace(np.min(l0), np.max(l0), 400) norm = w[wi] * np.sqrt(2 * np.pi) for j in range(npeaks): ax2.plot(xs, norm * gauss(xs, w[wi], peak[j][wi, 1] - peak[j][wi, 2] / 2),
linestyle='-', marker='s', markevery=[1143], zorder=8, label=r"Box") ax5.text(0.02, 0.9, r"e)", ha="left", va="top", transform=ax5.transAxes) #, rotation=0, bbox=labelBox) # plot inset/zoom in 1d axial cross-correlation from mpl_toolkits.axes_grid1.inset_locator import (inset_axes, InsetPosition, mark_inset) ax6 = plt.axes( [0, 0, 1, 1] ) # Create a set of inset Axes: these should fill the bounding box allocated to them ip = InsetPosition(ax5, [ 0.75, 0.35, 0.20, 0.60 ]) # Manually set position and relative size of the inset within original ax5 ax6.set_axes_locator(ip) ax6.set_xlim(left=-10.0, right=10.0) # where to zoom in? ax6.set_ylim(bottom=-0.1, top=0.1) # where to zoom in? ax6.set_xticks([]) ax6.set_yticks([]) ax6.axhline(y=0.0, color=Grey) ax6.axvline(x=0.0, color=Grey) ax6.plot(z1d, puzF, color=Black, linestyle='-', marker='^', markevery=[1153], zorder=7,
ax2.plot(z, czB, color=Blue, linestyle='-', zorder=9, label=r"Box") ax2.legend(loc='lower left', frameon=False, fancybox=False, facecolor=None, edgecolor=None, framealpha=None) # plot inset/zoom in axial cross-correlation from mpl_toolkits.axes_grid1.inset_locator import (inset_axes, InsetPosition, mark_inset) ax3 = plt.axes( [0, 0, 1, 1] ) # Create a set of inset Axes: these should fill the bounding box allocated to them ip = InsetPosition( ax2, [0.575, 0.725, 0.4, 0.25 ]) # Manually set position and relative size of the inset within ax2 ax3.set_axes_locator(ip) ax3.set_xlim(left=-40.0, right=40.0) ax3.set_xticks([]) ax3.set_yticks([]) ax3.axhline(y=0.0, color=Grey) ax3.axvline(x=0.0, color=Grey) ax3.plot(z, czF, color=Black, linestyle='-', zorder=7, label=r"Fourier") ax3.plot(z, czG, color=Vermillion, linestyle='-', zorder=8, label=r"Gauss") ax3.plot(z, czB, color=Blue, linestyle='-', zorder=9, label=r"Box") #mark_inset(ax2, ax3, loc1=3, loc2=1, fc="none", ec='0.5') # Mark the region corresponding to the inset # plot mode interactive or pdf if plot == 1: plt.tight_layout()
def visualize_network(weights, biases, activations, M=100, y0range=[-1, 1], y1range=[-1, 1], size=400.0, linewidth=5.0, weights_are_swapped=False, layers_already_initialized=False, plot_cost_function=None, current_cost=None, cost_max=None, plot_target=None): """ Visualize a neural network with 2 input neurons and 1 output neuron (plot output vs input in a 2D plot) weights is a list of the weight matrices for the layers, where weights[j] is the matrix for the connections from layer j to layer j+1 (where j==0 is the input) weights[j][m,k] is the weight for input neuron k going to output neuron m (note: internally, m and k are swapped, see the explanation of batch processing in lecture 2) biases[j] is the vector of bias values for obtaining the neurons in layer j+1 biases[j][k] is the bias for neuron k in layer j+1 activations is a list of the activation functions for the different layers: choose 'linear','sigmoid', 'jump' (i.e. step-function), and 'reLU' M is the resolution (MxM grid) y0range is the range of y0 neuron values (horizontal axis) y1range is the range of y1 neuron values (vertical axis) """ if not weights_are_swapped: swapped_weights = [] for j in range(len(weights)): swapped_weights.append(np.transpose(weights[j])) else: swapped_weights = weights y0, y1 = np.meshgrid(np.linspace(y0range[0], y0range[1], M), np.linspace(y1range[0], y1range[1], M)) y_in = np.zeros([M * M, 2]) y_in[:, 0] = y0.flatten() y_in[:, 1] = y1.flatten() # if we call visualization directly, we still # need to initialize the 'Weights' and other # global variables; otherwise (during training) # all of this has already been taken care of: if not layers_already_initialized: init_layer_variables(swapped_weights, biases, activations) y_out = apply_net_simple(y_in) if plot_cost_function is None: fig, ax = plt.subplots(ncols=2, nrows=1, figsize=(8, 4)) else: fig = plt.figure(figsize=(8, 4)) gs_top = gridspec.GridSpec(nrows=1, ncols=2) gs_left = gridspec.GridSpecFromSubplotSpec(nrows=2, ncols=1, subplot_spec=gs_top[0], height_ratios=[1.0, 0.3]) ax = [ fig.add_subplot(gs_left[0]), fig.add_subplot(gs_top[1]), fig.add_subplot(gs_left[1]) ] # ax[0] is network # ax[1] is image produced by network # ax[2] is cost function subplot # plot the network itself: # positions of neurons on plot: posX = [[-0.5, +0.5]] posY = [[0, 0]] vmax = 0.0 # for finding the maximum weight vmaxB = 0.0 # for maximum bias for j in range(len(biases)): n_neurons = len(biases[j]) posX.append(np.array(range(n_neurons)) - 0.5 * (n_neurons - 1)) posY.append(np.full(n_neurons, j + 1)) vmax = np.maximum(vmax, np.max(np.abs(weights[j]))) vmaxB = np.maximum(vmaxB, np.max(np.abs(biases[j]))) # plot connections for j in range(len(biases)): for k in range(len(posX[j])): for m in range(len(posX[j + 1])): plot_connection_line(ax[0], [posX[j][k], posX[j + 1][m]], [posY[j][k], posY[j + 1][m]], swapped_weights[j][k, m], vmax=vmax, linewidth=linewidth) # plot neurons for k in range(len(posX[0])): # input neurons (have no bias!) plot_neuron(ax[0], posX[0][k], posY[0][k], vmaxB, vmax=vmaxB, size=size) for j in range(len(biases)): # all other neurons for k in range(len(posX[j + 1])): plot_neuron(ax[0], posX[j + 1][k], posY[j + 1][k], biases[j][k], vmax=vmaxB, size=size) ax[0].axis('off') # now: the output of the network img = ax[1].imshow(np.reshape(y_out, [M, M]), origin='lower', extent=[y0range[0], y0range[1], y1range[0], y1range[1]]) ax[1].set_xlabel(r'$y_0$') ax[1].set_ylabel(r'$y_1$') # axins1 = inset_axes(ax[1], # width="40%", # width = 50% of parent_bbox width # height="5%", # height : 5% # loc='upper right', # bbox_to_anchor=[0.3,0.4]) # axins1 = ax[1].inset_axes([0.5,0.8,0.45,0.1]) axins1 = plt.axes([0, 0, 1, 1]) ip = InsetPosition(ax[1], [0.25, 0.1, 0.5, 0.05]) axins1.set_axes_locator(ip) imgmin = np.min(y_out) imgmax = np.max(y_out) color_bar = fig.colorbar(img, cax=axins1, orientation="horizontal", ticks=np.linspace(imgmin, imgmax, 3)) cbxtick_obj = plt.getp(color_bar.ax.axes, 'xticklabels') plt.setp(cbxtick_obj, color="white") axins1.xaxis.set_ticks_position("bottom") if plot_target is not None: axins2 = plt.axes([0.01, 0.01, 0.99, 0.99]) ip = InsetPosition(ax[1], [0.75, 0.75, 0.2, 0.2]) axins2.set_axes_locator(ip) axins2.imshow(plot_target, origin='lower') axins2.get_xaxis().set_ticks([]) axins2.get_yaxis().set_ticks([]) if plot_cost_function is not None: ax[2].plot(plot_cost_function) ax[2].set_ylim([0.0, cost_max]) ax[2].set_yticks([0.0, cost_max]) ax[2].set_yticklabels(["0", '{:1.2e}'.format(cost_max)]) if current_cost is not None: ax[2].text(0.9, 0.9, 'cost={:1.2e}'.format(current_cost), horizontalalignment='right', verticalalignment='top', transform=ax[2].transAxes) plt.show()
im1 = ax1.imshow(vd, origin="lower", cmap="jet", norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax)) ims = [im0, im1] for i, ax in enumerate([ax0, ax1]): im = ims[i] ax.set_xlim([0.5, hmax - 0.5]) ax.set_ylim([0.5, mmax - 0.5]) ax.set_xticks(np.arange(20, hmax, 20)) ax.set_xlabel("hitpoints") ax.set_yticks(np.arange(20, mmax, 20)) ax1.set_yticklabels([]) ax0.set_ylabel("maximum hit") ip = InsetPosition(ax1, [1.05, 0, 0.05, 1]) cax.set_axes_locator(ip) fig.colorbar(im, cax=cax, ax=[ax0, ax1]) #axes[0,0].set_title("$\\delta\\langle L\\rangle$") #axes[0,1].set_title("$\\delta\\langle R\\rangle$") ax0.set_title("$\\delta v_k$") ax1.set_title("$\\delta v_d$") #axes[0,0].set_xticklabels([]) #axes[0,1].set_xticklabels([]) #axes[0,1].set_yticklabels([]) #axes[1,1].set_yticklabels([]) #axes[1,0].set_xlabel("hitpoints") #axes[0,0].set_ylabel("maximum hit") #fig.savefig('test.pdf', bbox_inches='tight', pad_inches=0.1) fig.savefig('mhErrors.pdf', bbox_inches='tight', pad_inches=0.1)
#Load data files wdir = ('T-runs/Tl/', 'T-runs/Th/', 'B-runs/Bl/', 'B-runs/Bh/', 'T-runs/TDh/', 'B-runs/BDh/', 'Q-run/', 'B-runs/BDh2/') labels = ('Tl', 'Th', 'Bl', 'Bh', 'TDh', 'BDh', 'QD', 'BDh2') colors = ((230, 25, 75), (60, 180, 75), (255, 225, 25), (0, 130, 200), (245, 130, 48), (145, 30, 180), (183, 58, 12), (240, 50, 230), (250, 190, 190), (6, 71, 24)) colors = np.array(colors) / 255. fig, ax = plt.subplots() box = ax.get_position() ax.set_position([box.x0, box.y0, box.width, box.height]) axins = plt.axes([0, 0, 1, 1]) ip = InsetPosition(ax, [0.1, 0.1, 0.5, 0.3]) axins.set_axes_locator(ip) fig.set_size_inches(6, 5) for i1 in xrange(0, no_files): filedir = '/mnt/lustre/phy/phyprtek/RAJ_RUNS/cooling_data/' + wdir[i1] file = filedir + 'pluto_hst.out' data = np.loadtxt(file, skiprows=1, usecols=(0, 13)) ax.plot(data[:, 0] * UNIT_TIME, data[:, 1], label=labels[i1], color=colors[i1]) axins.plot(data[:, 0] * UNIT_TIME, data[:, 1], label=labels[i1], color=colors[i1]) ax.set_xlabel(r'time (Myr)', fontsize=18)
def attributes_diagram(rel_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Forecast Probability", ylabel="Observed Relative Frequency", ticks=np.arange(0, 1.05, 0.05), dpi=300, title="Attributes Diagram", legend_params=None, inset_params=None, inset_position=(0.12, 0.72, 0.25, 0.25), bootstrap_sets=None, ci=(2.5, 97.5)): """ Plot reliability curves against a 1:1 diagonal to determine if probability forecasts are consistent with their observed relative frequency. Also adds gray areas to show where the climatological probabilities lie and what areas result in a positive Brier Skill Score. Args: rel_objs (list): List of DistributedReliability objects. obj_labels (list): List of labels describing the forecast model associated with each curve. colors (list): List of colors for each line markers (list): List of line markers filename (str): Where to save the figure. figsize (tuple): (Width, height) of the figure in inches. xlabel (str): X-axis label ylabel (str): Y-axis label ticks (`numpy.ndarray`): Tick value labels for the x and y axes. dpi (int): resolution of the saved figure in dots per inch. title (str): Title of figure legend_params (dict): Keyword arguments for the plot legend. inset_params (dict): Keyword arguments for the inset axis. inset_position (tuple): Position of the inset axis in normalized axes coordinates (left, bottom, width, height) bootstrap_sets (list): A list of arrays of bootstrapped DistributedROC objects. If not None, confidence regions will be plotted. ci (tuple): tuple of bootstrap confidence interval percentiles """ if legend_params is None: legend_params = dict(loc=4, fontsize=10, framealpha=1, frameon=True) if inset_params is None: inset_params = dict(width="25%", height="25%", loc=2, axes_kwargs=dict(facecolor='white')) fig, ax = plt.subplots(figsize=figsize) plt.plot(ticks, ticks, "k--") inset_hist = inset_axes(ax, **inset_params) ip = InsetPosition(ax, inset_position) inset_hist.set_axes_locator(ip) climo = rel_objs[0].climatology() no_skill = 0.5 * ticks + 0.5 * climo skill_x = [climo, climo, 1, 1, climo, climo, 0, 0, climo] skill_y = [climo, 1, 1, no_skill[-1], climo, 0, 0, no_skill[0], climo] f = ax.fill(skill_x, skill_y, "0.8") f[0].set_zorder(1) ax.plot(ticks, np.ones(ticks.shape) * climo, "k--") if bootstrap_sets is not None: for b, b_set in enumerate(bootstrap_sets): brel_curves = np.vstack([ b_rel.reliability_curve()["Positive_Relative_Freq"].values for b_rel in b_set ]) rel_range = np.nanpercentile(brel_curves, ci, axis=0) fb = ax.fill_between(b_set[0].thresholds[:-1], rel_range[1], rel_range[0], alpha=0.5, color=colors[b]) fb.set_zorder(2) for r, rel_obj in enumerate(rel_objs): rel_curve = rel_obj.reliability_curve() ax.plot(rel_curve["Bin_Start"], rel_curve["Positive_Relative_Freq"], color=colors[r], marker=markers[r], label=obj_labels[r]) inset_hist.semilogy(rel_curve["Bin_Start"] * 100, rel_obj.frequencies["Total_Freq"][:-1], color=colors[r], marker=markers[r]) inset_hist.set_xlabel("Forecast Probability") inset_hist.set_ylabel("Frequency") ax.annotate("No Skill", (0.6, no_skill[12]), rotation=22.5) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_xticks(ticks) ax.set_xticklabels((ticks * 100).astype(int)) ax.set_yticks(ticks) ax.set_yticklabels((ticks * 100).astype(int)) ax.legend(**legend_params) ax.set_title(title) plt.savefig(filename, dpi=dpi, bbox_inches="tight") plt.close()
def main(unused_argv): # Load datasets athenafile = "/home/rummelm/local_files/resid_Athena_2.csv" full_set = pd.read_csv(athenafile, skiprows=1) num_resid = full_set.shape[1] - 1 # Read out feature columns from csv file COLUMNS = [] for i in range(num_resid): COLUMNS.append("Resid" + str(i + 1)) FEATURES = COLUMNS COLUMNS.append("gval") FEATURES = FEATURES[:-1] LABEL = "gval" # Define full set full_set = pd.read_csv(athenafile, skiprows=1, names=COLUMNS) # option to only use fraction of shuffled entries fracuse = 1.0 full_set = full_set.sample(frac=fracuse) num_rows = full_set.shape[0] #print(full_set) #sys.exit(0) # split full_set into training set and test set split_testtrain = int(0.75 * num_rows) training_set = full_set[:split_testtrain].reset_index(drop=True) test_set = full_set[split_testtrain:].reset_index(drop=True) # Feature cols feature_cols = [tf.contrib.layers.real_valued_column(k) for k in FEATURES] # Build the Estimator for linear regression #model = tf.estimator.LinearRegressor(feature_columns=feature_cols) # Build a DNNRegressor, with 2x"nodes"-unit hidden layers, with the feature columns # defined above as input. nodes = 200 model = tf.estimator.DNNRegressor(hidden_units=[nodes, nodes], feature_columns=feature_cols) # Train the model. # By default, the Estimators log output every 100 steps. model.train(input_fn=lambda: input_fn(training_set, FEATURES, LABEL), steps=10000) #model.train(input_fn=lambda: input_fn(training_set, FEATURES, LABEL), steps=100) # Evaluate how the model performs on data it has not yet seen. eval_result = model.evaluate( input_fn=lambda: input_fn(test_set, FEATURES, LABEL), steps=1) #sys.exit(0) # test predictions more detailed: save predicted values for g # all actual values of the label g in the test set gval_testvalues = test_set.drop(COLUMNS[:-1], axis=1) # test set without labels test_set_nolabel = test_set.drop(columns='gval') # length of test set ntest = len(test_set_nolabel) # predictions for g from the above gval_testpredictions = model.predict( input_fn=lambda: input_fn_pred(test_set_nolabel, FEATURES)) gval_testpredictionsislice = list( itertools.islice(gval_testpredictions, ntest)) # store in list gval_testpredlist = [] for entry in gval_testpredictionsislice: gval_testpredlist.append(entry["predictions"][0]) # Find what values of g are being used gvals = [] for i in range(len(gval_testvalues)): gval = gval_testvalues.loc[i][0] if not gval in gvals: gvals.append(gval) gvals = np.sort(gvals) # calculate loss by hand losshand = 0. for i in range(ntest): losshand += (gval_testvalues.loc[i][0] - gval_testpredlist[i])**2 print("loss calculated by hand: " + str(losshand)) # Produce histograms and percentiles for predicted g values for each actual value of g percentiles = [] for g in gvals: gpreds = [] for i in range(ntest): if gval_testvalues.loc[i][0] == g: gpreds.append(gval_testpredlist[i]) # make histograms plt.hist(gpreds, bins='auto') plt.title("g = " + str(g) + "e-13") plt.savefig("histo_Athena_" + str(g) + ".pdf", bbox_inches='tight') plt.clf() # calculate percentiles if g == 0.: gperc = np.percentile(gpreds, 95) else: gperc = np.percentile(gpreds, 5) percentiles.append(gperc) print([g, gperc]) # Plot g vs 5% of DNN predicted values for g fig, ax1 = plt.subplots() #plt.rc('text', usetex=True) ax1.loglog(gvals[1:], percentiles[1:], 'bo', [0.5, 1500]) ax1.set_xlim(0.05, 150.) #ax1.set_ylim(0.1,200) ax1.axhline(y=percentiles[0], color='red', linestyle='--') ax1.set_xlabel(r'$g\, [10^{-13}\, {\rm GeV}^{-1}]$', fontsize=16) ax1.set_ylabel(r'$G_{\rm DNN}(\mathcal{F}_{i,{\rm sim}}\,|\,g)$', fontsize=18) ax1.annotate( r'$95\% \, {\rm of}\, G_{\rm DNN}(\mathcal{F}_{i,{\rm sim}}\,|\,g=0)$', xy=(0.06, 1.1 * percentiles[0]), fontsize=12, color='red') ax2 = plt.axes([0, 0, 1, 1]) ip = InsetPosition(ax1, [0.1, 0.45, 0.45, 0.5]) ax2.set_axes_locator(ip) mark_inset(ax1, ax2, loc1=2, loc2=1, fc="none", ec='0.5') #ax2.loglog(gvals[1:], percentiles[1:], 'bo', [0.5,1500]) ax2.loglog(gvals[6:10], percentiles[6:10], 'bo', [0.5, 1500]) ax2.axhline(y=percentiles[0], color='red', linestyle='--') ax2.set_xlim(2.5, 6.5) ax2.set_ylim(0.3, 5.3) fig.savefig("Athena_05percentile.pdf", bbox_inches='tight')
def state_sum(csv): cdf = read_csv(csv) df = cdf.groupby(['State', 'State_Code'])[[ 'IM2002_ac', 'NASS_2002_ac', 'IM2007_ac', 'NASS_2007_ac', 'IM2012_ac', 'NASS_2012_ac' ]].sum() fig, ax = plt.subplots(1, 1) s = Series(index=df.index) s.loc[0], s.loc[df.shape[0]] = 0, 1e8 s.interpolate(axis=0, inplace=True) s.index = s.values s.plot(x=s.values, ax=ax, kind='line', lw=1, loglog=True, color='k', style='--', alpha=0.5) df_state = df.groupby(['State', 'State_Code'])[[ 'IM2002_ac', 'NASS_2002_ac', 'IM2007_ac', 'NASS_2007_ac', 'IM2012_ac', 'NASS_2012_ac' ]].sum() s = Series(index=df_state.index) s.loc[0], s.loc[df_state.shape[0]] = 1e6, 1e7 s.interpolate(axis=0, inplace=True) s.index = s.values ax2 = fig.add_axes([0, 0, 1, 1]) ax2.xaxis.label.set_visible(False) ax2.yaxis.label.set_visible(False) ax.text(0.26, 0.62, 'States', transform=ax.transAxes, ha="right") df_state.plot(x='NASS_{}_ac'.format(2002), y='IM{}_ac'.format(2002), kind='scatter', s=4, xlim=(1e6, 1e7), ylim=(1e6, 1e7), ax=ax2, loglog=True, color='g') df_state.plot(x='NASS_{}_ac'.format(2007), y='IM{}_ac'.format(2007), kind='scatter', s=4, xlim=(1e6, 1e7), ylim=(1e6, 1e7), ax=ax2, loglog=True, color='b') df_state.plot(x='NASS_{}_ac'.format(2012), y='IM{}_ac'.format(2012), kind='scatter', s=4, xlim=(1e6, 1e7), ylim=(1e6, 1e7), ax=ax2, loglog=True, color='r') s.plot(x=s.values, kind='line', lw=1, loglog=True, color='k', style='--', alpha=0.5, label='_nolegend_') ip = InsetPosition(ax, [0.07, 0.67, 0.3, 0.3]) ax2.set_axes_locator(ip) plt.show() return plt
AX3LIM = 0.995 ax2 = plt.axes([0, 0, 1, 1], label='inset1') ax2.set_xlim(AX2LIM, 1) ax2.set_ylim(AX2LIM, 1) ax3 = plt.axes([0, 0, 1, 1], label='inset2') ax3.set_xlim(AX3LIM, 1) ax3.set_ylim(AX3LIM, 1) ax2.set_xticklabels(ax2.get_xticks(), backgroundcolor='w', fontsize=8 - 1) ax2.set_yticklabels(ax2.get_yticks(), backgroundcolor='w', fontsize=8 - 1) ax3.set_xticklabels(ax3.get_xticks(), backgroundcolor='w', fontsize=8 - 2) ax3.set_yticklabels(ax3.get_yticks(), backgroundcolor='w', fontsize=8 - 2) ip1 = InsetPosition(ax1, [0.2, 0.4, 0.5, 0.5]) ax2.set_axes_locator(ip1) ip2 = InsetPosition(ax2, [0.2, 0.4, 0.5, 0.5]) ax3.set_axes_locator(ip2) #mark_inset(ax1, ax2, loc1=2, loc2=4, fc="none", ec='0.5') is_inset1_marked = False #True is_inset2_marked = False #True #fig, ax = plt.subplots() fidx = 0 str_base_vars = '' str_vartype = '' uvc_version = ''
# Plot g vs 5% of Delta chi^2 fig, ax1 = plt.subplots() #plt.rc('text', usetex=True) ax1.loglog(gvals, chisq05, 'bo', [0.5, 1500]) ax1.set_xlim(0.05, 150.) ax1.set_ylim(900, 110000) ax1.axhline(y=chisq95excl_g0, color='red', linestyle='--') ax1.set_xlabel(r'$g\, [10^{-13}\, {\rm GeV}^{-1}]$', fontsize=16) ax1.set_ylabel('$\chi^2_0$', fontsize=18) ax1.annotate(r'$95\% \, {\rm of}\, [\chi^2_0(g=0)]$', xy=(0.1, 1.1 * chisq95excl_g0), fontsize=12, color='red') ax2 = plt.axes([0, 0, 1, 1]) ip = InsetPosition(ax1, [0.13, 0.4, 0.5, 0.5]) ax2.set_axes_locator(ip) mark_inset(ax1, ax2, loc1=2, loc2=1, fc="none", ec='0.5') ax2.loglog(gvals, chisq05, 'bo', [0.5, 1500]) ax2.axhline(y=chisq95excl_g0, color='red', linestyle='--') ax2.set_xlim(3.5, 11.) ax2.set_ylim(1200, 4000) fig.savefig(file0[:-4] + "_05percentile.pdf", bbox_inches='tight') ############### new methods ################ files = [ "g_chisq_Fourier_E2weighting_" + str(instrument) + "_run" + str(run) + ".txt", "g_chisq_Fit_" + str(instrument) + "_run" + str(run) + ".txt" ] for file in files:
def graficoBase(self): self.taxaDes, self.amazonRaio, self.amazonCoord, self.amazonEmiss, self.DesmAcum = self.getDatas() self.ax = self.figure.add_subplot(2, 3, (1,5), projection=ccrs.PlateCarree()) self.anoText = self.ax.text(-38, 5.7, "", size=20, ha="center", va="center", color="white", bbox=dict(boxstyle="round", ec='white', fc=(0.59375 , 0.71484375, 0.8828125) ) ) ##Gráfico de Desmatamento self.axDes = plt.axes([0,0,1,1], facecolor=[ 0.59375 , 0.71484375, 0.8828125 ]) width = 1/1.5 self.axDes.bar(['Desma'], .2, align='center', color=['red'], ecolor='black', alpha=.5) self.axDes.set_xticks([]) self.axDes.set_yticks([]) self.axDes.spines['bottom'].set_color('white') self.axDes.spines['top'].set_color('white') self.axDes.spines['right'].set_color('white') self.axDes.spines['left'].set_color('white') ip = InsetPosition(self.ax, [0.85,.05,.05,.85]) self.axDes.set_axes_locator(ip) ##Gráfico de Emissão CO2 self.axEmiss = plt.axes([1,1,1,1], facecolor=[ 0.59375 , 0.71484375, 0.8828125 ]) width = 1/1.5 self.axEmiss.bar(['Emissao'], .2, align='center', color=['yellow'], ecolor='black', alpha=.8) self.axEmiss.set_xticks([]) self.axEmiss.set_yticks([]) self.axEmiss.tick_params(axis='y', labelsize=6) self.axEmiss.yaxis.tick_left() self.axEmiss.spines['bottom'].set_color('white') self.axEmiss.spines['top'].set_color('white') self.axEmiss.spines['right'].set_color('white') self.axEmiss.spines['left'].set_color('white') ip = InsetPosition(self.ax, [0.80,.05,.05,.85]) self.axEmiss.set_axes_locator(ip) ##Gráfico Linhas self.axLinhas = self.figure.add_subplot(2, 3, 3) self.axLinhas.axis('off') self.axLinhasEmiss = self.axLinhas.twinx() self.axLinhasEmiss.axis('off') self.axScatter = self.figure.add_subplot(2, 3, 6) self.axScatter.axis('off') ##Mapa Brasil e Amazônia Legal self.ax.set_title('The Brazilian Legal Amazon Deforestation Map', fontsize=11, color='#595959') self.ax.outline_patch.set_edgecolor('#d9d9d9') self.ax.set_extent([-74, -20, 7.7, -35.5], crs=ccrs.PlateCarree()) self.ax.add_feature(cfeature.LAND) self.ax.add_feature(cfeature.OCEAN) self.ax.add_feature(cfeature.COASTLINE) self.ax.add_feature(cfeature.BORDERS, linestyle='-') self.ax.add_feature(cfeature.LAKES) self.ax.add_feature(cfeature.RIVERS) lons, lats = self.sample_data() track = sgeom.LineString(list(zip(lons, lats))) states_shp = 'CoordStates/50m_admin_1_states_provinces_lakes_shp.shp' for state in shpreader.Reader(states_shp).geometries(): facecolor = 'none' edgecolor = 'none' if state.intersects(track): edgecolor = 'gray' self.ax.add_geometries([state], ccrs.PlateCarree(), facecolor=facecolor, edgecolor=edgecolor, alpha = .3) amazon_shp = 'CoordAmazon/amazlegal.shp' for state in shpreader.Reader(amazon_shp).geometries(): facecolor = 'none' edgecolor = 'none' if state.intersects(track): facecolor = 'green' edgecolor = 'olive' self.ax.add_geometries([state], ccrs.PlateCarree(), facecolor=facecolor, edgecolor=edgecolor, alpha = .3) text1 = """The graphs are arranged as follows: - A chart with the map of the Brazilian legal Amazon: In this graph it's possible to follow the total deforestation in each state and the total deforestation of the Brazilian Amazon between 1988 and 2017. And also the rate of deforestation and CO2 emissions in each year.\n""" text2 = """ - A red line plot showing the evolution of the annual deforestation rate and a yellow line showing the evolution of the carbon dioxide emission rate due to deforestation.\n""" text3 = """ - A scatter diagram with the x-axis the deforestation rate and the y-axis CO2 emission rate.\n""" text4 = """ Please, press play or any year button below! """ text = text1+text2+text3+text4 self.descricaoText = self.figure.text(.4, .4, text, size='medium',#stretch="ultra-condensed", ha="left", va="baseline", color="#595959", bbox=dict(boxstyle="round", ec='#d9d9d9', fc='white'#(0.59375 , 0.71484375, 0.8828125) ) )
res_error.append(data['error'][0]) titles = ['(a)', '(b)', '(c)', '(d)', '(e)', '(f)', '(g)', '(h)', '(i)'] m_s = 6 x_ticks = [0, 0.04, 0.08, 0.12, 0.16] x_ticks2 = [0, 0.16] res_fig = plt.figure() for i in range(0, len(length)): ax = plt.subplot(3, 3, i + 1) if i == 1: fill_temp = np.delete(fill_factor, 7) res_temp = np.delete(all_res[i], [7, 9, 10]) err_temp = np.delete(res_error[i], [7, 9, 10]) ax.errorbar(fill_temp, res_temp, yerr=err_temp, fmt='o', ms=m_s) ax2 = inset_axes(ax, width="30%", height=1, loc=2) ip = InsetPosition(ax, [0.18, 0.62, 0.4, 0.3]) ax2.errorbar(fill_factor, all_res[i][:len(fill_factor)], yerr=res_error[i][:len(fill_factor)], fmt='o') ax2.set_axes_locator(ip) ax2.xaxis.set_ticks(x_ticks2) ax2.yaxis.set_ticks([0, 15, 30]) ax2.set_xlim(-0.01, 0.17) elif i == 8: fill_temp = np.delete(fill_factor, 4) res_temp = np.delete(all_res[i], 4) err_temp = np.delete(res_error[i], 4) ax.errorbar(fill_temp, res_temp, yerr=err_temp, fmt='o', ms=m_s) ax2 = inset_axes(ax, width="30%", height=1, loc=2) ip = InsetPosition(ax, [0.18, 0.62, 0.4, 0.3])
plt.ylim([ext[2], ext[3]]) plt.xticks([1205923., 1600000., 1994077.]) ax.set_xticklabels(['168.0$^\circ$E', '173.0$^\circ$E', '178.0$^\circ$E']) plt.yticks([5004874., 5560252., 6115515.]) ax.set_yticklabels(['45.0$^\circ$S', '40.0$^\circ$S', '35.0$^\circ$S']) divider = make_axes_locatable(ax) cax = divider.append_axes('bottom', size='3%', pad=0.35) cb = plt.colorbar(im, orientation='horizontal', cax=cax, ticks=np.arange(vmin, b_dict[IM_name][1] + 0.00001, b_dict[IM_name][1] / 5.)) cb.ax.set_xlabel(str_lbl[IM_name]) iax_p = plt.axes([0, 0, 0, 0]) ip_p = InsetPosition(ax, [0.05, 0.66, 0.35, 0.27]) #posx, posy, width, height iax_p.set_axes_locator(ip_p) iax_p.hist(res_h, color='grey', bins=8) iax_p.spines['right'].set_visible(False) iax_p.spines['top'].set_visible(False) iax_p.spines['left'].set_visible(False) iax_p.set_yticks([]) iax_p.set_xlim([-2, 2]) str_metric = '$\mu$ = ' + str(round( np.mean(res_h), 2)) + ', $\sigma$ = ' + str(round(np.std(res_h), 2)) ax.text(ext[0] + 25000, ext[3] - 50000, str_metric) plt.tight_layout() plt.savefig(str_file, dpi=600) plt.close('all')