我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用matplotlib.pyplot.ticklabel_format()。
def plot(self, dataset, path, show=False): with PdfPages(path) as pdf: x_vals = dataset.data['T'].tolist() y_vals = dataset.data[self.symbol].tolist() plt.plot(x_vals, y_vals, 'ro', alpha=0.4, markersize=4) x_vals2 = np.linspace(min(x_vals), max(x_vals), 80) fx = np.polyval(self._coeffs, x_vals2) plt.plot(x_vals2, fx, linewidth=0.3, label='') plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 4)) plt.legend(loc=3, bbox_to_anchor=(0, 0.8)) plt.title('$%s$ vs $T$' % self.display_symbol) plt.xlabel('$T$ (K)') plt.ylabel('$%s$ (%s)' % (self.display_symbol, self.units)) fig = plt.gcf() pdf.savefig(fig) plt.close() if show: webbrowser.open_new(path)
def plot_deviance(sol, save=False, draw=True, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = get_model_type(sol) if draw or save: fig, ax = plt.subplots(figsize=(4,3)) deviance = sol.MDL.trace('deviance')[:] sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, deviance, "-", color="C3", label="Model deviance\nDIC = %.2f\nBPIC = %.2f" %(sol.MDL.DIC,sol.MDL.BPIC)) plt.xlabel("Iteration") plt.ylabel("Model deviance") plt.legend(numpoints=1, loc="best", fontsize=9) plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: save_where = '/Figures/ModelDeviance/' working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving model deviance figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'ModelDeviance-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight') try: plt.close(fig) except: pass if draw: return fig else: return None
def plot_logp(sol, save=False, draw=True, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = get_model_type(sol) if draw or save: fig, ax = plt.subplots(figsize=(4,3)) logp = logp_trace(sol.MDL) sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, logp, "-", color="C3") plt.xlabel("Iteration") plt.ylabel("Log-likelihood") plt.legend(numpoints=1, loc="best", fontsize=9) plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: save_where = '/Figures/LogLikelihood/' working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving logp trace figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'LogLikelihood-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight') try: plt.close(fig) except: pass if draw: return fig else: return None
def plot_deviance(sol, save=False, draw=True, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = get_model_type(sol) if draw or save: fig, ax = plt.subplots(figsize=(4,3)) deviance = sol.MDL.trace('deviance')[:] sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, deviance, "-", color="C3", label="Model deviance\nDIC = %.2f\nBPIC = %.2f" %(sol.MDL.DIC,sol.MDL.BPIC)) plt.xlabel("Iteration") plt.ylabel("Model deviance") plt.legend(numpoints=1, loc="best") plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: save_where = '/Figures/ModelDeviance/' working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving model deviance figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'ModelDeviance-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight') try: plt.close(fig) except: pass if draw: return fig else: return None
def plot_logp(sol, save=False, draw=True, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = get_model_type(sol) if draw or save: fig, ax = plt.subplots(figsize=(4,3)) logp = logp_trace(sol.MDL) sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, logp, "-", color="C3") plt.xlabel("Iteration") plt.ylabel("Log-likelihood") plt.legend(numpoints=1, loc="best") plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: save_where = '/Figures/LogLikelihood/' working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving logp trace figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'LogLikelihood-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight') try: plt.close(fig) except: pass if draw: return fig else: return None
def plotfmt(self, figsize=(10, 5)): pl.figure(figsize=figsize) pl.subplot(311) pl.plot(self.properties.geometry.axle, self.V) pl.grid(True) pl.title('Vertical shear') pl.ylabel('Force in [N]') pl.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) pl.subplot(312) pl.plot(self.properties.geometry.axle, self.M) pl.grid(True) pl.title('Bending moments') pl.ylabel('Moment in [Nm]') pl.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) pl.subplot(313) pl.plot(self.properties.geometry.axle, self.T) pl.grid(True) pl.title('Torque') pl.ylabel('Torque in [Nm]') pl.xlabel('Length in [mm]') pl.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) pl.tight_layout() pl.show()
def plot_frequencies(flu, gene, mutation=None, plot_regions=None, all_muts=False, ax=None, **kwargs): import seaborn as sns sns.set_style('whitegrid') cols = sns.color_palette() linestyles = ['-', '--', '-.', ':'] if plot_regions is None: plot_regions=regions pivots = flu.pivots if ax is None: plt.figure() ax=plt.subplot(111) if type(mutation)==int: mutations = [x for x,freq in flu.mutation_frequencies[('global', gene)].iteritems() if (x[0]==mutation)&(freq[0]<0.5 or all_muts)] elif mutation is not None: mutations = [mutation] else: mutations=None if mutations is None: for ri, region in enumerate(plot_regions): count=flu.mutation_frequency_counts[region] plt.plot(pivots, count, c=cols[ri%len(cols)], label=region) else: print("plotting mutations", mutations) for ri,region in enumerate(plot_regions): for mi,mut in enumerate(mutations): if mut in flu.mutation_frequencies[(region, gene)]: freq = flu.mutation_frequencies[(region, gene)][mut] err = flu.mutation_frequency_confidence[(region, gene)][mut] c=cols[ri%len(cols)] label_str = str(mut[0]+1)+mut[1]+', '+region plot_trace(ax, pivots, freq, err, c=c, ls=linestyles[mi%len(linestyles)],label=label_str, **kwargs) else: print(mut, 'not found in region',region) ax.ticklabel_format(useOffset=False) ax.legend(loc=2)
def plot(self, *args, plotTitle=None, showPlot=True, filename=None, **kwargs): dataFrame = self.select(*args, **kwargs).getDataFrame() if dataFrame.index.nlevels > 1: self._raiseException('Please restrict the dataset such that only one index is left.') ax = dataFrame.plot() plt.ticklabel_format(useOffset=False, style='plain') plt.title(plotTitle if plotTitle else kwargs) self.showPlot(showPlot=showPlot, filename=filename) return self
def plot_hexbin(sol, var1, var2, save=False, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' MDL = sol.MDL filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = sol.get_model_type() if var1 == "R0": stoc1 = "R0" else: stoc1 = ''.join([i for i in var1 if not i.isdigit()]) stoc_num1 = [int(i) for i in var1 if i.isdigit()] try: x = MDL.trace(stoc1)[:,stoc_num1[0]-1] except: x = MDL.trace(stoc1)[:] if var2 == "R0": stoc2 = "R0" else: stoc2 = ''.join([i for i in var2 if not i.isdigit()]) stoc_num2 = [int(i) for i in var2 if i.isdigit()] try: y = MDL.trace(stoc2)[:,stoc_num2[0]-1] except: y = MDL.trace(stoc2)[:] xmin, xmax = min(x), max(x) ymin, ymax = min(y), max(y) fig, ax = plt.subplots(figsize=(4,4)) plt.grid(None) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # plt.scatter(x, y) plt.hexbin(x, y, gridsize=20, cmap=plt.cm.Blues) plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.xticks(rotation=90) plt.locator_params(axis = 'y', nbins = 5) plt.locator_params(axis = 'x', nbins = 5) cb = plt.colorbar() cb.set_label('Number of observations') plt.yticks(fontsize=14) plt.xticks(fontsize=14) plt.ylabel("%s" %var2, fontsize=14) plt.xlabel("%s" %var1, fontsize=14) if save: save_where = '/Figures/Hexbins/%s/' %filename working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving hexbin figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'Bivar-%s-%s_%s_%s.%s'%(model,filename,var1,var2,save_as), dpi=fig_dpi, bbox_inches='tight') plt.close(fig) return fig
def plot_autocorr(sol, save=False, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' MDL = sol.MDL model = get_model_type(sol) filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] keys = sorted([x.__name__ for x in MDL.deterministics]) + sorted([x.__name__ for x in MDL.stochastics]) try: keys.remove("zmod") keys.remove("log_m_i") keys.remove("log_tau_i") keys.remove("cond") except: pass for (i, k) in enumerate(keys): vect = old_div((MDL.trace(k)[:].size),(len(MDL.trace(k)[:]))) if vect > 1: keys[i] = [k+"%d"%n for n in range(1,vect+1)] keys = list(flatten(keys)) ncols = 2 nrows = int(ceil(len(keys)*1.0 / ncols)) fig, ax = plt.subplots(nrows, ncols, figsize=(10,nrows*2)) plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) for (a, k) in zip(ax.flat, keys): if k[-1] not in ["%d"%d for d in range(1,8)] or k =="R0": data = sorted(MDL.trace(k)[:].ravel()) else: data = sorted(MDL.trace(k[:-1])[:][:,int(k[-1])-1].ravel()) plt.axes(a) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) plt.gca().get_xaxis().get_major_formatter().set_useOffset(False) plt.yticks(fontsize=12) plt.xticks(fontsize=12) plt.ylabel(k, fontsize=12) to_thin = old_div(len(data),50) if to_thin != 0: plt.xlabel("Lags / %d"%to_thin, fontsize=12) else: plt.xlabel("Lags", fontsize=12) max_lags = None if len(data) > 50: data= data[::to_thin] plt.acorr(data, usevlines=True, maxlags=max_lags, detrend=plt.mlab.detrend_mean) plt.grid(None) fig.tight_layout() for a in ax.flat[ax.size - 1:len(keys) - 1:-1]: a.set_visible(False) if save: save_where = '/Figures/Autocorrelations/' working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving autocorrelation figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'Autocorr-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight') try: plt.close(fig) except: pass return fig
def plot_errors(sol, ax, noise): MDL = sol["pymc_model"] # model = get_model_type(sol) filename = sol["path"].replace("\\", "/").split("/")[-1].split(".")[0] keys = sorted([x.__name__ for x in MDL.deterministics]) + sorted([x.__name__ for x in MDL.stochastics]) sampler = MDL.get_state()["sampler"] try: keys.remove("zmod") keys.remove("m_") except: pass for (i, k) in enumerate(keys): vect = old_div((MDL.trace(k)[:].size),(len(MDL.trace(k)[:]))) if vect > 1: keys[i] = [k+"%d"%n for n in range(0,vect)] keys = list(flatten(keys)) labels = [r"$log_{10}\bar{\tau}$", "$\Sigma m$", "$R_0$", "$a_0$", "$a_1$", "$a_2$", "$a_3$", "$a_4$"] ncols = 2 nrows = int(ceil(len(keys)*1.0 / ncols)) for c, (a, k) in enumerate(zip(ax.flat, keys)): if k == "R0": stoc = "R0" else: stoc = ''.join([i for i in k if not i.isdigit()]) stoc_num = [int(i) for i in k if i.isdigit()] try: mean = np.mean(MDL.trace(stoc)[:][:,stoc_num[0]-1]) SD = np.std(MDL.trace(stoc)[:][:,stoc_num[0]-1]) except: mean = np.mean(MDL.trace(stoc)[:]) SD = np.std(MDL.trace(stoc)[:]) # x = np.arange(sampler["_burn"]+1, sampler["_iter"]+1, sampler["_thin"]) plt.axes(a) a.grid(False) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,2)) plt.locator_params(axis = 'y', nbins = 6) plt.yticks(fontsize=14) plt.xticks(list(range(0,12)),["","1","2","3","4","5","6","7","8","9","10"], fontsize=14) plt.ylabel(labels[c], fontsize=14) ty = a.yaxis.get_offset_text() ty.set_size(12) tx = a.xaxis.get_offset_text() tx.set_size(12) plt.xlim([0.5, 10.5]) plt.errorbar(noise+1, mean, SD, None, 'ob', label=filename, linewidth=1.0) # plt.xticks()
def spectogram(trace, traceSyn): ''' Plots the amplitude spectrum of a recorded trace and a sytnthetic trace. Calculation with the Fast Fourier Transform (FFT) from numpy. The x-axis is converted to frequencies from 0 to half of the maximum sampling frequency (Nyquist frequency). The y-axis is converted by taking the absolute value of the FFT and multiplication by a factor of 2. Further the amplitude has to be normalized with the number of samples. To improve the amplitude spectrum the data is also multiplied with a Hanning window. Balzer explains how to apply the FFT in his IPython Notebook: rhttp://nbviewer.jupyter.org/github/balzer82/FFT-Python/blob/master/FFT-Tutorial.ipynb :param trace: The recorded trace :type trace: obspy.core.trace.Trace :param traceSyn: The synthetic trace :type traceSyn: obspy.core.trace.Trace ''' #spektrum trace.data -= trace.data.mean() traceSyn.data -= traceSyn.data.mean() Fs = trace.stats.sampling_rate fig = plt.figure(1) fig.suptitle(trace.stats.station, fontsize=20) ax1 = plt.subplot(211) ax1.set_title('Recorded Signal') # Calculate amplitude spectrum for recorded data y = trace.data hann = np.hanning(len(y)) N = len(y)/2 +1 Y = np.fft.fft(y*hann) X = np.linspace(0, Fs/2, N, endpoint = True) plt.ylabel('|Ground Motion (m/s)|') plt.semilogx(X, (2.0*np.abs(Y[:N])/N), 'k') # plotting the spectrum plt.setp(ax1.get_xticklabels(), visible=False) # Calculate amplitude spectrum for synthetic data y = traceSyn.data hann = np.hanning(len(y)) N = len(y)/2 +1 Y = np.fft.fft(y*hann) X = np.linspace(0, Fs/2, N, endpoint = True) ax2 = plt.subplot(212, sharex=ax1) ax2.set_title('Synthetic Signal') plt.semilogx(X, (2.0*np.abs(Y[:N]))/N) # plotting the spectrum plt.xlabel('Freq (Hz)') plt.ylabel('|Ground Motion (m/s)|') plt.yticks(np.array([0,1,2,3,4,5])*10e-8) plt.ticklabel_format(axis='y',style='sci',scilimits=(0,0)) fig.subplots_adjust(top=0.85) plt.savefig('../spectrum.pdf', bbox_inches='tight', pad_inches=0.05) plt.draw()
def plot2D(result,par1,par2, colorMap = getColorMap(), labelSize = 15, fontSize = 10, axisHandle = None, showImediate = True): """ This function constructs a 2 dimensional marginal plot of the posterior density. This is the same plot as it is displayed in plotBayes in an unmodifyable way. The result struct is passed as result. par1 and par2 should code the two parameters to plot: 0 = threshold 1 = width 2 = lambda 3 = gamma 4 = eta Further plotting options may be passed. """ # convert strings to dimension number par1,label1 = _utils.strToDim(str(par1)) par2,label2 = _utils.strToDim(str(par2)) assert (par1 != par2), 'par1 and par2 must be different numbers to code for the parameters to plot' if axisHandle == None: axisHandle = plt.gca() try: plt.axes(axisHandle) except TypeError: raise ValueError('Invalid axes handle provided to plot in.') plt.set_cmap(colorMap) marg, _, _ = marginalize(result, np.array([par1, par2])) if par1 > par2 : marg = marg.T if 1 in marg.shape: if len(result['X1D'][par1])==1: plotMarginal(result,par2) else: plotMarginal(result,par2) else: e = [result['X1D'][par2][0], result['X1D'][par2][-1], \ result['X1D'][par1][0], result['X1D'][par1][-1]] plt.imshow(marg, extent = e) plt.ylabel(label1,fontsize = labelSize) plt.xlabel(label2,fontsize = labelSize) plt.tick_params(direction='out',right='off',top='off') for side in ['top','right']: axisHandle.spines[side].set_visible(False) plt.ticklabel_format(style='sci',scilimits=(-2,4)) if (showImediate): plt.show(0)