def plot_surface(spectra, dimension1, dimension2, fig_num=1, show_plot=True, **kwargs): """ Plot the two dimensions from spectra as a 2D histogram Args: spectra (:class:`echidna.core.spectra`): The spectra to plot. dimension1 (string): The name of the dimension you want to plot. dimension2 (string): The name of the dimension you want to plot. Returns: matplotlib.pyplot.figure: Plot of the surface of the two dimensions. """ fig = plt.figure(num=fig_num) axis = fig.add_subplot(111) index1 = spectra.get_config().get_index(dimension1) index2 = spectra.get_config().get_index(dimension2) if index1 < index2: x = _produce_axis(spectra, dimension2) y = _produce_axis(spectra, dimension1) else: x = _produce_axis(spectra, dimension1) y = _produce_axis(spectra, dimension2) data = spectra.surface(dimension1, dimension2) par1 = spectra.get_config().get_par(dimension1) par2 = spectra.get_config().get_par(dimension2) if index1 < index2: axis.set_xlabel("%s (%s)" % (dimension2, par2.get_unit())) axis.set_ylabel("%s (%s)" % (dimension1, par1.get_unit())) else: axis.set_xlabel("%s (%s)" % (dimension1, par1.get_unit())) axis.set_ylabel("%s (%s)" % (dimension2, par2.get_unit())) # `plot_surface` expects `x` and `y` data to be 2D X, Y = numpy.meshgrid(x, y) # Set sensible levels, pick the desired colormap and define normalization if kwargs.get("color_scheme") is None: color_scheme = "hot_r" # default else: color_scheme = kwargs.get("color_scheme") color_map = plt.get_cmap(color_scheme) linear = numpy.linspace(numpy.sqrt(data.min()), numpy.sqrt(data.max()), num=100) locator = FixedLocator(linear**2) levels = locator.tick_values(data.min(), data.max()) norm = BoundaryNorm(levels, ncolors=color_map.N) # Plot color map color_map = axis.pcolormesh(X, Y, data, cmap=color_map, norm=norm) color_bar = fig.colorbar(color_map) color_bar.set_label("Counts per bin") if show_plot: plt.show() return fig
def set_latitude_grid(self, degrees): """ Set the number of degrees between each latitude grid. """ # Skip -90 and 90, which are the fixed limits. grid = np.arange(-90 + degrees, 90, degrees) self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid))) self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))
def plot_reference(fig, reference, simdata, x, y, style='-o', color='#8DC63F', alpha=1, linewidth=1) : from matplotlib.ticker import FixedLocator ax = fig.gca() numpoints = len(simdata[x]) ax.plot(range(numpoints), reference['risks'] + [reference['prevalence']], style, color=color, alpha=alpha, linewidth=linewidth) ax.xaxis.set_major_locator(FixedLocator(range(numpoints))) ax.set_xticklabels(['hh'] + [str(i) for i in reference['distances'][1:]] + ['all']) ax.set(xlabel=x, ylabel=y)
def set_longitude_grid(self, degrees): # Copied from matplotlib.geo.GeoAxes.set_longitude_grid and modified number = (360.0 / degrees) + 1 self.xaxis.set_major_locator( FixedLocator( np.linspace(0, 2*np.pi, number, True)[1:-1])) self._longitude_degrees = degrees self.xaxis.set_major_formatter(self.RaFormatter(degrees))
def set_longitude_grid(self, degrees): """ Set the number of degrees between each longitude grid. """ number = (360.0 / degrees) + 1 self.xaxis.set_major_locator( FixedLocator(np.linspace(-np.pi, np.pi, number, True)[1:-1])) self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))
def main(amb_fname, ele_fname): df_a = read_cable_file(amb_fname) df_a = resample_to_seasonal_cycle(df_a) df_e = read_cable_file(ele_fname) df_e = resample_to_seasonal_cycle(df_e) fig = plt.figure(figsize=(8, 6)) fig.subplots_adjust(hspace=0.3) fig.subplots_adjust(wspace=0.2) plt.rcParams['text.usetex'] = False plt.rcParams['font.family'] = "sans-serif" plt.rcParams['font.sans-serif'] = "Helvetica" plt.rcParams['axes.labelsize'] = 12 plt.rcParams['font.size'] = 12 plt.rcParams['legend.fontsize'] = 12 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 12 ax1 = fig.add_subplot(3, 2, 1) ax2 = fig.add_subplot(3, 2, 2) ax3 = fig.add_subplot(3, 2, 3) ax4 = fig.add_subplot(3, 2, 4) ax5 = fig.add_subplot(3, 2, 5) ax6 = fig.add_subplot(3, 2, 6) axes = [ax1, ax2, ax3, ax4, ax5, ax6] vars = ["GPP", "CO2air", "Qle", "LAI", "TVeg", "ESoil"] for a, v in zip(axes, vars): a.plot(df_a.month, df_a[v], c="blue", lw=2.0, ls="-", label="AMB") a.plot(df_e.month, df_e[v], c="red", lw=2.0, ls="-", label="ELE") labels = ["GPP (g C m$^{-2}$ d$^{-1}$)", \ "CO$_2$ ($\mathrm{\mu}$mol mol$^{-1}$)",\ "Qle (W m$^{-2}$)", "LAI (m$^{2}$ m$^{-2}$)",\ "TVeg (mm d$^{-1}$)", "Esoil (mm d$^{-1}$)"] for a, l in zip(axes, labels): a.set_title(l, fontsize=12) xtickagaes_minor = FixedLocator([2, 3, 4, 5, 7, 8, 9, 10, 11]) for i, a in enumerate(axes): a.set_xticks([1, 6, 12]) if i != 1: a.set_ylim(ymin=0) a.xaxis.set_minor_locator(xtickagaes_minor) a.set_xticklabels(['Jan', 'Jun', 'Dec']) if i < 4: plt.setp(a.get_xticklabels(), visible=False) ax1.legend(numpoints=1, loc="best") plot_fname = "seasonal_plot_gw_off_amb_vs_ele_standard_para.png" plot_dir = "plots" if not os.path.exists(plot_dir): os.makedirs(plot_dir) fig.savefig(os.path.join(plot_dir, plot_fname), bbox_inches='tight', pad_inches=0.1)
def _plot_ir(data, *, model_name_string, figname): # plot for income and region _data = data.copy().sort_values( by=["trname", "archname", "sz", "income bucket", "region"], ascending=False ) _data["new_model_name"] = _data.apply( lambda x: model_name_string.format(**x.to_dict()), axis=1 ) fig, ax = plt.subplots(1, 2, figsize=(8, 4)) seaborn.lineplot( data=_data, x="income bucket", y="hit", hue="new_model_name", style="new_model_name", ax=ax[0], ) seaborn.lineplot( data=_data, x="region", y="hit", hue="new_model_name", style="new_model_name", ax=ax[1], ) for i in range(2): ax[i].legend_.set_title(None) # set axis limits mini, maxi = ax[i].get_ylim() print(mini, maxi) if maxi - floor(10 * maxi) / 10 >= 0.05: maxi = ceil(maxi * 10) / 10 ax[i].set_ylim(mini, maxi) ax[i].yaxis.set_major_locator(FixedLocator([x / 10 for x in range(11)])) ax[i].legend(loc="lower right") ax[i].grid(which="major", color="#d3d3d3", linestyle="dotted", linewidth=1) fig.tight_layout() fig.savefig(figname) # display dataframes side by side ldf = [ _data.groupby(["income bucket", "new_model_name"])["hit"].mean().reset_index(), _data.groupby(["region", "new_model_name"])["hit"].mean().reset_index(), ] display_html( ("\xa0" * 10).join( [ df.style.set_table_attributes("style='display:inline'")._repr_html_() for df in ldf ] ), raw=True, )
def hmm_matrix(matrix, xticks=None, yticks=None, text=None, axes=None, cmap=None, xlabel=None): if axes is None: fig = plt.figure() axes = fig.add_subplot(1, 1 ,1) axes.set_aspect('equal') axes.set_frame_on(True) if xlabel is not None: axes.set_xlabel(xlabel) if text is not None: axes.text(matrix.shape[1]/2.0, -3, text, fontsize=12, horizontalalignment='center') axes.matshow(matrix, cmap=cm.Greens) if xticks is not None: axes.xaxis.set_major_locator(FixedLocator(range(matrix.shape[1]))) axes.set_xticklabels(xticks, rotation=45, size=8) else: axes.xaxis.set_major_locator(NullLocator()) if yticks is not None: axes.yaxis.set_major_locator(FixedLocator(range(matrix.shape[0]))) axes.set_yticklabels(yticks, rotation=45, size=8) else: axes.yaxis.set_major_locator(NullLocator()) axes.grid(False) def color(value): if value < 0.5: return (0.0, 0.0, 0.0, 1.0) else: return (1.0, 1.0, 1.0, 1.0) idx = ((i, j) for i in xrange(matrix.shape[1]) for j in xrange(matrix.shape[0])) for i, j in idx: axes.text(i, j, '%.2f' %(matrix[j, i]), horizontalalignment='center', verticalalignment='center', fontsize=7, color=color(matrix[j, i])) return axes.get_figure()
def _set_tick_labels(ax, x, y): nint = lambda val: ceil(val) if val >= 0 else floor(val) xmin, xmax = np.min(x), np.max(x) ymin, ymax = np.min(y), np.max(y) xmin_log = nint(log10(xmin)) xmax_log = nint(log10(xmax)) ymin_log = nint(log10(ymin)) ymax_log = nint(log10(ymax)) nx = abs(xmax_log - xmin_log) + 1 ny = abs(ymax_log - ymin_log) + 1 # Set the ticks on the x-axis xticks_major = np.linspace(xmin_log, xmax_log, nx) xticks_minor = [ log10(i * 10**j) for i in range(1, 10) for j in xticks_major ] xlabels = [r'$10^{' + f'{int(i)}' + '}$' for i in xticks_major] xticks_major_locator = FixedLocator(xticks_major) xticks_minor_locator = FixedLocator(xticks_minor) xlabels_formatter = FixedFormatter(xlabels) ax.xaxis.set_major_locator(xticks_major_locator) ax.xaxis.set_minor_locator(xticks_minor_locator) ax.xaxis.set_major_formatter(xlabels_formatter) ax.set_xlim(xmin_log, xmax_log) # Set the ticks on the y-axis yticks_major = np.linspace(ymin_log, ymax_log, ny) yticks_minor = [ log10(i * 10**j) for i in range(1, 10) for j in yticks_major ] ylabels = [r'$10^{' + f'{int(i)}' + '}$' for i in yticks_major] yticks_major_locator = FixedLocator(yticks_major) yticks_minor_locator = FixedLocator(yticks_minor) ylabels_formatter = FixedFormatter(ylabels) ax.yaxis.set_major_locator(yticks_major_locator) ax.yaxis.set_minor_locator(yticks_minor_locator) ax.yaxis.set_major_formatter(ylabels_formatter) ax.set_ylim(ymin_log, ymax_log)
def set_default_locators_and_formatters(self, axis): """ Set the locators and formatters to specialized versions for log scaling. """ axis.set_major_locator(FixedLocator(self._get_probs(1e10))) axis.set_major_formatter(FuncFormatter(ProbFormatter())) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter())
def set_default_locators_and_formatters(self, axis): class DegreeFormatter(Formatter): def __call__(self, x, pos=None): return "%d\N{DEGREE SIGN}" % np.degrees(x) axis.set_major_locator(FixedLocator(np.radians(np.arange(-90, 90, 10)))) axis.set_major_formatter(DegreeFormatter()) axis.set_minor_formatter(DegreeFormatter())
def plot_xtick_format(calendar, minDays, maxDays, maxXTicks, yearStride=None): ''' Formats tick labels and positions along the x-axis for time series / index plots Parameters ---------- calendar : str the calendar to use for formatting the time axis minDays : float start time for labels maxDays : float end time for labels maxXTicks : int the maximum number of tick marks to display, used to sub-sample ticks if there are too many yearStride : int, optional the number of years to skip over between ticks ''' # Authors # ------- # Xylar Asay-Davis ax = plt.gca() start = days_to_datetime(np.amin(minDays), calendar=calendar) end = days_to_datetime(np.amax(maxDays), calendar=calendar) if yearStride is not None or end.year - start.year > maxXTicks/2: if yearStride is None: yearStride = 1 else: maxXTicks = None major = [date_to_days(year=year, calendar=calendar) for year in np.arange(start.year, end.year+1, yearStride)] formatterFun = partial(_date_tick, calendar=calendar, includeMonth=False) else: # add ticks for months major = [] for year in range(start.year, end.year+1): for month in range(1, 13): major.append(date_to_days(year=year, month=month, calendar=calendar)) formatterFun = partial(_date_tick, calendar=calendar, includeMonth=True) ax.xaxis.set_major_locator(FixedLocator(major, maxXTicks)) ax.xaxis.set_major_formatter(FuncFormatter(formatterFun)) plt.setp(ax.get_xticklabels(), rotation=30) plt.autoscale(enable=True, axis='x', tight=True)
def plot_label(ax, df): dates = [base.strDate2num(each) for each in df.date] years = set([d.year for d in dates]) mdindex = [] for y in sorted(years): months = set([d.month for d in dates if d.year == y]) for m in sorted(months): monthday = min( [dt for dt in dates if dt.year == y and dt.month == m]) mdindex.append(dates.index(monthday)) xMajorLocator = FixedLocator(np.array(mdindex)) def x_major_formatter(idx, pos=None): return dates[int(idx)].strftime('%Y-%m-%d') xMajorFormatter = FuncFormatter(x_major_formatter) ax.xaxis.set_major_locator(xMajorLocator) ax.xaxis.set_major_formatter(xMajorFormatter) wdindex = {} for d in dates: isoyear, weekno = d.isocalendar()[0:2] dmark = isoyear * 100 + weekno if dmark not in wdindex: wdindex[dmark] = dates.index(d) xMinorLocator = FixedLocator(np.array(sorted(wdindex.values()))) def x_minor_formatter(idx, pos=None): return dates[int(idx)].strftime("%m-%d") xMinorFormatter = FuncFormatter(x_minor_formatter) ax.xaxis.set_minor_locator(xMinorLocator) ax.xaxis.set_minor_formatter(xMinorFormatter) for malabel in ax.get_xticklabels(minor=False): malabel.set_fontsize(12) malabel.set_horizontalalignment('right') malabel.set_rotation('45') for milabel in ax.get_xticklabels(minor=True): milabel.set_fontsize(10) milabel.set_color('blue') milabel.set_horizontalalignment('right') milabel.set_rotation('45')
def set_default_locators_and_formatters(self, axis): """ Override to set up the locators and formatters to use with the scale. This is only required if the scale requires custom locators and formatters. Writing custom locators and formatters is rather outside the scope of this example, but there are many helpful examples in ``ticker.py``. """ axis.set_major_locator(FixedLocator(self.points))
def figura_bias(df, titulo, colores, leyenda, estilo, ylimit): fig, ax = plt.subplots() for col, color, label, lineaest in zip(df.columns, colores, leyenda, estilo): ax.plot(df.index, df[col], color= color, label=label, ls=lineaest) # Generales del grafico ax.set_title(titulo, fontsize=13) ax.set_xlabel(u'Días de pronóstico', fontsize=11) ax.set_ylabel(u'mm', fontsize=11) # Eje X ax.xaxis.set_major_locator(FixedLocator([1, 5, 10, 15, 20, 25, 30])) ax.xaxis.set_minor_locator(FixedLocator(np.arange(1, 31))) ax.xaxis.grid(which='major') ax.xaxis.grid(which='minor', linestyle=':') # Eje Y ax.set_ylim(ylimit[0], ylimit[1]) ax.yaxis.grid(linestyle='--') plt.tight_layout() # Para que no quede tanto espacio en blanco ax.legend(loc='best') return fig, ax
def set_latitude_grid(self, degrees): """ Set the number of degrees between each longitude grid. """ number = (180.0 / degrees) + 1 self.yaxis.set_major_locator( FixedLocator( npy.linspace(-npy.pi / 2.0, npy.pi / 2.0, number, True)[1:-1])) self._latitude_degrees = degrees self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))
def set_default_locators_and_formatters(self, axis): # axis.set_major_locator(FixedLocator( # nparray([1-10**(-k) for k in range(1+self.nines)]))) # axis.set_major_formatter(FixedFormatter( # [str(1-10**(-k)) for k in range(1+self.nines)])) #majloc = [10**(-1*self.nines)*k for k in range(100) if k >= 90 or k % 10 == 0] majloc = [0.0, 0.9, 0.99] majloc = [round(k, self.nines) for k in majloc] axis.set_major_locator(FixedLocator(nparray(majloc))) axis.set_major_formatter(FixedFormatter([str(k) for k in majloc])) minloc = [ 10**(-1 * self.nines) * k for k in range(100) if k not in [0, 90, 99] and (k > 90 or k % 10 == 0) ] minloc = [round(k, self.nines) for k in minloc] axis.set_minor_locator(FixedLocator(nparray(minloc))) axis.set_minor_formatter(FixedFormatter([str(k) for k in minloc]))
def set_longitude_grid(self, degrees): """ Set the number of degrees between each longitude grid. """ number = (360.0 / degrees) + 1 locs = np.linspace(-np.pi, np.pi, number, True)[1:] locs[-1] -= 0.01 # Workaround for "back" gridlines showing. self.xaxis.set_major_locator(FixedLocator(locs)) self._logitude_degrees = degrees self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))
def main(fname, plot_fname=None): df = read_cable_file(fname) df = resample_to_seasonal_cycle(df) fig = plt.figure(figsize=(6, 9)) fig.subplots_adjust(hspace=0.3) fig.subplots_adjust(wspace=0.2) plt.rcParams['text.usetex'] = False plt.rcParams['font.family'] = "sans-serif" plt.rcParams['font.sans-serif'] = "Helvetica" plt.rcParams['axes.labelsize'] = 12 plt.rcParams['font.size'] = 12 plt.rcParams['legend.fontsize'] = 12 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 12 ax1 = fig.add_subplot(3, 2, 1) ax2 = fig.add_subplot(3, 2, 2) ax3 = fig.add_subplot(3, 2, 3) ax4 = fig.add_subplot(3, 2, 4) ax5 = fig.add_subplot(3, 2, 5) ax6 = fig.add_subplot(3, 2, 6) axes = [ax1, ax2, ax3, ax4, ax5, ax6] vars = ["GPP", "NEE", "Qle", "LAI", "TVeg", "ESoil"] for a, v in zip(axes, vars): a.plot(df.month, df[v], c="black", lw=2.0, ls="-") labels = ["GPP (g C m$^{-2}$ d$^{-1}$)", "NEE (g C m$^{-2}$ d$^{-1}$)",\ "Qle (W m$^{-2}$)", "LAI (m$^{2}$ m$^{-2}$)",\ "TVeg (mm d$^{-1}$)", "Esoil (mm d$^{-1}$)"] for a, l in zip(axes, labels): a.set_title(l, fontsize=12) xtickagaes_minor = FixedLocator([2, 3, 4, 5, 7, 8, 9, 10, 11]) for i, a in enumerate(axes): a.set_xticks([1, 6, 12]) if i != 1: a.set_ylim(ymin=0) a.xaxis.set_minor_locator(xtickagaes_minor) a.set_xticklabels(['Jan', 'Jun', 'Dec']) if i < 4: plt.setp(a.get_xticklabels(), visible=False) if plot_fname is None: plt.show() else: plot_dir = "plots" if not os.path.exists(plot_dir): os.makedirs(plot_dir) fig.savefig(os.path.join(plot_dir, plot_fname), bbox_inches='tight', pad_inches=0.1)
def set_section(self, section_name=None, cell_number=None, direction='y', ax=None, ax_pos=111, ve=1): if ax is None: # TODO ax = self.fig.add_subplot(ax_pos) if section_name is not None: if section_name == 'topography': ax.set_title('Geological map') ax.set_xlabel('X') ax.set_ylabel('Y') extent_val = self.model.grid.topography.extent else: dist = self.model.grid.sections.df.loc[section_name, 'dist'] extent_val = [ 0, dist, self.model.grid.regular_grid.extent[4], self.model.grid.regular_grid.extent[5] ] labels, axname = self._make_section_xylabels( section_name, len(ax.get_xticklabels()) - 2) pos_list = np.linspace(0, dist, len(labels)) ax.xaxis.set_major_locator( FixedLocator(nbins=len(labels), locs=pos_list)) ax.xaxis.set_major_formatter(FixedFormatter((labels))) ax.set(title=section_name, xlabel=axname, ylabel='Z') elif cell_number is not None: _a, _b, _c, extent_val, x, y = self._slice(direction, cell_number)[:-2] ax.set_xlabel(x) ax.set_ylabel(y) else: raise AttributeError if extent_val[3] < extent_val[ 2]: # correct vertical orientation of plot ax.gca().invert_yaxis() aspect = (extent_val[3] - extent_val[2]) / (extent_val[1] - extent_val[0]) / ve print(aspect) ax.set_xlim(extent_val[0], extent_val[1]) ax.set_ylim(extent_val[2], extent_val[3]) ax.set_aspect('equal') return ax
def plot_tot_tdc_calibration(scan_parameters, filename, tot_mean, tot_error=None, tdc_mean=None, tdc_error=None, title="Charge calibration"): fig = Figure() FigureCanvas(fig) ax1 = fig.add_subplot(111) fig.patch.set_facecolor('white') ax1.grid(True) ax1.errorbar(scan_parameters, (tot_mean + 1) * 25.0, yerr=(tot_error * 25.0) if tot_error is not None else None, fmt='o', color='b', label='ToT') ax1.set_ylabel('ToT [ns]') ax1.set_title(title) ax1.set_xlabel('Charge [PlsrDAC]') if tdc_mean is not None: ax1.errorbar(scan_parameters, tdc_mean * 1000.0 / 640.0, yerr=(tdc_error * 1000.0 / 640.0) if tdc_error is not None else None, fmt='o', color='g', label='TDC') ax1.set_ylabel('ToT / TDC [ns]') ax1.legend(loc=0) ax1.set_ylim(ymin=0.0) # second axis with ToT code ax2 = ax1.twinx() ax2.set_ylabel('ToT code') ax2.set_ylim(ax1.get_ylim()) from matplotlib.ticker import IndexLocator, FuncFormatter, NullFormatter, MultipleLocator, FixedLocator def format_fn(tick_val, tick_pos): if tick_val <= 25 * 16: return str(int((tick_val / 25.0) - 1)) else: return '' ax2.yaxis.set_major_formatter(FuncFormatter(format_fn)) ax2.yaxis.set_major_locator( FixedLocator( locs=range(25, 17 * 25, 25) if ax1.get_ylim()[1] < 1000 else [25, 16 * 25])) if not filename: fig.show() elif isinstance(filename, PdfPages): filename.savefig(fig) else: fig.savefig(filename)
def set_nm_ticks(axis, wavelength, xmin, xmax): """ Sets the tick positions and labels for a nanometer x-axes using the given lower & upper limits and the wavelength """ np_nm2a = np.vectorize(partial(get_2t_from_nm, wavelength=wavelength)) def get_tick_labels(a, b): def in_close(value, arr): for val in arr: if np.isclose(value, val): return True return False return ["%g" % val if in_close(val, b) else "" for val in a] minor_ticks_nm, major_ticks_nm, label_ticks_nm = _get_ticks() dmax = min(get_nm_from_2t(xmin, wavelength), 100) #limit this so we don't get an "infinite" scale dmin = get_nm_from_2t(xmax, wavelength) # Extract the part we need: selector = (minor_ticks_nm >= dmin) & (minor_ticks_nm <= dmax) minor_ticks_pos = np_nm2a(minor_ticks_nm[selector]) selector = (major_ticks_nm >= dmin) & (major_ticks_nm <= dmax) major_ticks_pos = np_nm2a(major_ticks_nm[selector]) major_ticks_labels = get_tick_labels(major_ticks_nm[selector], label_ticks_nm) # Set the ticks helper = axis.get_helper() helper.axis.minor.locator = FixedLocator(minor_ticks_pos) helper.axis.minor.formatter = FixedFormatter([""] * len(minor_ticks_pos)) helper.axis.major.locator = FixedLocator(major_ticks_pos) helper.axis.major.formatter = FixedFormatter(major_ticks_labels) pass #end of func
def getMinLocatorAndFormatter(dates): """获取显示分钟线时使用的Major Locator和Major Formatter""" sep = len(dates) / 5 loc = [(i, str(d) if i % sep != 0 else "{}-{}-{} {}:{}".format( d.year, d.month, d.day, d.hour, d.minute)) for i, d in enumerate(dates)] fixed_loc = [i for i in range(len(dates)) if i != 0 and i % sep == 0] month_loc = FixedLocator(fixed_loc) month_fm = FuncFormatter(StockFuncFormatter(dict(loc))) return month_loc, month_fm
def set_default_locators_and_formatters(self, axis): axis.set_major_locator( FixedLocator([0.07, 0.08, 0.1, 0.12, 0.15, 0.2, 0.3, 0.5, 1, 1000])) class StickinessFormatter(Formatter): def __call__(self, x, pos=None): return "%g" % x axis.set_major_formatter(StickinessFormatter()) axis.set_minor_formatter(StickinessFormatter())
def set_longitude_grid(self, degrees): """ Set the number of degrees between each longitude grid. This is an example method that is specific to this projection class -- it provides a more convenient interface to set the ticking than set_xticks would. """ grid = n.linspace(-180, 180, int(360/degrees+1)) self.xaxis.set_major_locator(FixedLocator(n.deg2rad(grid))) self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))
def set_energy_labels(self, stepsize=5): def func(x, pos): return "$" + _n(self.channel2energy(x), precision=3) + "$" formatter = FuncFormatter(func) plt.gca().xaxis.set_major_formatter(formatter) pos = (np.linspace(0, 60, 60 / stepsize + 1) - self._calibration.offset) / self._calibration.slope locator = FixedLocator(pos) plt.gca().xaxis.set_major_locator(locator) plt.xlabel("$ E $ / keV")
def set_latitude_grid(self, degrees): """ Set the number of degrees between each longitude grid. This is an example method that is specific to this projection class -- it provides a more convenient interface than set_yticks would. """ # Skip -90 and 90, which are the fixed limits. grid = np.arange(-90 + degrees, 90, degrees) self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid))) self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))
def PLOT_CP(CPX, XP, ZP, GE=False, save=True, savename='test'): fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(7, 7)) for k in range(len(XP)): ax[0].plot(XP[k], CPX[k], color='#1f77b4', linestyle='--', marker='None') ax[1].plot(XP[k], ZP[k], color='k', linewidth=1.5) fig.tight_layout(h_pad=-12, w_pad=0) #Set limits cprange = np.max(CPX) - np.min(CPX) #Set Ticks multiple = np.around(cprange * 0.2, 0) majorLocatory = MultipleLocator(multiple) majorFormattery = FormatStrFormatter('%.1f') ax[0].yaxis.set_major_locator(majorLocatory) ax[0].yaxis.set_major_formatter(majorFormattery) majorLocatorx = FixedLocator([0.5, 1.0]) majorFormatterx = FormatStrFormatter('%.1f') minorLocatorx = MultipleLocator(0.1) ax[0].xaxis.set_major_locator(majorLocatorx) ax[0].xaxis.set_major_formatter(majorFormatterx) ax[0].xaxis.set_minor_locator(minorLocatorx) ax[0].xaxis.set_tick_params(bottom='True', top='False', direction='inout') ax[0].yaxis.set_tick_params(left='True', right='False', direction='inout') if (GE == False): ax[0].invert_yaxis() ax[0].spines['top'].set_visible(False) ax[0].spines['right'].set_visible(False) ax[0].spines['bottom'].set_position('zero') ax[0].set_ylabel(r"\textbf{C\textsubscript{P}}", rotation='horizontal') ax[0].set_xlabel(r"\textbf{X/C}", x=1.05) ax[1].spines['top'].set_visible(False) ax[1].spines['right'].set_visible(False) ax[1].spines['bottom'].set_visible(False) ax[1].spines['left'].set_visible(False) ax[1].set_xticks([]) ax[1].set_yticks([]) ax[1].axis('scaled') if save == True: plt.savefig(savename + '_cp.pdf', dpi=600, bbox_inches='tight') return (fig)
def set_latitude_grid(self, degrees): #menentukan jumlah dari derajat diantara tiap longitude grid #pada contoh metode ini bahwa secara spesifik pada kelas projek #memberikan antarmuka yang baik untuk menentukan set_yticks nantinya #menentukan FixedLocator pada tiap titik, bahkan ruang dengan derajat number = (180.0 / degrees) + 1 self.yaxis.set_major_locator( FixedLocator( np.linspace(-np.pi / 2.0, np.pi / 2.0, number, True)[1:-1])) #menentukan format pada tampilan ketebalan label dalam derajat bahkan radian self.yaxis.set_major_formatter(self.DegreeFormatter(degrees))
def plot_series(fig, dates, series, title, format="-", start=0, end=None): """ Visualize the CO2 data as a time series""" ax = fig.add_subplot(111) ax.plot(dates[start:end], series[start:end], format) # plt.xticks(time[start:end], dates[start:end]) ax.xaxis.set_major_locator(FixedLocator(range(start, end, 20))) plt.xlabel("Time") plt.ylabel("Value") plt.title(title) plt.grid(True)
def plot_episodes(results, ai, ylab, xlab="Hour"): maxSteps = 24 nplot = len(results) for i, (result_mean, result_std, passive_mean, passive_std, lab) in enumerate(results): ax = subplot(nplot, 1, i + 1) # title("Agent %d (%s)" % (ai + 1, lab)) x = arange(0.0, maxSteps, 1.0) y = result_mean[ai, :] e = result_std[ai, :] py = passive_mean[ai, :] pe = passive_std[ai, :] # y2 = epsilon[ai, :] # plot(x, y, # color=clr[ai % nc], # linestyle=ls[ai % ns], # label=lab) errorbar(x, y, yerr=e, fmt='kx', linestyle="None", label="Agent %d (%s)" % (ai + 1, lab), capsize=3, markersize=5) #, linewidth=0.2) ylabel(ylab) errorbar(x, py, yerr=pe, fmt='ko', linestyle="None", label="Marginal Cost", capsize=1, markersize=3) #, linewidth=0.2) ax.ticklabel_format(style='sci', scilimits=(0, 0), axis='y') xlim((0, 23)) ax.yaxis.grid(True) locator = FixedLocator(range(0, 24)) ax.xaxis.set_major_locator(locator) #minor x-axis ticks l = legend(loc="upper left") l.get_frame().set_linewidth(0.5) xlabel(xlab)
def turn_on(syst_analyser, signal_config, fig=1, **kwargs): """ Plot deviation from chi-squared with no floated systematics. When does the effect of floating the systematic "turn on"? Args: syst_analyser (:class:`echidna.limit.limit_setting.SystAnalyser`): Systematic analyser object, created during limit setting. Can be used during limit setting setting or can load an instance from hdf5 signal_config (:class:`echidna.limit.limit_config.LimitConfig`): Signal config class, where chi squareds have been stored. fig_num (int): Fig number. When creating multiple plots in the same script, ensures matplotlib doesn't overwrite them. .. note:: Keyword arguments include: * save_as (*string*): supply file name to save image """ # Set x and y axes x = syst_analyser.get_actual_counts() y = syst_analyser.get_syst_values() # Set chi squared map values data = numpy.average(syst_analyser.get_chi_squareds(), axis=1) data = numpy.transpose(data) # transpose it so that axes are correct # Create meshgrid X, Y = numpy.meshgrid(x, y) # Define an array of \chi_0 values - chi squared without floating systematics chi_squareds = signal_config.get_chi_squareds()[0] data_np = numpy.zeros(data.shape) # zeroed array the same size as data for y in range(len(data_np)): for x, chi_squared in enumerate(chi_squareds): data_np[y][x] = chi_squared #if numpy.any((numpy.average(data_np, axis=0) != chi_squareds)): # raise AssertionError("Incorrect chi squareds (no floating) array.") # Make an array of the offsets offsets = data - data_np # Set sensible levels, pick the desired colormap and define normalization color_map = plt.get_cmap('coolwarm') positives = numpy.linspace(numpy.log10(offsets.max())*-1., numpy.log10(offsets.max()), num=50) # linear array in log space if offsets.min() < 0.: negatives = numpy.linspace(offsets.min(), 0.0, num=51) else: negatives = numpy.zeros((51)) # Add the positive part to the negative part full_scale = numpy.append(negatives, numpy.power(10, positives)) locator = FixedLocator(full_scale) levels = locator.tick_values(offsets.min(), offsets.max()) norm = BoundaryNorm(levels, ncolors=color_map.N) fig = plt.figure(fig, figsize=(12, 10)) # Fig. 4 fig.text(0.1, 0.95, syst_analyser._name, **BOLD_FONT) ax = fig.add_subplot(1, 1, 1) # Set labels ax.set_xlabel("Signal counts", **BOLD_FONT) ax.set_ylabel("Value of systematic", **BOLD_FONT) # Plot color map color_map = ax.pcolormesh(X, Y, offsets, cmap=color_map, norm=norm) color_bar = fig.colorbar(color_map) color_bar.set_label("$\chi^2 - \chi_0^2$", size=MAIN_FONT.get("size")) color_bar.ax.tick_params(labelsize=MAIN_FONT.get("size")) # tick label size # Set axes limits ax.set_xlim([X.min(), X.max()]) ax.set_ylim([Y.min(), Y.max()]) # Set axes tick label size for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(MAIN_FONT.get("size")) ax.legend(loc="upper left") if kwargs.get("save_as") is not None: fig.savefig(kwargs.get("save_as") + "_turn_on.png", dpi=300) return fig
def chi_squared_map(syst_analyser, fig_num=1, **kwargs): """ Plot chi squared surface for systematic vs. signal counts Args: syst_analyser (:class:`echidna.limit.limit_setting.SystAnalyser`): Systematic analyser object, created during limit setting. Can be used during limit setting setting or can load an instance from hdf5 fig_num (int): Fig number. When creating multiple plots in the same script, ensures matplotlib doesn't overwrite them. .. note:: Keyword arguments include: * contours (*bool*): if True produces a contour plot of chi squared surface. Default (*False*). * preferred_values (*bool*): if False "preferred values" curve is not overlayed on colour map. Default (*True*) * minima (*bool*): if False "minima" are not overlayed on colour map. Default (*True*) * save_as (*string*): supply file name to save image Default is to produce a colour map, with "preferred values" curve and "minima" overlayed. """ # Set kwargs defaults if kwargs.get("preferred_values") is None: kwargs["preferred_values"] = True if kwargs.get("minima") is None: kwargs["minima"] = True # Set x and y axes x = syst_analyser.get_actual_counts() y = syst_analyser.get_syst_values() # Set chi squared map values data = numpy.average(syst_analyser.get_chi_squareds(), axis=1) data = numpy.transpose(data) # transpose it so that axes are correct # Set preferred value values y_2 = numpy.average(syst_analyser.get_preferred_values(), axis=1) # Set minima values x_3 = syst_analyser.get_minima()[0] y_3 = syst_analyser.get_minima()[1] # Create meshgrid X, Y = numpy.meshgrid(x, y) # Set sensible levels, pick the desired colormap and define normalization color_map = plt.get_cmap('hot_r') linear = numpy.linspace(numpy.sqrt(data.min()), numpy.sqrt(data.max()), num=100) locator = FixedLocator(linear**2) levels = locator.tick_values(data.min(), data.max()) norm = BoundaryNorm(levels, ncolors=color_map.N) if kwargs.get("contours"): fig = plt.figure(fig_num, figsize=(16, 10)) # Fig. 2 fig.text(0.1, 0.9, syst_analyser._name, **BOLD_FONT) ax = Axes3D(fig) ax.view_init(elev=17.0, azim=-136.0) # set intial viewing position # Plot surface surf = ax.plot_surface(X, Y, data, rstride=1, cstride=1, cmap=color_map, norm=norm, linewidth=0, antialiased=False) ax.zaxis.set_minor_locator(locator) ax.ticklabel_format(style="scientific", scilimits=(3, 4)) # Set axis labels ax.set_xlabel("\nSignal counts", **BOLD_FONT) ax.set_ylabel("\nValue of systematic", **BOLD_FONT) for label in (ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()): label.set_fontsize(MAIN_FONT.get("size")) # tick label size ax.dist = 11 # Ensures tick labels are not cut off ax.margins(0.05, 0.05, 0.05) # Adjusts tick margins # Draw colorbar color_bar = fig.colorbar(surf, ax=ax, orientation="vertical", fraction=0.2, shrink=0.5, aspect=10) # kwargs here control axes that the colorbar is drawn in color_bar.set_label(r"$\chi^2$", size=MAIN_FONT.get("size")) color_bar.ax.tick_params(labelsize=MAIN_FONT.get("size")) plt.show() if kwargs.get("save_as") is not None: fig.savefig(kwargs.get("save_as") + "_contour.png", dpi=300) else: fig = plt.figure(fig_num, figsize=(12, 10)) # Fig. 2 fig.text(0.1, 0.95, syst_analyser._name, **BOLD_FONT) ax = fig.add_subplot(1, 1, 1) # Set labels ax.set_xlabel("Signal counts", **BOLD_FONT) ax.set_ylabel("Value of systematic", **BOLD_FONT) # Plot color map color_map = ax.pcolormesh(X, Y, data, cmap=color_map, norm=norm) color_bar = fig.colorbar(color_map) color_bar.set_label("$\chi^2$", size=MAIN_FONT.get("size")) color_bar.ax.tick_params(labelsize=MAIN_FONT.get("size")) # tick label size # Set axes limits ax.set_xlim([X.min(), X.max()]) ax.set_ylim([Y.min(), Y.max()]) if kwargs.get("preferred_values"): ax.plot(x, y_2, "bo-", label="Preferred values") if kwargs.get("minima"): ax.plot(x_3, y_3, "ko", label="Minima") # Set axes tick label size for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(MAIN_FONT.get("size")) ax.legend(loc="upper left") if kwargs.get("save_as") is not None: fig.savefig(kwargs.get("save_as") + "_color_map.png", dpi=300) return fig
def push_pull(syst_analyser, fig=1, **kwargs): """ Plot penalty value - poisson likelihood chi squared. When does minimising chi squared, which wants to "pull" the away from the data/prior value dominate and when does the penalty term, which wants to "pull" towards the data/prior, constraining the fit dominate? Args: syst_analyser (:class:`echidna.limit.limit_setting.SystAnalyser`): Systematic analyser object, created during limit setting. Can be used during limit setting setting or can load an instance from hdf5 fig_num (int): Fig number. When creating multiple plots in the same script, ensures matplotlib doesn't overwrite them. .. note:: Keyword arguments include: * save_as (*string*): supply file name to save image """ # Set x and y axes x = syst_analyser.get_actual_counts() y = syst_analyser.get_syst_values() # Set chi squared map values data = numpy.average(syst_analyser.get_chi_squareds(), axis=1) data = numpy.transpose(data) # transpose it so that axes are correct # Create meshgrid X, Y = numpy.meshgrid(x, y) # Define an array penalty values penalty_values = syst_analyser._penalty_values[1, 0:len(y)] penalty_array = numpy.zeros(data.shape) # zeroed array the same size as data for y, penalty_value in enumerate(penalty_values): for x in range(len(penalty_array[y])): penalty_array[y][x] = penalty_value # Define the push pull array penalty term - chi_squared # --> push_pull > 0 when penalty_value > chi_squared # --> push_pull < 1 when penalty_value < chi_squared push_pull = (2.*penalty_array) - data # Set sensible levels, pick the desired colormap and define normalization color_map = plt.get_cmap('coolwarm') if push_pull.min() < 0.: negatives = numpy.linspace(push_pull.min(), 0., num=50, endpoint=False) else: negatives = numpy.zeros((50)) if push_pull.max() > 0.: positives = numpy.linspace(0., push_pull.max(), num=51) else: positives = numpy.zeros((51)) # Add the pull part to the push part full_scale = numpy.append(negatives, positives) locator = FixedLocator(full_scale) levels = locator.tick_values(push_pull.min(), push_pull.max()) norm = BoundaryNorm(levels, ncolors=color_map.N) fig = plt.figure(fig, figsize=(12, 10)) # Fig. 4 fig.text(0.1, 0.95, syst_analyser._name, **BOLD_FONT) ax = fig.add_subplot(1, 1, 1) # Set labels ax.set_xlabel("Signal counts", **BOLD_FONT) ax.set_ylabel("Value of systematic", **BOLD_FONT) # Plot color map color_map = ax.pcolormesh(X, Y, push_pull, cmap=color_map, norm=norm) color_bar = fig.colorbar(color_map) color_bar.set_label("$s-\chi^{2}_{\lambda,p}$", size=MAIN_FONT.get("size")) color_bar.ax.tick_params(labelsize=MAIN_FONT.get("size")) # tick label size # Set axes limits ax.set_xlim([X.min(), X.max()]) ax.set_ylim([Y.min(), Y.max()]) # Set axes tick label size for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(MAIN_FONT.get("size")) ax.legend(loc="upper left") if kwargs.get("save_as") is not None: fig.savefig(kwargs.get("save_as") + "_push_pull.png", dpi=300) return fig