def create_slice(self, context): """ :type context: dict """ model = self._model axes = self._image.axes """ :type: matplotlib.axes.Axes """ axes.set_title(model.title, fontsize=12) axes.tick_params(axis='both') axes.set_ylabel(model.y_axis_name, fontsize=9) axes.set_xlabel(model.x_axis_name, fontsize=9) axes.get_xaxis().set_major_formatter( FuncFormatter(model.x_axis_formatter)) axes.get_xaxis().set_major_locator(AutoLocator()) axes.get_yaxis().set_major_formatter( FuncFormatter(model.y_axis_formatter)) axes.get_yaxis().set_major_locator(AutoLocator()) for label in (axes.get_xticklabels() + axes.get_yticklabels()): label.set_fontsize(9) self._set_default_limits() axes.add_patch(self._vertical_indicator) axes.add_patch(self._horizontal_indicator) self._update_indicators(context) self._image.set_cmap(cmap=context['colormap']) if model.data is not None: self._image.set_data(model.data)
def plot_variable(filename, varname, rmin=0, log=None, plot_fit=None, p0=[-1, -1, 20]): var = ExoReader(filename).read(varname) fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel(var.r_label, labelpad=10, fontsize=20) ax.set_ylabel(var.label, labelpad=10, fontsize=20) ax.tick_params(labelsize=20) r_data = var.r[var.r >= rmin] var_data = var.data[var.r >= rmin] ax.set_xlim(rmin, max(r_data)) if not not plot_fit: r_data /= r_data[0] var_data /= var_data[0] ax.set_xlim(1, max(r_data)) ax.plot(r_data, var_data, "x") if not not plot_fit: fpars = fit_variable(filename, varname, algorithm=plot_fit, rmin=rmin, p0=p0) p = fpars[2] cov = fpars[3] if plot_fit == "power": y_data = fit_powerlaw(r_data, p[0]) elif plot_fit == "curved": y_data = fit_curved_powerlaw(r_data, p[0], p[1]) elif plot_fit == "double": y_data = fit_double_powerlaw(r_data, p[0], p[1]) elif plot_fit == "broken": y_data = fit_broken_powerlaw(r_data, p[0], p[1], p[2]) elif plot_fit == "exp": y_data = fit_exp_powerlaw(r_data, p[0], p[1]) ax.plot(r_data, y_data, color="r") if not not log: plt.yscale("log") ax.yaxis.set_major_locator(LogLocator()) ax.xaxis.set_major_locator(AutoLocator()) if not log: ax.yaxis.set_major_locator(AutoLocator()) plt.tight_layout() plt.grid(which="major") plt.grid(which="minor") plt.show() return [p, cov]
def set_plot(ax, label_size=None): """ gqplot module set the plot parameters for paper plot """ #ax.xticks(size=18) #ax.yticks(size=18) if label_size is None: ax.tick_params(axis='both', labelsize=16) else: ax.tick_params(axis='both', labelsize=label_size) ax.tick_params(axis='both', pad=10.0) ax.spines['left'].set_linewidth(1.5) ax.spines['right'].set_linewidth(1.5) ax.spines['bottom'].set_linewidth(1.5) ax.spines['top'].set_linewidth(1.5) ax.tick_params(axis='both', width=2.0) #ax.tick_params(axis='both', which='major', length=10) #ax.tick_params(axis='both', which='minor', length=5) ax.tick_params(axis='both', which='major', length=6) ax.tick_params(axis='both', which='minor', length=3) ax.tick_params(which='minor', width=1.5) ax.xaxis.set_major_locator(AutoLocator()) ax.xaxis.set_minor_locator(AutoMinorLocator()) ax.yaxis.set_minor_locator(AutoMinorLocator()) ylim_low, ylim_up = ax.get_ylim() if np.abs(ylim_low - ylim_up) < 1.0: ax.yaxis.set_major_locator(AutoLocator()) myfmt = FormatStrFormatter('%3.2f') ax.yaxis.set_major_formatter(myfmt) else: ax.yaxis.set_major_locator(AutoLocator())
def add_colorbar(ax, vmin, vmax, cmap, label='', title='', orientation='horizontal', scale='linear'): import draw.my_script as my from matplotlib.ticker import AutoLocator, LogLocator ax.set_xscale(scale) ax.set_xlim((vmin, vmax)) tickvals = ax.xaxis.get_ticklocs() ax_inv_transform = ax.transAxes.inverted().transform ax_transData = ax.transData.transform ticks = [ax_inv_transform(ax_transData(np.array([(tic, 0.1)])))[0][0] for tic in tickvals] #ticklabels = [my.num2str4fig(tv, scientific=False) for tv in tickvals] ticklabels = [str(tv) for tv in tickvals] ticks, ticklabels = zip(*filter(lambda x: 0.0<=x[0]<=1.0, zip(ticks, ticklabels))) if len(ticks) < 10: if scale == 'linear': L = AutoLocator() else: L = LogLocator(base=10, subs=np.linspace(1.0,10.0,10)) tkvals = L.tick_values(vmin, vmax) minticks = filter(lambda x: 0<=x<=1, [ax_inv_transform(ax_transData(np.array([(tic,0.1)])))[0][0] for tic in tkvals]) ax.set_xscale('linear') cbar = mpl.colorbar.ColorbarBase(ax, ticklocation='auto', cmap=cmap, ticks=ticks, label=label, norm=mpl.colors.Normalize(vmin=0, vmax=1, clip=False), orientation=orientation) cbar.solids.set_rasterized(True) cbar.set_ticklabels(ticklabels) if orientation == 'horizontal': ax_working = cbar.ax.xaxis else: ax_working = cbar.ax.yaxis if len(ticks) < 10: ax_working.set_ticks(minticks, minor=True) ax_working.set_tick_params(which='minor', length=4) ax_working.set_tick_params(which='major', length=7) ax.set_title(title) return
def _set_zaxis_ticks(ax, lightcone, zticks, z_axis): if zticks != "distance": loc = AutoLocator() # Get redshift ticks. lc_z = lightcone.lightcone_redshifts if zticks == "redshift": coords = lc_z elif zticks == "frequency": coords = 1420 / (1 + lc_z) * un.MHz else: try: coords = getattr(lightcone.cosmo_params.cosmo, zticks)(lc_z) except AttributeError: raise AttributeError( "zticks '{}' is not a cosmology function.".format(zticks) ) zlabel = " ".join(z.capitalize() for z in zticks.split("_")) units = getattr(coords, "unit", None) if units: zlabel += " [{}]".format(str(coords.unit)) coords = coords.value ticks = loc.tick_values(coords.min(), coords.max()) if ticks.min() < coords.min() / 1.00001: ticks = ticks[1:] if ticks.max() > coords.max() * 1.00001: ticks = ticks[:-1] if coords[1] < coords[0]: ticks = ticks[::-1] if zticks == "redshift": z_ticks = ticks elif zticks == "frequency": z_ticks = 1420 / ticks - 1 else: z_ticks = [ z_at_value(getattr(lightcone.cosmo_params.cosmo, zticks), z * units) for z in ticks ] d_ticks = ( lightcone.cosmo_params.cosmo.comoving_distance(z_ticks).value - lightcone.lightcone_distances[0] ) getattr(ax, "set_{}ticks".format(z_axis))(d_ticks) getattr(ax, "set_{}ticklabels".format(z_axis))(ticks) else: zlabel = "Line-of-Sight Distance [Mpc]" return zlabel
def creation_plot(plot_parameters): nlines = 3 size_figure = (6,2.3*nlines) #height of the figure depends on the number of pair we display plt.close(1) fig, (ax1,ax2,ax3) = plt.subplots(nrows = nlines, ncols = 1, sharex = True, sharey = False, figsize=size_figure) major_xticks = np.arange(0, 8, 0.5) minor_xticks = np.arange(0, 8, 0.1) for ax in [ax1,ax2,ax3]: ax.set_xticks(major_xticks) ax.set_xticks(minor_xticks, minor=True) ax.set_xlim(0.9,4.4) ax.xaxis.set_ticks_position('both') majorLocator = AutoLocator() minorLocator = AutoMinorLocator() ax.yaxis.set_ticks_position('both') ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_minor_locator(minorLocator) plt.autoscale(axis='y') ax.tick_params(which = 'both', labelsize = plot_parameters["size_font_ticks"], width = plot_parameters["size_lines"]/2) # Fine-tune figure : 1) make subplots close to each other (+ less whitespace around), 2) hide x ticks for all but bottom plot, 3) add a big invisible subplot in order to center x and y labels (since the ticklabels are turned off we have to move the x and y labels with labelpad) fig.subplots_adjust(top = 0.95, bottom = 0.1, right = 0.95, left = 0.1, hspace = 0.03, wspace = 0.02) ax0 = fig.add_subplot(111, frameon=False) plt.tick_params(labeltop=False, top=False, labelbottom=False, bottom=False, labelleft=False, left=False, labelright = False, right=False) ax0.set_xlabel(r'Density (g.cm$^{-3}$)', fontweight = 'bold', fontsize = plot_parameters["size_fonts"], labelpad = plot_parameters["shift_labelpad"]) return fig, ax1, ax2, ax3, ax0
def axisinfo(unit, axis): if unit != "time": return None majloc = AutoLocator() majfmt = TimeFormatter(majloc) return units.AxisInfo(majloc=majloc, majfmt=majfmt, label="time")
def set_bottom_axis_appearance(axis, xmin, xmax, label_colour=None): spine_colour = '#363636' minor_tick_colour = '#8A8A8A' axis.spines['bottom'].set_visible(True) axis.spines['bottom'].set_color(spine_colour) axis.spines['bottom'].set_bounds(xmin, xmax) axis.tick_params(axis='x', bottom=True, labelbottom=True) axis.tick_params(axis='x', which='major', bottom=True, colors=spine_colour) axis.tick_params(axis='x', which='minor', bottom=True, length=3, colors=minor_tick_colour) axis.set_xlim([xmin, xmax]) axis.xaxis.set_major_locator(AutoLocator()) axis.set_xticklabels(axis.get_xticks()) axis.xaxis.set_minor_locator(AutoMinorLocator()) xlabels = [ f'{float(label.get_text()):.0f}' for label in axis.get_xticklabels(which='major') ] xlabels[0] = f'<{xlabels[0]}' xlabels[-1] = f'{xlabels[-1]}+' axis.set_xticklabels(xlabels) axis.set_xlabel('Age') axis.xaxis.label.set_color(label_colour)
def bin_boundaries(self, vmin, vmax): return [ x / self._factor for x in AutoLocator.bin_boundaries(self, vmin * self._factor, vmax * self._factor) ]
def process_command(self, command): from matplotlib.ticker import LogLocator, AutoLocator self.output(command[0]) if command[0] == 'ig': self.ig = command[1] elif command[0] == 'plot': xdata, ydata = command[1:] ig = self.ig ax = self.ax[ig] ax.set_yscale(self.yscales[ig]) ax.yaxis.grid(True) ax.plot(xdata, ydata) if self.yscales[ig] == 'log': ymajor_formatter = ax.yaxis.get_major_formatter() ymajor_formatter.label_minor(True) yminor_locator = LogLocator() else: yminor_locator = AutoLocator() self.ax[ig].yaxis.set_minor_locator(yminor_locator) elif command[0] == 'vline': x, kwargs = command[1:] self.vlines[self.ig].append((x, kwargs)) elif command[0] == 'clear': self.ax[self.ig].cla() elif command[0] == 'legends': for ig, ax in enumerate(self.ax): try: ax.legend(self.data_names[ig]) except: pass if self.xlabels[ig]: ax.set_xlabel(self.xlabels[ig]) if self.ylabels[ig]: ax.set_ylabel(self.ylabels[ig]) for x, kwargs in self.vlines[ig]: ax.axvline(x, **kwargs) elif command[0] == 'add_axis': ig, names, yscale, xlabel, ylabel = command[1:] self.data_names[ig] = names self.yscales[ig] = yscale self.xlabels[ig] = xlabel self.ylabels[ig] = ylabel self.n_gr = len(self.data_names) self.make_axes() elif command[0] == 'save': self.fig.savefig(command[1]) self.pipe.send(True) # Acknowledge save.
def update_plot(self): self.ax.clear() for Plotsignal in self.Plotsignals: if Plotsignal.plotenable: if Plotsignal.plotnormalise: data = Plotsignal.get_normalised_values() self.ax.plot(data, color=Plotsignal.plotcolor) else: data = Plotsignal.get_values() self.ax.plot(convert_to_si(Plotsignal.unit, data)[1], color=Plotsignal.plotcolor) self.ax.grid(True) self.ax.get_yaxis().tick_right() self.ax.get_yaxis().set_visible(True) self.ax.get_xaxis().set_visible(False) all_normalised = True iter = self.signalstore.get_iter(0) while iter is not None: if self.signalstore[iter][1] == False: all_normalised = False break iter = self.signalstore.iter_next(iter) if all_normalised: self.ax.set_yticks(np.arange(0, 1.1, step=0.1)) else: self.ax.yaxis.set_major_locator(AutoLocator()) self.canvas.draw() self.canvas.flush_events()
def set_default_locators_and_formatters(self, axis): """ Set the locators and formatters to automatic and scalar """ axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter())
def set_default_locators_and_formatters(self, axis): """ Default """ axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter())
def set_default_locators_and_formatters(self, axis): """ Just took the code from LinearScale.set_default_locators_and_formatters """ axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter())
def plot_1d(data, outputname, xlabel, ylabel): plt.rcParams.update({ "pgf.texsystem": "lualatex", "font.family": "serif", # use serif/main font for text elements "text.usetex": True, # use inline math for ticks "pgf.rcfonts": False, # don't setup fonts from rc parameters "axes.labelsize": 28, "axes.linewidth": 2.0, 'axes.unicode_minus': False, "font.size": 24, "pgf.preamble": '\n'.join([ "\\usepackage{units}", "\\usepackage{metalogo}", "\\usepackage{unicode-math}", r"\setmathfont{MathJax_Math}", r"\setmainfont{FreeSans}", ]) }) w, h = figaspect(1 / 1.1) plt.figure(figsize=(w, h)) plt.plot(data[0], data[1]) # plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) ax = plt.gca() ax.set_xlim(-180.0, 180.0) ax.set_ylim(0, 16.0) ax.xaxis.get_major_formatter()._usetex = False ax.yaxis.get_major_formatter()._usetex = False ax.tick_params(direction='in', which='major', length=6.0, width=1.0, top=True, right=True, pad=8.0) ax.tick_params(direction='in', which='minor', length=3.0, width=1.0, top=True, right=True, pad=8.0) ax.xaxis.set_major_locator(plt.MultipleLocator(90)) ax.yaxis.set_major_locator(AutoLocator()) ax.xaxis.set_minor_locator(AutoMinorLocator()) ax.yaxis.set_minor_locator(AutoMinorLocator()) plt.savefig(outputname, dpi=300, bbox_inches='tight', transparent=False) plt.close()
def plot_timeseries_stacked(df, date_col, id_col, category_col, freq, ax=None, area=False, percentage=False): ''' Plots an aggregrated stacked area chart the percentrage of id_col in each category_col ''' dfc = copy.deepcopy(df) # Aggregate by freq dfc[date_col] = pd.to_datetime(dfc[date_col]) dfc.set_index(date_col, inplace=True) agg = {id_col: 'count'} dfc_agg = dfc.groupby([pd.Grouper(freq=freq), category_col]).agg(agg) dfc_agg = dfc_agg.unstack(category_col) dfc_agg.columns = dfc_agg.columns.droplevel() # Remove NaNs dfc_agg.fillna(value=0, inplace=True) if ax is None: fig, ax = plt.subplots(nrows=1, ncols=1) if percentage: percent = dfc_agg.apply(lambda x: x / x.sum(), axis=1) * 100 if area: percent.plot.area(ax=ax, stacked=True) else: percent.plot(kind='bar', stacked=True, ax=ax) else: if area: dfc_agg.plot.area(ax=ax) else: dfc_agg.plot( kind='bar', stacked=True, ax=ax, ) percent = None # datemin = np.datetime64(dfc_agg.index.min()) # datemax = np.datetime64(dfc_agg.index.max()) # print(datemin, datemax) # ax.xaxis_date() # ax.set_xlim(datemin, datemax) # ax.xaxis.set_ticks(pd.date_range(dfc_agg.index.min()-dfc_agg.index.min().freq*30, dfc_agg.index.max()+dfc_agg.index.max().freq*30, freq='D')) plt.setp(ax.xaxis.get_majorticklabels(), 'rotation', 90) plt.setp(ax.xaxis.get_minorticklabels(), 'rotation', 90) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) # ax.xaxis.set_major_locator(mdates.MonthLocator(1)) ax.xaxis.set_major_locator(AutoLocator()) return dfc_agg, percent
def set_default_locators_and_formatters(self, axis): """ Set the locators and formatters to specialized versions for log scaling. """ axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter())
def set_default_locators_and_formatters(self, axis): """ Set the locators and formatters to reasonable defaults for linear scaling. """ axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter())
def format_axis_with_grid(ax, x_label=None, y_label=None, x_rotation=False): """ Adds a major and minor grid to axes, adds labels. Parameters ---------- ax : Axes Axes object containing the figure axis (modified) x_label : str X axis label y_label : str Y axis label x_rotation : bool True rotates the X axis labels by 90 deg (useful for ISOT dates) Returns ------- Axes Axes object containing the figure axis (modified) """ # Change major ticks ax.xaxis.set_major_locator(AutoLocator()) ax.yaxis.set_major_locator(AutoLocator()) # Change minor ticks to show with divisor of 4 ax.xaxis.set_minor_locator(AutoMinorLocator(4)) ax.yaxis.set_minor_locator(AutoMinorLocator(4)) ax.grid(which="major", color="#CCCCCC", linestyle="--") ax.grid(which="minor", color="#CCCCCC", linestyle=":") # Set axis labels if x_label: ax.set_xlabel(x_label) if y_label: ax.set_ylabel(y_label) # Rotate x axis labels if x_rotation: ax.tick_params(axis="x", labelrotation=90) return ax
def add_subplot_unshare(ax): ''' based on an answer from stacked overflow ''' ax._shared_x_axes.remove(ax) ax.xaxis.major = mpl.axis.Ticker() xloc = AutoLocator() xfmt = ScalarFormatter() ax.xaxis.set_major_locator(xloc) ax.xaxis.set_major_formatter(xfmt) ax.yaxis.set_tick_params(which='both', labelleft=True)
def _get_locators(self, locator, at, upto, count, every, between, minor): log_base, symlog_thresh = self._parse_for_log_params(self.trans) if locator is not None: major_locator = locator elif upto is not None: if log_base: major_locator = LogLocator(base=log_base, numticks=upto) else: major_locator = MaxNLocator(upto, steps=[1, 1.5, 2, 2.5, 3, 5, 10]) elif count is not None: if between is None: # This is rarely useful (unless you are setting limits) major_locator = LinearLocator(count) else: if log_base or symlog_thresh: forward, inverse = self._get_transform() lo, hi = forward(between) ticks = inverse(np.linspace(lo, hi, num=count)) else: ticks = np.linspace(*between, num=count) major_locator = FixedLocator(ticks) elif every is not None: if between is None: major_locator = MultipleLocator(every) else: lo, hi = between ticks = np.arange(lo, hi + every, every) major_locator = FixedLocator(ticks) elif at is not None: major_locator = FixedLocator(at) else: if log_base: major_locator = LogLocator(log_base) elif symlog_thresh: major_locator = SymmetricalLogLocator(linthresh=symlog_thresh, base=10) else: major_locator = AutoLocator() if minor is None: minor_locator = LogLocator(log_base, subs=None) if log_base else None else: if log_base: subs = np.linspace(0, log_base, minor + 2)[1:-1] minor_locator = LogLocator(log_base, subs=subs) else: minor_locator = AutoMinorLocator(minor + 1) return major_locator, minor_locator
def gridded_axis(ax): """ Plot major, minor ticks as well as a grid :param ax: :return: """ # Set number of major and minor ticks ax.xaxis.set_major_locator(AutoLocator()) ax.xaxis.set_minor_locator(AutoLocator()) ax.yaxis.set_major_locator(AutoLocator()) ax.yaxis.set_minor_locator(AutoLocator()) # Create nice-looking grid for ease of visualization ax.grid(which='minor', alpha=0.2, linestyle='--') ax.grid(which='major', alpha=0.5, linestyle='--') # For y-axis, format the numbers scale = 1 ticks = tkr.FuncFormatter(lambda x, pos: '{:0,d}'.format(int(x / scale))) ax.yaxis.set_major_formatter(ticks)
def creation_plot_P(plot_parameters): nlines = 3 size_figure = (6,2.3*nlines) #height of the figure depends on the number of pair we display plt.close(1) fig = plt.figure(figsize = (size_figure[0],size_figure[1])) gs = GridSpec(nlines,2,width_ratios=[1,2],top = 0.88, bottom = 0.12, right = 0.95, left = 0.15, wspace = 0, hspace = 0.03) ax1 = fig.add_subplot(gs[0,1]) ax2 = fig.add_subplot(gs[1,1]) ax3 = fig.add_subplot(gs[2,1]) ax11 = fig.add_subplot(gs[0,0],sharey=ax1) ax22 = fig.add_subplot(gs[1,0],sharey=ax2) ax33 = fig.add_subplot(gs[2,0],sharey=ax3) major_xticks = np.arange(-5,1.5,1) minor_xticks = np.arange(-5,1.5,0.2) #apply setup for ax in [ax11,ax22,ax33]: ax.set_xticks(major_xticks) ax.set_xticks(minor_xticks, minor=True) ax.set_xlim(-1,1) ax.set_facecolor((1,1,1,0)) for ax in [ax1,ax2,ax3]: ax.set_xlim(1,275) ax.set_xscale('log') plt.setp(ax.get_xticklabels()[1], visible=False) ax.tick_params(labelleft=False) for ax in [ax11,ax1,ax22,ax2]: ax.tick_params(labelbottom=False) for ax in [ax1,ax2,ax3,ax11,ax22,ax33]: ax.xaxis.set_ticks_position('both') ax.tick_params(which = 'both', labelsize = plot_parameters["size_font_ticks"], width = plot_parameters["size_lines"]/2) majorLocator = AutoLocator() minorLocator = AutoMinorLocator() ax.yaxis.set_ticks_position('both') ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_minor_locator(minorLocator) plt.autoscale(axis='y') ax.tick_params(which = 'both', labelsize = plot_parameters["size_font_ticks"], width = plot_parameters["size_lines"]/2) ax0 = fig.add_subplot(111, frameon=False) plt.tick_params(labeltop=False, top=False, labelbottom=False, bottom=False, labelleft=False, left=False, labelright = False, right=False) ax0.set_xlabel(r'Pressure (GPa)', fontweight = 'bold', fontsize = plot_parameters["size_fonts"], labelpad = plot_parameters["shift_labelpad"]) return fig, ax1, ax2, ax3, ax11, ax22, ax33, ax0
def set_default_locators_and_formatters(self, axis): # docstring inherited axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_formatter(NullFormatter()) # update the minor locator for x and y axis based on rcParams if (axis.axis_name == 'x' and mpl.rcParams['xtick.minor.visible'] or axis.axis_name == 'y' and mpl.rcParams['ytick.minor.visible']): axis.set_minor_locator(AutoMinorLocator()) else: axis.set_minor_locator(NullLocator())
def creation_plot(plot_parameters, atom_couple): """ ********** Creation of the plot ********** """ print("I use creation plot without insert") #parameters for article format size_fonts = plot_parameters["size_fonts"] size_font_ticks = plot_parameters["size_font_ticks"] size_figure = plot_parameters["size_figure"] size_markers = plot_parameters["size_markers"] size_lines = plot_parameters["size_lines"] shift_labelpad = plot_parameters["shift_labelpad"] #plot plt.close() fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=False, figsize=size_figure) #Adjustment of ticks major_xticks = np.arange(0, 9, 1) minor_xticks = np.arange(0, 8.5, 0.5) for ax in [ax1, ax2]: majorLocator = AutoLocator() minorLocator = AutoMinorLocator() ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_minor_locator(minorLocator) ax.yaxis.set_major_formatter( FormatStrFormatter('%.1f')) #set one decimal to ticks label`` plt.autoscale(enable=True, axis='y', tight=False) ax.yaxis.set_ticks_position('both') ax.set_ylabel(r'g$_{\mathrm{\bf' + atom_couple + '}}$(r)', fontsize=size_fonts, fontweight='bold', labelpad=shift_labelpad) ax.set_xticks(major_xticks) ax.set_xticks(minor_xticks, minor=True) ax.set_xlim([0, 8]) ax.set_xlabel('Distance r ($\AA$)', fontsize=size_fonts, fontweight='bold', labelpad=shift_labelpad) ax.tick_params(which='both', labelsize=size_font_ticks, width=size_lines / 2) #Fine-tune figure plt.subplots_adjust(top=0.97, bottom=0.12, right=0.89, left=0.07, hspace=0, wspace=0.27) return fig, ax1, ax2
def print_mat(): fig1 = plt.figure() ax1 = fig1.add_subplot(1, 1, 1) ax1.xaxis.set_major_formatter(DateFormatter('%m-%d')) #设置时间标签显示格式 ax1.xaxis.set_major_locator(AutoDateLocator()) #设置x轴自动时间刻度 ax1.yaxis.set_major_locator(AutoLocator()) #设置y轴自动刻度 plt.plot(Date, Open, label="Open", color="red") plt.plot(Date, Close, label="Close", color="blue") plt.title(u"抓取特斯拉股票历史开盘、收盘价格", fontproperties=font) plt.xlabel("时间", fontproperties=font) plt.legend() plt.show()
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(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_formatter(ScalarFormatter()) return
def plotmerge(n=3): """plot merging traps with n timesteps""" sep = np.linspace(0, max([Cswaist,Rbwaist])*2, n) # initial separation of the tweezer traps xs = np.linspace(-max(sep)*0.5, max(sep)*1.5, 200) # positions along the beam axis for atoms in [[Rb1064, Rb880, wrRb], [Cs1064, Cs880, wrCs]]: plt.figure(figsize=(6,7.5)) for i in range(n): ax = plt.subplot2grid((n,1), (i,0)) if atoms[0].X == 'Rb': minU0 = (atoms[0].acStarkShift(0,0,0,mj=0) + atoms[1].acStarkShift(0,0,0,mj=0))/kB*1.1e3 maxU0 = 0.16 elif atoms[0].X=='Cs': minU0 = atoms[0].acStarkShift(0,0,0,mj=0)/kB*1.1e3 maxU0 = atoms[1].acStarkShift(0,0,0,mj=0)/kB*1.1e3 # combined potential along the beam axis: U = (atoms[0].acStarkShift(xs,0,0,mj=0) + atoms[1].acStarkShift(xs-sep[n-i-1],0,0,mj=0))/kB*1e3 U1064 = atoms[0].acStarkShift(xs,0,0,mj=0)/kB*1e3 # potential in the 1064 trap U880 = atoms[1].acStarkShift(xs-sep[n-i-1],0,0,mj=0)/kB*1e3 # potential in the 880 trap plt.plot(xs*1e6, U, 'k') plt.plot(xs*1e6, U1064, color=default_colours.DUcherry_red, alpha=0.6) plt.plot(xs*1e6, U880, color=default_colours.DUsea_blue, alpha=0.6) plt.plot([0]*2, [minU0,maxU0], color=default_colours.DUcherry_red, linewidth=10, label='%.0f'%(Cswl*1e9), alpha=0.4) plt.plot([sep[n-i-1]*1e6]*2, [minU0,maxU0], color=default_colours.DUsea_blue, linewidth=10, label='%.0f'%(Rbwl*1e9), alpha=0.4) ax.set_xticks([]) ax.set_ylim((minU0,maxU0)) ax.set_xlim((xs[0]*1e6, xs[-1]*1e6)) # ax.set_yticks([]) if i == 0: if atoms[0].X == 'Rb': ax.set_title('a)', pad=30) elif atoms[0].X == 'Cs': ax.set_title('b)', pad=30) # ax.set_title("Optical potential experienced by "+atoms[0].X # +"\n%.0f beam power: %.3g mW %.0f beam power: %.3g mW"%(Cswl*1e9, power*1e3, Rbwl*1e9, Rbpower*1e3), # pad = 30) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) # ax.text(xs[0]*1e6, 0, '$\omega/2\pi = %.0f$ kHz'%(trap_freq(atoms[0])/afu), # bbox=dict(facecolor='white', edgecolor=None)) # ax.text(sep[-1]*1e6,0,'$\omega/2\pi = %.0f$ kHz'%(trap_freq(atoms[1])/afu), # bbox=dict(facecolor='white', edgecolor=None)) plt.xlabel(r'Position ($\mu$m)') ax.set_xticks(sep*1e6) plt.ylabel('Trap Depth (mK)') # ax.text(xs[0]*1e6, 0, '$\omega/2\pi = %.0f$ kHz'%atoms[2], bbox=dict(facecolor='white', edgecolor=None)) ax.yaxis.set_major_locator(AutoLocator()) plt.tight_layout() plt.subplots_adjust(hspace=0.02)
def setup_plot_for_right_frame(self, parent_frame): figure = Figure(dpi=100) self.plot = figure.add_subplot(111) self.plot.grid(**PropertiesDictionaries.grid_properties_dict) self.plot.xaxis.set_major_locator(AutoLocator()) self.plot.xaxis.set_minor_locator(AutoMinorLocator(4)) self.plot.yaxis.set_major_locator(AutoLocator()) self.plot.yaxis.set_minor_locator(AutoMinorLocator(4)) self.plot.tick_params( **dict( list( PropertiesDictionaries.ticks_properties_dict.items())[:2]), **dict( list(PropertiesDictionaries.ticks_properties_dict.items()) [3:7]), **dict( list( PropertiesDictionaries.ticks_properties_dict.items())[8:])) mat_art.setp(self.plot, **PropertiesDictionaries.axes_properties_dict) self.plot.autoscale() ChartCreator.chosen_plot_label = ttk.Label( parent_frame, text="Chosen: ", width=24, justify="left", font=Constants.MONOSPACED_FONT) ChartCreator.chosen_plot_label.grid(row=1, column=1, sticky="ew") self.canvas = FigureCanvasTkAgg(figure, parent_frame) self.canvas.mpl_connect("pick_event", self.event_handler.click_artist_callback) self.canvas.show() self.canvas.get_tk_widget().grid(row=0, column=0, columnspan=2, sticky="nwse") toolbar_frame = tk.Frame(parent_frame) toolbar_frame.grid(row=1, column=0, sticky="w") toolbar = NavigationToolbar2TkAgg(self.canvas, toolbar_frame) toolbar.update() self.canvas._tkcanvas.grid()
def update_ticks(axes, coord, components, is_log): """ Changes the axes to have the proper tick formatting based on the type of component. Returns `None` or the number of categories if components is Categorical. Parameters ---------- axes : `~matplotlib.axes.Axes` A matplotlib axis object to alter coord : { 'x' | 'y' } The coordinate axis on which to update the ticks components : iterable A list of components that are plotted along this axis if_log : boolean Whether the axis has a log-scale """ if coord == 'x': axis = axes.xaxis elif coord == 'y': axis = axes.yaxis else: raise TypeError("coord must be one of x,y") is_cat = any(comp.categorical for comp in components) is_date = any(comp.datetime for comp in components) if is_date: loc = AutoDateLocator() fmt = AutoDateFormatter(loc) axis.set_major_locator(loc) axis.set_major_formatter(fmt) elif is_log: axis.set_major_locator(LogLocator()) axis.set_major_formatter(LogFormatterMathtext()) elif is_cat: all_categories = np.empty((0, ), dtype=np.object) for comp in components: all_categories = np.union1d(comp.categories, all_categories) locator = MaxNLocator(10, integer=True) locator.view_limits(0, all_categories.shape[0]) format_func = partial(tick_linker, all_categories) formatter = FuncFormatter(format_func) axis.set_major_locator(locator) axis.set_major_formatter(formatter) return all_categories.shape[0] else: axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter())
def set_default_locators_and_formatters(self, axis): """ Set the locators and formatters to reasonable defaults for linear scaling. """ axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_formatter(NullFormatter()) # update the minor locator for x and y axis based on rcParams if rcParams['xtick.minor.visible']: axis.set_minor_locator(AutoMinorLocator()) else: axis.set_minor_locator(NullLocator())
def bin_boundaries(self, vmin, vmax): return [x/self._factor for x in AutoLocator.bin_boundaries( self, vmin*self._factor, vmax*self._factor)]
def __init__(self, factor): AutoLocator.__init__(self) self._factor = factor
def tick_values(self, vmin, vmax): return [v + offset for v in AutoLocator.tick_values(self, vmin, vmax)]
def fancy_axes(figure=None, target=None, nb_labels=5, xl=None, xh=None, tight=False, symmetric=False, padding=0.05, opacity=0.7, face_color=None, line_width=2.0, grid_color=None, labels=True, label_color=None, label_shadow=True, consolidate_labels=True): """Make axes with 3 shaded walls and a grid similar to matplotlib Args: figure (mayavi.core.scene.Scene): specific figure, or None for :py:func:`mayavi.mlab.gcf` target (Mayavi Element): If either xl or xh are not given, then get that limit from a bounding box around `target` nb_labels (int, sequence): number of labels in all, or each (x, y, z) directions xl (float, sequence): lower corner of axes xh (float, sequence): upper corner of axes tight (bool): If False, then let xl and xh expand to make nicer labels. This uses matplotlib to determine new extrema symmetric (bool): If True, then xl + xh = 0 padding (float): add padding as a fraction of the total length opacity (float): opacity of faces face_color (sequence): color (r, g, b) of faces line_width (float): Width of grid lines grid_color (sequence): Color of grid lines labels (bool): Whether or not to put axis labels on label_color (sequence): color of axis labels label_shadow (bool): Add shadows to all labels consolidate_labels (bool): if all nb_labels are the same, then only make one axis for the labels Returns: VTKDataSource: source to which 2 surfaces and 3 axes belong """ if figure is None: figure = mlab.gcf() # setup xl and xh if xl is None or xh is None: _outline = mlab.outline(target, figure=figure) if xl is None: xl = _outline.bounds[0::2] if xh is None: xh = _outline.bounds[1::2] _outline.remove() nb_labels = np.broadcast_to(nb_labels, (3,)) xl = np.array(np.broadcast_to(xl, (3,))) xh = np.array(np.broadcast_to(xh, (3,))) L = xh - xl xl -= padding * L xh += padding * L # now adjust xl and xh to be prettier if symmetric: tight = False if not tight: from matplotlib.ticker import AutoLocator for i in range(len(xl)): # pylint: disable=consider-using-enumerate l = AutoLocator() l.create_dummy_axis() l.set_view_interval(xl[i], xh[i]) locs = l() xl[i] = locs[0] xh[i] = locs[-1] dx = (xh - xl) / (nb_labels - 1) grid = tvtk.ImageData(dimensions=nb_labels, origin=xl, spacing=dx) src = VTKDataSource(data=grid) src.name = "fancy_axes" if face_color is None: face_color = figure.scene.background if grid_color is None: grid_color = figure.scene.foreground if label_color is None: label_color = grid_color face = mlab.pipeline.surface(src, figure=figure, opacity=opacity, color=face_color) face.actor.property.frontface_culling = True if line_width: grid = mlab.pipeline.surface(src, figure=figure, opacity=1.0, color=grid_color, line_width=line_width, representation='wireframe') grid.actor.property.frontface_culling = True if labels: def _make_ax_for_labels(_i, all_axes=False): if all_axes: _ax = Axes(name='axes-labels') else: _ax = Axes(name='{0}-axis-labels'.format('xyz'[_i])) # VTK bug... y_axis and z_axis are flipped... how is VTK still # the de-facto 3d plotting library? if _i == 0: _ax.axes.x_axis_visibility = True _ax.axes.y_axis_visibility = False _ax.axes.z_axis_visibility = False elif _i == 1: _ax.axes.x_axis_visibility = False _ax.axes.y_axis_visibility = False _ax.axes.z_axis_visibility = True # VTK bug elif _i == 2: _ax.axes.x_axis_visibility = False _ax.axes.y_axis_visibility = True # VTK bug _ax.axes.z_axis_visibility = False else: raise ValueError() _ax.property.opacity = 0.0 _ax.axes.number_of_labels = nb_labels[_i] # import IPython; IPython.embed() _ax.title_text_property.color = label_color _ax.title_text_property.shadow = label_shadow _ax.label_text_property.color = label_color _ax.label_text_property.shadow = label_shadow src.add_module(_ax) if consolidate_labels and np.all(nb_labels[:] == nb_labels[0]): _make_ax_for_labels(0, all_axes=True) else: _make_ax_for_labels(0, all_axes=False) _make_ax_for_labels(1, all_axes=False) _make_ax_for_labels(2, all_axes=False) return src