我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.ticker.MaxNLocator()。
def make_split(ratio, gap=0.12): import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from matplotlib.ticker import MaxNLocator cax = plt.gca() box = cax.get_position() xmin, ymin = box.xmin, box.ymin xmax, ymax = box.xmax, box.ymax gs = GridSpec(2, 1, height_ratios=[ratio, 1 - ratio], left=xmin, right=xmax, bottom=ymin, top=ymax) gs.update(hspace=gap) ax = plt.subplot(gs[0]) plt.setp(ax.get_xticklabels(), visible=False) bx = plt.subplot(gs[1], sharex=ax) return ax, bx
def inertia(self, explained_inertia): fig, ax = plt.subplots() ax.grid('on') ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.plot(explained_inertia, color=SEABORN['blue'], label='Normalized inertia') ax.plot(explained_inertia, 'o', color=SEABORN['cyan']) ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) ax.margins(0.05) ax.set_ylim(ymax=1) ax.set_title('Component contributions to inertia') ax.set_xlabel('Component number') ax.set_ylabel('Normalized inertia') ax.legend(loc='best') return fig, ax
def _plot_walk(self, ax, parameter, data, truth=None, extents=None, convolve=None, color=None): # pragma: no cover if extents is not None: ax.set_ylim(extents) assert convolve is None or isinstance(convolve, int), \ "Convolve must be an integer pixel window width" x = np.arange(data.size) ax.set_xlim(0, x[-1]) ax.set_ylabel(parameter) if color is None: color = "#0345A1" ax.scatter(x, data, c=color, s=2, marker=".", edgecolors="none", alpha=0.5) max_ticks = self.parent.config["max_ticks"] ax.yaxis.set_major_locator(MaxNLocator(max_ticks, prune="lower")) if convolve is not None: color2 = self.parent.color_finder.scale_colour(color, 0.5) filt = np.ones(convolve) / convolve filtered = np.convolve(data, filt, mode="same") ax.plot(x[:-1], filtered[:-1], ls=':', color=color2, alpha=1) if truth is not None: ax.axhline(truth, **self.parent.config_truth)
def plotKurtosisVsLvls(ax, runs, *args, **kwargs): """Plots El, Vl vs TOL of @runs, as returned by MIMCDatabase.readRunData() ax is in instance of matplotlib.axes """ args, kwargs = __normalize_fmt(args, kwargs) ax.set_xlabel(r'$\ell$') ax.set_ylabel(r'$\textnormal{Kurt}_\ell$') ax.set_yscale('log') fnNorm = kwargs.pop("fnNorm") if "__calc_moments" in kwargs: central_delta_moments, _, _, _, _ = kwargs.pop("__calc_moments") else: central_delta_moments, _, _, _, _ = __calc_moments(runs, seed=kwargs.pop('seed', None), direction=kwargs.pop('direction', None), fnNorm=fnNorm) Vl = central_delta_moments[:, 1] E4l = central_delta_moments[:, 3] ax.xaxis.set_major_locator(MaxNLocator(integer=True)) line = ax.plot(np.arange(0, len(Vl)), E4l/Vl**2, *args, **kwargs) return line[0].get_xydata(), [line]
def plotSkewnessVsLvls(ax, runs, *args, **kwargs): """Plots El, Vl vs TOL of @runs, as returned by MIMCDatabase.readRunData() ax is in instance of matplotlib.axes """ args, kwargs = __normalize_fmt(args, kwargs) ax.set_xlabel(r'$\ell$') ax.set_ylabel(r'$\textnormal{Skew}_\ell$') ax.set_yscale('log') fnNorm = kwargs.pop("fnNorm") if "__calc_moments" in kwargs: central_delta_moments, _, _, _, _ = kwargs.pop("__calc_moments") else: central_delta_moments, _, _, _, _ = __calc_moments(runs, seed=kwargs.pop('seed', None), direction=kwargs.pop('direction', None), fnNorm=fnNorm) Vl = central_delta_moments[:, 1] E3l = np.abs(central_delta_moments[:, 2]) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) line = ax.plot(np.arange(0, len(Vl)), E3l/Vl**1.5, *args, **kwargs) return line[0].get_xydata(), [line]
def showResult(date, scales, power, time_scale, window, file_name): # y_ticks = np.arange(0, 15, 2) import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, ax = plt.subplots() ax.xaxis.set_major_locator(YearLocator(time_scale)) # ax.set_yticks(y_ticks) ax.xaxis.set_major_locator(mticker.MaxNLocator(5)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) ax.contourf(date, scales, power, 100) # ax.set_yscale('log') print("Wavelet saved to", file_name) fig.savefig(file_name) # fig.show() # fig.waitforbuttonpress()
def paper_single_mult_ax(nrows=1, ncols=1, **kwargs): #import matplotlib as mpl paper_single(FF=max(nrows,ncols)) f, ax = plt.subplots(nrows=nrows, ncols=ncols, **kwargs) plt.minorticks_on() ylocator6 = plt.MaxNLocator(5) xlocator6 = plt.MaxNLocator(6) if len(ax.shape) > 1: for axrow in ax: for axcol in axrow: axcol.xaxis.set_major_locator(xlocator6) axcol.yaxis.set_major_locator(ylocator6) else: for axcol in ax: axcol.xaxis.set_major_locator(xlocator6) axcol.yaxis.set_major_locator(ylocator6) return f, ax
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 heatmap(data, save_file='heatmap.png'): ax = plt.figure().gca() ax.yaxis.set_major_locator(MaxNLocator(integer=True)) ax.yaxis.set_major_locator(MultipleLocator(5)) plt.pcolor(data, cmap=plt.cm.jet) plt.savefig(save_file) # plt.show()
def plot_pull(data, func): import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator ax, bx = make_split(0.8) plt.sca(ax) x, y, norm = histpoints(data) lower, upper = ax.get_xlim() xs = np.linspace(lower, upper, 200) plt.plot(xs, norm * func(xs), 'b-') #plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower')) plt.sca(bx) resid = y[1] - norm * func(x) err = np.zeros_like(resid) err[resid >= 0] = y[0][resid >= 0] err[resid < 0] = y[2][resid < 0] pull = resid / err plt.errorbar(x, pull, yerr=1, color='k', fmt='o') plt.ylim(-5, 5) plt.axhline(0, color='b') plt.sca(ax) return ax, bx
def visualise(self, marks, counts): N = len(marks) ind = range(N) _, ax = plt.subplots() ax.bar(ind, counts, color='#4286f4') ax.set_ylabel('Posts') ax.set_xticks(ind) ax.yaxis.set_major_locator(MaxNLocator(nbins=20, integer=True, min_n_ticks=1)) step = N // 12 + 1 labels = [self.format_time(mark) if i % step == 0 else '' for i, mark in enumerate(marks)] ax.set_xticklabels(labels, rotation=45, fontsize=10) return self.save()
def cumulative_inertia(self, cumulative_explained_inertia, threshold): fig, ax = plt.subplots() ax.grid('on') ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') # Plot threshold line ax.axhline(y=threshold, color=SEABORN['red'], label='Threshold', linestyle='--') # Plot first value above threshold line try: index_above_threshold = [ i >= threshold for i in cumulative_explained_inertia ].index(True) ax.axvline(x=index_above_threshold, color=SEABORN['green'], label='First component above threshold', linestyle='--') except ValueError: pass # Plot inertia percentages curve ax.plot(cumulative_explained_inertia, color=SEABORN['blue'], label='Normalized cumulative inertia') ax.plot(cumulative_explained_inertia, 'o', color=SEABORN['blue']) ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) ax.margins(0.05, 0.15) ax.set_ylim(ymin=0) ax.set_title('Cumulative component contributions to inertia') ax.set_xlabel('Component number') ax.set_ylabel('Normalized cumulative inertia') ax.legend(loc='best') return fig, ax
def plot_ohlcv(self, df): fig, ax = plt.subplots() # Plot the candlestick candlestick2_ohlc(ax, df['open'], df['high'], df['low'], df['close'], width=1, colorup='g', colordown='r', alpha=0.5) # shift y-limits of the candlestick plot so that there is space # at the bottom for the volume bar chart pad = 0.25 yl = ax.get_ylim() ax.set_ylim(yl[0] - (yl[1] - yl[0]) * pad, yl[1]) # Add a seconds axis for the volume overlay ax2 = ax.twinx() ax2.set_position( matplotlib.transforms.Bbox([[0.125, 0.1], [0.9, 0.26]])) # Plot the volume overlay # bc = volume_overlay(ax2, df['open'], df['close'], df['volume'], # colorup='g', alpha=0.5, width=1) ax.xaxis.set_major_locator(ticker.MaxNLocator(6)) def mydate(x, pos): try: return df.index[int(x)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) plt.margins(0) plt.show()
def __init__(self, max_n_ticks, calendar, date_unit, min_n_ticks=3): # The date unit must be in the form of days since ... self.max_n_ticks = max_n_ticks self.min_n_ticks = min_n_ticks self._max_n_locator = mticker.MaxNLocator(max_n_ticks, integer=True) self._max_n_locator_days = mticker.MaxNLocator( max_n_ticks, integer=True, steps=[1, 2, 4, 7, 14]) self.calendar = calendar self.date_unit = date_unit if not self.date_unit.lower().startswith('days since'): msg = 'The date unit must be days since for a NetCDF time locator.' raise ValueError(msg) self._cached_resolution = {}
def __init__(self, *args, **kwargs): mticker.MaxNLocator.__init__(self, *args, **kwargs)
def __call__(self, *args, **kwargs): return mticker.MaxNLocator.__call__(self, *args, **kwargs) # at most 5 ticks, pruning the upper and lower so they don't overlap # with other ticks #ax2.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both')) #ax3.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both'))
def plot_index_and_sentiment(tick_seq, shindex_seq, sentiment_seq, date): if len(tick_seq) != len(shindex_seq) or len(tick_seq) != len(sentiment_seq): print('error(plot) : three sequence length is not same') return x = range(len(shindex_seq)) labels = tick_seq y1 = shindex_seq y2 = sentiment_seq def format_fn(tick_val, tick_pos): if int(tick_val) in x: return labels[int(tick_val)] else: return '' fig = plt.figure(figsize=(12,8)) p1 = fig.add_subplot(111) p1.xaxis.set_major_formatter(FuncFormatter(format_fn)) p1.xaxis.set_major_locator(MaxNLocator(integer=True, nbins=12)) delta = shindex_seq[len(shindex_seq) - 1] - shindex_seq[0] if delta > 0: p1.plot(x, y1, label="$SCI$", color="red", linewidth=1) else: p1.plot(x, y1, label="$SCI$", color="green", linewidth=1) p1.plot(x, y2, 'b--', label="$ISI$", color="blue", linewidth=1) plt.title("Shanghai Composite Index(SCI) & Investor Sentiment Index(ISI)") plt.xlabel("Time(5min)") plt.ylabel("Index Value") plt.legend() # plt.show() global subdir filepath = './Pic/' + subdir + '/' + date + '.png' plt.savefig(filepath)
def __call__(self, *args, **kwargs): return mticker.MaxNLocator.__call__(self, *args, **kwargs)
def __call__(self, *args, **kwargs): return mticker.MaxNLocator.__call__(self, *args, **kwargs) #plt.rc('axes', grid=True)
def main(): dir_data = './data' ext_img = 'png' #n_epoch = 100 n_epoch = 50 #n_img_per_batch = 40 n_img_per_batch = 60 #n_img_per_batch = 1 n_worker = 4 interval_train_loss = int(round(20000 / n_img_per_batch)) * n_img_per_batch is_gpu = torch.cuda.device_count() > 0 transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) di_set_transform = {'train' : transform, 'test' : transform} #fig = plt.figure(num=None, figsize=(1, 2), dpi=500) fig = plt.figure(num=None, figsize=(12, 18), dpi=100) plt.ion() ax_loss_train = fig.add_subplot(2, 1, 1) ax_loss_train.set_title('Avg. train loss per image vs. # train input images') ax_loss_train.xaxis.set_major_locator(MaxNLocator(integer=True)) ax_loss_val = fig.add_subplot(2, 1, 2) ax_loss_val.set_title('Avg. val. loss per image vs. # train input images') ax_loss_val.xaxis.set_major_locator(MaxNLocator(integer=True)) trainloader, testloader, net, criterion, optimizer, scheduler, li_class = \ initialize( is_gpu, dir_data, di_set_transform, ext_img, n_img_per_batch, n_worker) #print('[%s] lap of initializing : %d sec' % (lap_sec)) kolor = np.random.rand(3) #if 2 == i_m: # a = 0 train(is_gpu, trainloader, testloader, net, criterion, optimizer, scheduler, #li_class, n_epoch, ax_loss_train, ax_loss_val, kolor, interval_train_loss) print('Finished all.') plt.pause(1000) return
def _set_cbticks(cbrange, cb_kws): """Set colorbar ticks. Adjust colorbar range if using a discrete colorbar so that the ticks fall in the middle of each level. Parameters: cbrange (list): Colorbar range. cb_kws (dict): Keyword args to set and draw colorbar. Return: tuple: colorbar range, colorbar tick numbers """ if cb_kws.get('log_cb'): ticks = _log_cbticks(cbrange) else: try: ticks = MaxNLocator(cb_kws.get('n_ticks', 7)).tick_values(*cbrange) except AttributeError: print('AttributeError: MaxNLocator instance has no attribute ``tick_values``.') # if discrete colorbar, offset upper and lower cbrange so ticks are in center of each level if cb_kws.get('n_levels', None) is not None: offset = (ticks[1] - ticks[0]) / 2. cbrange = [ticks[0] - offset, ticks[-1] + offset] if cb_kws.get('tick_everyother', False): ticks = ticks[::2] return cbrange, ticks
def add_colorbar(cm, bins, fontsize=5): cb = plt.colorbar(cm, shrink=0.9) cb.outline.set_linewidth(0) cb.locator = ticker.MaxNLocator(nbins=bins) cb.ax.tick_params(labelsize=fontsize) cb.update_ticks()
def create_colorbar(cm, cax, colorbar_bins=8, fontsize=None, linewidth=0): cb = plt.colorbar(mappable=cm, cax=cax) if fontsize is not None: cb.ax.tick_params(labelsize=fontsize) cb.outline.set_linewidth(linewidth) cb.locator = ticker.MaxNLocator(nbins=colorbar_bins) cb.update_ticks()
def graphData(stock): stockFile=stock+".txt" date,closep,highp,lowp,openp,volume= np.loadtxt(stockFile,delimiter=',',unpack=True, converters={0: mdates.strpdate2num('%Y%m%d')}) fig=plt.figure() ax1=plt.subplot(1,1,1) # how much by how much by ax1.plot(date,openp) ax1.plot(date,highp) ax1.plot(date,lowp) ax1.plot(date,closep) #pretty it up ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) #max10days ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # rotate for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) plt.show()
def _set_integer_tick_labels(axis, labels): """Use labels dict to set labels on axis""" axis.set_major_formatter(FuncFormatter(lambda x, _: labels.get(x, ''))) axis.set_major_locator(MaxNLocator(integer=True))
def plotExpectVsLvls(ax, runs, *args, **kwargs): """Plots El, Vl vs TOL of @runs, as returned by MIMCDatabase.readRunData() ax is in instance of matplotlib.axes """ ax.set_xlabel(r'$\ell$') ax.set_ylabel(r'$E_\ell$') ax.set_yscale('log') ax.xaxis.set_major_locator(MaxNLocator(integer=True)) fnNorm = kwargs.pop("fnNorm") if "__calc_moments" in kwargs: central_delta_moments, central_fine_moments, _, M, _ = kwargs.pop("__calc_moments") else: central_delta_moments, central_fine_moments, _, M, _ = __calc_moments(runs, seed=kwargs.pop('seed', None), direction=kwargs.pop('direction', None), fnNorm=fnNorm) fine_kwargs = kwargs.pop('fine_kwargs', None) plotObj = [] El = central_delta_moments[:, 0] if central_delta_moments.shape[1] > 1: Vl = central_delta_moments[:, 1] plotObj.append(ax.errorbar(np.arange(0, len(El)), np.abs(El), *args, yerr=3*np.sqrt(np.abs(Vl/M)), **kwargs)) else: plotObj.append(ax.plot(np.arange(0, len(El)), np.abs(El), *args, **kwargs)) if fine_kwargs is not None: El = central_fine_moments[:, 0] if central_fine_moments.shape[1] > 1: Vl = central_fine_moments[:, 1] plotObj.append(ax.errorbar(np.arange(0, len(El)), np.abs(El), yerr=3*np.sqrt(np.abs(Vl/M)), **fine_kwargs)) else: plotObj.append(ax.plot(np.arange(0, len(El)), np.abs(El), **fine_kwargs)) return plotObj[0][0].get_xydata(), plotObj
def plotLvlsNumVsTOL(ax, runs, *args, **kwargs): """Plots L vs TOL of @runs, as returned by MIMCDatabase.readRunData() ax is in instance of matplotlib.axes """ filteritr = kwargs.pop("filteritr", filteritr_all) summary = [] for r in runs: prev = 0 prevMax = 0 for i in xrange(0, len(r.iters)): if not filteritr(r, i): continue itr = r.iters[i] stats = [np.sum(data) for j, data in itr.lvls_sparse_itr(prev)] if len(stats) == 0: assert(prev > 0) newMax = prevMax else: newMax = np.maximum(np.max(stats), prevMax) summary.append([itr.TOL, newMax]) prev = itr.lvls_count prevMax = newMax summary = np.array(summary) ax.set_xscale('log') ax.set_xlabel('TOL') ax.set_ylabel(r'$L$') ax.yaxis.set_major_locator(MaxNLocator(integer=True)) scatter = ax.scatter(summary[:, 0], summary[:, 1], *args, **kwargs) return summary, [scatter]
def plot_matrix(data, ax): im = ax.imshow( data.T, aspect='auto', origin='lower', interpolation='nearest') cax = make_axes_locatable(ax).append_axes("right", size="1%", pad=0.05) cb = pyplot.colorbar(im, cax=cax) tick_locator = ticker.MaxNLocator(nbins=5) cb.locator = tick_locator cb.ax.yaxis.set_major_locator(ticker.AutoLocator()) cb.update_ticks()
def Plot(Xs, predictions): # We will use subplots to display the results in a grid nrows = len(Xs) ncols = len(predictions) fig = plt.figure(figsize=(16, 8)) fig.canvas.set_window_title('Clustering data from ' + DATA) # Show each element in the plots returned from plt.subplots() for row, (row_label, X_x, X_y) in enumerate(Xs): for col, (col_label, y_pred) in enumerate(predictions): ax = plt.subplot(nrows, ncols, row * ncols + col + 1) if row == 0: plt.title(col_label) if col == 0: plt.ylabel(row_label) # Plot the decomposed input data and use the predicted # cluster index as the value in a color map. plt.scatter(X_x, X_y, c=y_pred.astype(np.float), cmap='prism', alpha=0.5) # Set the axis tick formatter to reduce the number of ticks ax.xaxis.set_major_locator(MaxNLocator(nbins=4)) ax.yaxis.set_major_locator(MaxNLocator(nbins=4)) # Let matplotlib handle the subplot layout plt.tight_layout() plt.show() plt.close()
def plot(outfn, a, genomeSize, base2chr, _windowSize, dpi=300, ext="svg"): """Save contact plot""" def format_fn(tick_val, tick_pos): """Mark axis ticks with chromosome names""" if int(tick_val) in base2chr: return base2chr[int(tick_val)] else: sys.stderr.write("[WARNING] %s not in ticks!\n"%tick_val) return '' # invert base2chr base2chr = {genomeSize-b: c for b, c in base2chr.iteritems()} # start figure fig = plt.figure() ax = fig.add_subplot(111) ax.set_title("Contact intensity plot [%sk]"%(_windowSize/1000,)) # label Y axis with chromosome names if len(base2chr)<50: ax.yaxis.set_major_formatter(FuncFormatter(format_fn)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) plt.yticks(base2chr.keys()) ax.set_ylabel("Chromosomes") else: ax.set_ylabel("Genome position") # label axes ax.set_xlabel("Genome position") plt.imshow(a+1, cmap=cm.hot, norm=LogNorm(), extent=(0, genomeSize, 0, genomeSize))# plt.colorbar() # save fig.savefig("%s.%s"%(outfn,ext), dpi=dpi, papertype="a4")
def showPlot(date, data, file_name): import matplotlib.ticker as mticker import matplotlib.dates as mdates import datetime fig, ax = plt.subplots() ax.xaxis.set_major_locator(mticker.MaxNLocator(5)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) print(date) # print(data) # date = [datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1, 1, 2, 0, 0), datetime.datetime(1, 1, 3, 0, 0), datetime.datetime(1, 1, 4, 0, 0)] # data = [1, 2, 3, 4] ax.plot(date, data) # fig.plot([1, 2, 3], [1, 1, 1]) fig.savefig(file_name) plt.close(fig) # def showPlotMix(data, file_name='test.png'): # fig, arr = plt.subplots(nrows=len(data), sharex=True) # print('showPlotMix') # for i, d in enumerate(data): # # print(len(d[0])) # for j, td in enumerate(d[0]): # # print(len(td)) # print(len(d[1][j])) # arr[i].plot(d[1][j], td) # fig.savefig(file_name) # plt.close(fig)
def showPlotMixSeparate(data, date, file_name='test.png'): print('shopPlotMixSeparate') import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, arr = plt.subplots() ax1 = arr ax1.xaxis.set_major_locator(mticker.MaxNLocator(5)) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) for j, td in enumerate(date): arr.plot(td, data[j]) fig.savefig(file_name) plt.close(fig)
def showPlotCompare(data, date, file_name): print("showPlotCompare") print(len(date)) import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, arr = plt.subplots(nrows=len(data), sharex=True) for i, d in enumerate(data): arr[i].xaxis.set_major_locator(mticker.MaxNLocator(7)) arr[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) # fig.suptitle('test title', fontsize=20) # arr[i].set_title('ax1 title') arr[i].plot(date, d) fig.savefig(file_name) plt.close(fig)
def showPlotLabelsCompare(data, date, labels, file_name): print("showPlotCompare") print(len(date)) import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, arr = plt.subplots(nrows=len(data), sharex=True) for i, d in enumerate(data): arr[i].xaxis.set_major_locator(mticker.MaxNLocator(7)) arr[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) # fig.suptitle('test title', fontsize=20) arr[i].set_title(labels[i]) arr[i].plot(date, d) fig.savefig(file_name) plt.close(fig)
def showPlotCompareSeparate(data, date, file_name): print("showPlotCompare") print(len(date)) import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, arr = plt.subplots(nrows=len(data), sharex=True) for i, d in enumerate(data): arr[i].xaxis.set_major_locator(mticker.MaxNLocator(7)) arr[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) arr[i].plot(date[i], d) fig.savefig(file_name) plt.close(fig)
def plot_hist(ax, data): """ Plot the histogram of differences between PS_RVSM and P9_STAT """ ix=np.where(data['WOW_IND'] == 0)[0] p9_stat=data['P9_STAT'][ix,:] ps_rvsm=data['PS_RVSM'][ix,:] delta=(p9_stat-ps_rvsm).ravel() _range=(-10.0, 10.0) _step_size=0.2 _bins= np.arange(_range[0], _range[1], _step_size) freq, bin_edges = np.histogram(delta, bins=_bins, range=_range) freq=freq.astype(np.float32)/delta.size*100. ax.bar((_bins[0:-1]+_bins[1:])/2.0, freq, width=_step_size, alpha=0.80, color='tomato') ax.grid(b='on') ax.set_xlabel('P9_STAT-PS_RVSM (mb)') ax.set_ylabel('percentage (%)') ax.text(0.1, 0.15, 'n=%i' % (delta.size), transform=ax.transAxes) rect = [0.2, 0.6, 0.25, 0.25] ax2 = plt.gcf().add_axes(rect, aspect='equal') ax2.plot(p9_stat.ravel(), ps_rvsm.ravel(), '.') ax2.set_xlabel('PS_RVSM (mb)') ax2.set_ylabel('P9_STAT (mb)') lim0, lim1 = 250, 1050 ax2.set_xlim((lim0, lim1)) ax2.set_ylim((lim0, lim1)) ax2.grid(b='on') lfit=linear_fit(data) ax2.set_title(lfit) # oplot 1:1 line plt.plot(plt.gca().get_xlim(), plt.gca().get_ylim(), linestyle='--', color='grey') ax2.yaxis.set_major_locator(MaxNLocator(4)) ax2.xaxis.set_major_locator(MaxNLocator(4)) return ax
def plot_formatter(self): ax=self.axs[0] # if ax.get_xlim()[1]-ax.get_xlim()[0] > 3600./86400.: minloc = mpl.dates.HourLocator() xformat = mpl.dates.DateFormatter('%H:%M') else: minloc = mpl.dates.MinuteLocator() xformat = mpl.dates.DateFormatter('%H:%M') #for ax in self.subplt: x_range=ax.get_xlim()[1]-ax.get_xlim()[0] _xlim=(ax.get_xlim()[0]-(x_range/100.)*3, ax.get_xlim()[1]+(x_range/100.)*3) ax.set_xlim(_xlim) for ax in self.axs: ax.grid(b='on') #TODO try: plt.setp(ax.get_xticklabels(), visible=False) except: pass ax.xaxis.set_major_formatter(xformat) ax.xaxis.set_major_locator(minloc) if ax.get_xticklabels().__len__() > 6: ax.xaxis.set_major_locator(MaxNLocator(6)) ax.yaxis.set_major_formatter(ScalarFormatter(useOffset=False)) #http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot #box = ax.get_position() #ax.set_position([box.x0, box.y0, box.width * 0.90, box.height]) #ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) #ax.legend() leg=ax.legend() leg.get_frame().set_alpha(0.5) plt.setp(ax.get_xticklabels(), visible=True) ax.set_xlabel('utc')
def plot_formatter(self): #for ax in self.subplt: ax=self.axs[0] y_range=ax.get_ylim()[1]-ax.get_ylim()[0] _ylim=(ax.get_ylim()[0]-(y_range/100.)*3, ax.get_ylim()[1]+(y_range/100.)*3) ax.set_ylim(_ylim) for ax in self.axs: ax.grid(b='on') plt.setp(ax.get_yticklabels(), visible=False) #http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot #box = ax.get_position() #ax.set_position([box.x0, box.y0 + box.height * 0.2, box.width, box.height * 0.8]) #ax.set_position([box.x0, box.y0, box.width, box.height * 0.8]) #ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12)) leg=ax.legend() leg.get_frame().set_alpha(0.5) if ax.get_xticklabels().__len__() > 5: ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_formatter(ScalarFormatter(useOffset=False)) #set y-axis lower limit to zero cur_ylim = ax.get_ylim() if cur_ylim[0] < 0: ax.set_ylim((0, cur_ylim[1])) plt.setp((self.axs[0].get_yticklabels()), visible=True) (self.axs[0]).set_ylabel('alt (m)')
def paper_single_ax(TW = 6.64, AR = 0.74, FF = 1.): #import matplotlib as mpl paper_single(TW=TW, AR=AR, FF=FF) f = plt.figure() ax = plt.subplot(111) plt.minorticks_on() ylocator6 = plt.MaxNLocator(5) xlocator6 = plt.MaxNLocator(6) ax.xaxis.set_major_locator(xlocator6) ax.yaxis.set_major_locator(ylocator6) return f, ax
def paper_double_ax(): #import matplotlib as mpl paper_single(TW = 12) f = plt.figure() ax = plt.subplot(111) plt.minorticks_on() ylocator6 = plt.MaxNLocator(5) xlocator6 = plt.MaxNLocator(6) ax.xaxis.set_major_locator(xlocator6) ax.yaxis.set_major_locator(ylocator6) return f, ax
def paper_double_mult_ax(nrows=1, ncols=1, setticks=True, **kwargs): #import matplotlib as mpl paper_single() TW = 6.97*2 AR = 0.74 FF = 1. mpl.rc('figure', figsize=(FF*TW, FF*TW*AR), dpi=200) mpl.rc('figure.subplot', left=0.1, right=0.97, bottom=0.1, top=0.97) mpl.rc('font', size=24.0, family="serif", serif="CM") f, ax = plt.subplots(nrows=nrows, ncols=ncols, **kwargs) plt.minorticks_on() if setticks: ylocator6 = plt.MaxNLocator(5) xlocator6 = plt.MaxNLocator(6) if len(ax.shape) > 1: for axrow in ax: for axcol in axrow: axcol.xaxis.set_major_locator(xlocator6) axcol.yaxis.set_major_locator(ylocator6) else: for axcol in ax: axcol.xaxis.set_major_locator(xlocator6) axcol.yaxis.set_major_locator(ylocator6) return f, ax
def make_ax3(): paper_single(TW=8, AR=0.9) f = plt.figure() from matplotlib.ticker import NullFormatter, MaxNLocator nullfmt = NullFormatter() # no labels # definitions for the axes left, width = 0.1, 0.65 bottom, height = 0.1, 0.6 bottom_h = bottom+height+0.02 left_h = left+width+0.02 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] ax = plt.axes(rect_scatter) plt.minorticks_on() axx = plt.axes(rect_histx) plt.minorticks_on() axy = plt.axes(rect_histy) plt.minorticks_on() # no labels axx.xaxis.set_major_formatter(nullfmt) axy.yaxis.set_major_formatter(nullfmt) axy.xaxis.set_major_locator(MaxNLocator(3)) axx.yaxis.set_major_locator(MaxNLocator(3)) return f,ax,axx,axy
def __init__(self, *args, **kwargs): self.locator = MaxNLocator(*args, **kwargs)