def draw_spectrogram(example_wav="musb_005_angela thomas wade_audio_model_without_context_cut_28234samples_61002samples_93770samples_126538.wav"): y, sr = librosa.load(example_wav, sr=None) spec = np.abs(librosa.stft(y, 512, 256, 512)) norm_spec = librosa.power_to_db(spec**2) black_time_frames = np.array([28234, 61002, 93770, 126538]) / 256.0 fig, ax = plt.subplots() img = ax.imshow(norm_spec) plt.vlines(black_time_frames, [0, 0, 0, 0], [10, 10, 10, 10], colors="red", lw=2, alpha=0.5) plt.vlines(black_time_frames, [256, 256, 256, 256], [246, 246, 246, 246], colors="red", lw=2, alpha=0.5) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) plt.colorbar(img, cax=cax) ax.xaxis.set_label_position("bottom") #ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x * 256.0 / sr)) #ax.xaxis.set_major_formatter(ticks_x) ax.xaxis.set_major_locator(ticker.FixedLocator(([i * sr / 256. for i in range(len(y)//sr + 1)]))) ax.xaxis.set_major_formatter(ticker.FixedFormatter(([str(i) for i in range(len(y)//sr + 1)]))) ax.yaxis.set_major_locator(ticker.FixedLocator(([float(i) * 2000.0 / (sr/2.0) * 256. for i in range(6)]))) ax.yaxis.set_major_formatter(ticker.FixedFormatter([str(i*2) for i in range(6)])) ax.set_xlabel("t (s)") ax.set_ylabel('f (KHz)') fig.set_size_inches(7., 3.) fig.savefig("spectrogram_example.pdf", bbox_inches='tight') #compute_mean_metrics("/mnt/windaten/Source_Estimates/endtoend/", False)
def retick_relabel_axis(ax, xticks, yticks, xformat_func=None, yformat_func=None): #set the xlim and ylim before calling this function so it can tick them. #other ticks are placed at xticks and yticks via format func # #def format_func(tick): # return "foo %s" % tick # if xformat_func is None: xformat_func = str if yformat_func is None: yformat_func = str #set to remove duplicates all_xticks = sorted(set(list(ax.get_xlim()) + xticks)) all_yticks = sorted(set(list(ax.get_ylim()) + yticks)) #defined labels xlbls = {i: xformat_func(i) for i in xticks} ylbls = {i: yformat_func(i) for i in yticks} #now remove labels on unlabeled ticks ('') if xlbls: ax.xaxis.set_major_formatter( mticker.FixedFormatter([xlbls.get(i, '') for i in all_xticks])) ax.xaxis.set_major_locator(mticker.FixedLocator(all_xticks)) if ylbls: ax.yaxis.set_major_formatter( mticker.FixedFormatter([ylbls.get(i, '') for i in all_yticks])) ax.yaxis.set_major_locator(mticker.FixedLocator(all_yticks))
def setupfunc(ax): xticks = ax.get_xticks() xticks = np.arange(0, 1.05, 0.05) yticks = ax.get_yticks() yticks = np.arange(-0.1, 1.7, 0.1) ax.set_yticks(yticks) ytickslabel = ['%.1f' % ele for ele in yticks] ytickslabel = [ytickslabel[i] if (i % 11 == 0 or i == 1) and i != 0 else '' for i in range(len(ytickslabel))] ax.set_yticklabels(ytickslabel) ax.set_xticks(xticks) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(16) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(16) majorLocator = MultipleLocator(0.25) minorLocator = MultipleLocator(0.05) ymajorLocator = MultipleLocator(0.5) yminorLocator = MultipleLocator(0.1) ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_major_locator(majorLocator) ax.yaxis.set_minor_locator(yminorLocator) ax.yaxis.set_major_locator(ymajorLocator) majors = ["0", "", "0.5", "", ""] ymajors = ["0", "", "1", "", ""] ax.xaxis.set_major_formatter(ticker.FixedFormatter(majors)) ax.yaxis.set_major_formatter(ticker.FixedFormatter(ymajors)) ax.yaxis.set_label_coords(-0.03, 0.4)
def generate_puzzle_image(puzzle: np.array): global images plt.rcParams["figure.figsize"] = (2, 2) fig, ax = plt.subplots() for (i, j), z in np.ndenumerate(puzzle): if z != 0: ax.text(j, i, '{:0.0f}'.format(z - 1), ha='center', va='center') ax.matshow(puzzle, cmap='Paired') minor_ticks = [.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5] ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(minor_ticks, minor=True) ax.grid(which='minor', linewidth=1.1, color='k') # Set major ticks locations major_ticks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ax.xaxis.set_major_locator(ticker.FixedLocator(major_ticks)) ax.yaxis.set_major_locator(ticker.FixedLocator(major_ticks)) # Customize minor tick labels ax.xaxis.set_minor_locator(ticker.FixedLocator(minor_ticks)) ax.yaxis.set_minor_locator(ticker.FixedLocator(minor_ticks)) char_array = np.arange(10) # Strip the '.0' and convert to string representation of number char_array = [str(x) for x in char_array] # Set major axis labels ax.xaxis.set_major_formatter(ticker.FixedFormatter(char_array)) ax.yaxis.set_major_formatter(ticker.FixedFormatter(char_array)) images.append(fig2data(fig))
def show_matrix(A, n): x = -0.2 y = 0.1 fig, ax = plt.subplots(figsize=(12, 9)) res = ax.imshow(pylab.array(A), cmap=plt.cm.jet, interpolation='nearest') for i, line in enumerate(A): for j, val in enumerate(line): # if val > 0: plt.text(j+x, i+y, "{}".format(val), fontsize=8) # pass plt.title("Matrix A, n: {}".format(n), y=1.08) plt.xlabel("x") ax.xaxis.tick_top() ax.xaxis.set_label_position("top") plt.ylabel("y") ax.xaxis.set_major_locator(ticker.FixedLocator((xrange(0, n)))) ax.xaxis.set_major_formatter(ticker.FixedFormatter((xrange(0, n)))) ax.yaxis.set_major_locator(ticker.FixedLocator((xrange(0, n)))) ax.yaxis.set_major_formatter(ticker.FixedFormatter((xrange(0, n)))) plt.subplots_adjust(bottom=0.1, top=0.85) #left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) cb = fig.colorbar(res) plt.show()
def PlotWmatrix(Wmatrix,figname,HighDiag=False,title=''): N=len(Wmatrix) myvmax=max(max([max(Wmatrix[i]) for i in range(len(Wmatrix))]),(-1)* min([min(Wmatrix[i]) for i in range(len(Wmatrix))])) myvmin=-myvmax if HighDiag: for neuron in range(N): Wmatrix[neuron,neuron]=myvmax fig=plt.figure(); ax=fig.add_subplot(111); pplot=ax.pcolor(Wmatrix, cmap='jet', vmin=myvmin, vmax=myvmax); ax.set(aspect=1) ax.set_ylabel("Presynaptic") ax.set_xlabel("Postsynaptic") ax.set(frame_on=False, aspect=1, xticks=range(1,N+1), yticks=range(1,N+1)) ax.invert_yaxis() ax.xaxis.set_label_position('top') ax.xaxis.tick_top() tickpos=list(np.array(range(N))+0.5) ticknames=[str(i) for i in range(1,N+1)] ax.tick_params(axis=u'both', which=u'both',length=0) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.xaxis.set_minor_locator(ticker.FixedLocator(tickpos)) ax.xaxis.set_minor_formatter(ticker.FixedFormatter(ticknames)) ax.tick_params(axis=u'both', which=u'both',length=0) ax.yaxis.set_major_formatter(ticker.NullFormatter()) ax.yaxis.set_minor_locator(ticker.FixedLocator(tickpos)) ax.yaxis.set_minor_formatter(ticker.FixedFormatter(ticknames)) fig.suptitle(title) fig.colorbar(pplot) pylab.savefig(figname)
def plot_matrix(matrix, yaxis=None, xaxis=None, **kwargs): """ Prepare a matrix plot """ # Make new matplotlib figure. fig = pyplot.figure() ax = fig.add_subplot(1, 1, 1) fig.subplots_adjust(top=0.85) cax = ax.matshow(matrix, interpolation=kwargs.get('interpolation', 'bilinear')) cb = fig.colorbar(cax) cb.set_label(kwargs.get('cblabel', '')) # Set figure and axis titles fig.suptitle(kwargs.get('title', '')) ax.set_title(kwargs.get('subtitle', ''), fontsize=8) ax.set_ylabel(kwargs.get('ylabel', ''), fontsize=10) ax.set_xlabel(kwargs.get('xlabel', ''), fontsize=10) # Set the ticks and tick labels. Reverse y axis to align x/y origin yaxis_locs = range(0, len(yaxis), int(len(yaxis) / 10)) ax.yaxis.set_ticks_position('left') ax.yaxis.set_major_locator(mticker.FixedLocator(yaxis_locs)) ax.yaxis.set_major_formatter(mticker.FixedFormatter(['%1.2f' % yaxis[x] for x in yaxis_locs])) ax.invert_yaxis() xaxis_locs = range(0, len(xaxis), int(len(xaxis) / 10)) ax.xaxis.set_ticks_position('bottom') ax.xaxis.set_major_locator(mticker.FixedLocator(xaxis_locs)) ax.xaxis.set_major_formatter(mticker.FixedFormatter(['%1.2f' % xaxis[x] for x in xaxis_locs])) ax.grid(None) return fig
def _reset_xticklabels(self): ''' For StackedGroupedBar plots the xticklabels don't include the bar names ''' self.ax.xaxis.set_major_locator( mticker.FixedLocator(np.arange(len(self.plotdata.data)))) self.ax.xaxis.set_major_formatter( mticker.FixedFormatter( self.plotdata._data.xs( self.plotdata._data.index.get_level_values(-1)[0], level=-1).index)) plt.setp(self.ax.get_xticklabels(), rotation=self.xticklabel_rotation) self.ax.xaxis.set_minor_locator(mticker.FixedLocator(self.xpos_minor)) self.ax.xaxis.set_minor_formatter( mticker.FixedFormatter( np.repeat(self.list_bars, len(self.plotdata.xpos)))) plt.setp(self.ax.get_xminorticklabels(), rotation=self.xticklabel_rotation) self.ax.tick_params(axis='x', direction='in', which='minor', pad=-15) for tick in self.ax.xaxis.get_minor_ticks(): tick.label1.set_verticalalignment('bottom')
def time_formatterSetting(ax, times, majorStep=20, majorOffset=0, timeFormat='%Y-%m-%d', minor=False, minorStep=5, minorOffset=0): ''' 设置横轴时间轴的格式,与FixedFormatter相配合 @param: ax: 当前图对应的axes times: 日期列表,要求可迭代,且列表中元素为对应的日期时间类型,原则上应该 为datetime.datetime类型,但是如果有strftime方法返回字符串也可 majorStep: 主刻度之间的下标间隔,e.g., 5可以表示为[0, 5, 10,...] majorOffset: 根据该公式选择刻度,即(index-majorOffset)%majorStep==0, 默认为1 timeFormat: 时间解析的形式,按照datetime要求的形式解析,默认为解析为 yyyy-mm-dd的日期形式 minor: 是否设置次刻度,默认为False,即不设置 minorStep: 同majorStep,默认为5 minorOffset: 同majorOffset,默认为1 @return: res: 按照给定形式解析后的时间字符串列表 同时设置刻度表示的日期形式 ''' strDates = list(map(lambda x: x.date().strftime(timeFormat), times)) majorDates = [strDates[i] for i in range(len(strDates)) if (i-majorOffset) % majorStep == 0] formatter = ticker.FixedFormatter(majorDates) ax.xaxis.set_major_formatter(formatter) if minor: minorDates = [strDates[i] for i in range(len(strDates)) if (i-minorOffset) % minorStep == 0] minorFormatter = ticker.FixedFormatter(minorDates) ax.xaxis.set_minor_formatter(minorFormatter) return strDates
def setupfunc(ax): xticks = ax.get_xticks() xticks = np.arange(0, 40, 5) yticks = ax.get_yticks() print min(yticks), max(yticks) yticks = np.linspace(-0.2, (max(yticks)), 19) ax.set_yticks(yticks) ytickslabel = ['%.1f' % ele for ele in yticks] ytickslabel = [ytickslabel[i] if (i % 11 == 0 or i == 1) and i != 0 else '' for i in range(len(ytickslabel))] ax.set_yticklabels(ytickslabel) ax.set_xticks(xticks) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(16) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(16) ax.yaxis.set_label_coords(-0.05, 0.5) majorLocator = MultipleLocator(15.0) minorLocator = MultipleLocator(5) ymajorLocator = MultipleLocator(15) yminorLocator = MultipleLocator(5) ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_major_locator(majorLocator) ax.yaxis.set_minor_locator(yminorLocator) ax.yaxis.set_major_locator(ymajorLocator) majors = ["0", "", "30", "", "4"] ymajors = ["0", "", "30", "", "4"] ax.xaxis.set_major_formatter(ticker.FixedFormatter(majors)) ax.yaxis.set_major_formatter(ticker.FixedFormatter(ymajors))
def PlotOneMapProjections(DirectConn,ProjectConn,figname,titletext,colors='no'): rc('text', usetex=True) rc('font', family='serif') N=len(DirectConn) cmap1,vmin1,vmax1=maphatchBase() cmap2,vmin2,vmax2=maphatch() cmapc,vminc,vmaxc= map_projections() MapProj=np.zeros([N,N]) for i in range(N): for j in range(N): if i !=j: if DirectConn[i][j]==True: MapProj[i,j]=1 else: if ProjectConn[i][j]==1: MapProj[i,j]=2 elif ProjectConn[i][j]==2: MapProj[i,j]=3 elif DirectConn[i][j]==False and ProjectConn[i][j]==0: MapProj[i,j]=0 else: MapProj[i,j]=4 fig=plt.figure() ax=fig.add_subplot(111) if colors=='no': ax.pcolor(MapProj, cmap=cmap1, vmin=0, vmax=vmax1, edgecolors='black',hatch='///') ax.pcolor(MapProj, cmap=cmap2, vmin=0, vmax=vmax2, edgecolors='black') else: ax.pcolor(MapProj, cmap=cmapc, vmin=0, vmax=vmaxc, edgecolors='black') ax.set_ylabel("Presynaptic") ax.set_xlabel("Postsynaptic") ax.set(frame_on=False, aspect=1, xticks=range(1,N+1), yticks=range(1,N+1)) ax.invert_yaxis() ax.xaxis.set_label_position('top') ax.xaxis.tick_top() tickpos=list(np.array(range(N))+0.5) ticknames=[str(i) for i in range(1,N+1)] ax.tick_params(axis=u'both', which=u'both',length=0) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.xaxis.set_minor_locator(ticker.FixedLocator(tickpos)) ax.xaxis.set_minor_formatter(ticker.FixedFormatter(ticknames)) ax.tick_params(axis=u'both', which=u'both',length=0) ax.yaxis.set_major_formatter(ticker.NullFormatter()) ax.yaxis.set_minor_locator(ticker.FixedLocator(tickpos)) ax.yaxis.set_minor_formatter(ticker.FixedFormatter(ticknames)) ax.set_title(titletext, fontsize=14,y=1.08) pylab.savefig(figname+'.pdf', format='pdf', dpi=1000)
def set_ticks(ax, slots, amps=16): """Set the tick labels, centering the slot names between amps 1 and 16.""" major_locs = [i*amps - 0.5 for i in range(len(slots) + 1)] minor_locs = [amps//2 + i*amps for i in range(len(slots))] for axis in (ax.xaxis, ax.yaxis): axis.set_tick_params(which='minor', length=0) axis.set_major_locator(ticker.FixedLocator(major_locs)) axis.set_major_formatter(ticker.FixedFormatter(['']*len(major_locs))) axis.set_minor_locator(ticker.FixedLocator(minor_locs)) axis.set_minor_formatter(ticker.FixedFormatter(slots))
def ttp_style( ax, df_, padding=0, rotate_xticks=True, ): #place and null major ticks (we still need them for the grid) ax.xaxis.set_major_locator(ticker.LinearLocator(len(df_.index) + 1)) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.yaxis.set_major_locator(ticker.LinearLocator(len(df_.columns) + 1)) ax.yaxis.set_major_formatter(ticker.NullFormatter()) #place and format minor ticks (used to substitute for centered major tick labels) ax.xaxis.set_minor_locator(ticker.IndexLocator(1, 0.5)) ax.xaxis.set_minor_formatter(ticker.FixedFormatter(df_.index)) ax.yaxis.set_minor_locator(ticker.IndexLocator(1, 0.5)) ax.yaxis.set_minor_formatter(ticker.FixedFormatter(df_.columns)) #remove bottom and top small tick lines plt.tick_params(axis='x', which='both', bottom='off', top='off', left='off', right='off') plt.tick_params(axis='y', which='both', bottom='off', top='off', left='off', right='off') #Set only 7th minor tick label to visible for label in ax.xaxis.get_minorticklabels(): label.set_visible(False) for label in ax.xaxis.get_minorticklabels()[padding::7]: label.set_visible(True) for label in ax.yaxis.get_minorticklabels(): label.set_visible(False) for label in ax.yaxis.get_minorticklabels(): label.set_visible(True) #Rotate xticks if rotate_xticks: plt.setp(ax.xaxis.get_minorticklabels(), rotation=90) # create grid ax.xaxis.grid(True, which='major', color='1', linestyle='-') ax.yaxis.grid(True, which='major', color='1', linestyle='-') #delete all spines for spine in ["right", "left", "top", "bottom"]: ax.spines[spine].set_visible(False) return ax
def dftoHeatmap(df, numsplits, figsize, saveDir): iSave = [] fms = [] for k in range(0, numsplits): if k == 0: indStart = 0 indEnd = int(len(df) / numsplits) else: indStart = k * int(len(df) / numsplits) + 1 indEnd = (k + 1) * int(len(df) / numsplits) ii = df.iloc[indStart:indEnd, 0] for j in range(0, len(df.columns)): if j > 0: ii = np.vstack((ii, df.iloc[indStart:indEnd, j].values)) iSave.extend([ii]) fms.extend([list(df.index[indStart:indEnd])]) # plot for each split fig, ax = plt.subplots(figsize=figsize) plt.pcolor(ii.T, cmap='YlOrRd', vmin=0, vmax=3) cb = plt.colorbar() cb.ax.set_title('Net I&I') # format axis ax.set_xticks(range(0, len(df.columns) + 1)) ax.set_yticks(range(0, len(fms[k]) + 1)) ax.grid(b=True, color='xkcd:blue grey', which='major', linewidth=0.5, alpha=0.5) # Hide major tick labels ax.xaxis.set_major_formatter(ticker.NullFormatter()) # Customize minor tick labels ax.xaxis.set_minor_locator( ticker.FixedLocator( list(np.linspace(0.5, len(df.columns) - 0.5, len(df.columns))))) ax.xaxis.set_minor_formatter(ticker.FixedFormatter(list(df.columns))) ax.yaxis.set_major_formatter(ticker.NullFormatter()) ax.yaxis.set_minor_locator( ticker.FixedLocator( list(np.linspace(0.5, len(df.index) - 0.5, len(df.index))))) ax.yaxis.set_minor_formatter(ticker.FixedFormatter(list(df.index))) saveName = saveDir + 'heatmap_' + fms[k][0] + '-' + fms[k][-1] + '.png' plt.savefig(saveName) plt.close(fig)
def compareMatrix(): ax=plt.gca() ax.tick_params(axis=u'both', which=u'both',length=0) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.xaxis.set_minor_locator(ticker.FixedLocator(mx)) ax.xaxis.set_minor_formatter(ticker.FixedFormatter(['YSU (1)','MYJ (2)','MYNN (5)','CAM5 (9)'])) plt.xlabel('PBL scheme') ax.yaxis.set_major_formatter(ticker.NullFormatter()) ax.yaxis.set_minor_locator(ticker.FixedLocator(my)) ax.yaxis.set_minor_formatter(ticker.FixedFormatter(['KF (1)','BMJ (2)','GF (5)','CAM5 (7)'])) plt.ylabel('Cu scheme') plt.colorbar() plt.gca().invert_yaxis()
def plot(self, figsize=(15, 50), tick_kwargs={}, major_kwargs={}, minor_kwargs={}): """Make an image figure with major and minor depth ticks. Parameters ---------- figsize : tuple(int) Size of matplotlib figure to plot on. Note: at default DPI of 100, 650 is about as large as common image formats will support saving (~2^16 pixels). tick_kwargs: Parameters for tick creation: 'major' and 'minor' options for `*_precision` and `*_format_str`. See `viz.make_depth_ticks()`. major/minor_kwargs: Parameters for tick size and appearance. Passed to `ax.tick_params`. Returns ------- fig, ax Matplotlib figure and axis with image + ticks plotted. """ # Update any new tick kwargs tick_kwargs = utils.strict_update(defaults.DEPTH_TICK_ARGS, tick_kwargs) major_kwargs = utils.strict_update(defaults.MAJOR_TICK_PARAMS, major_kwargs) minor_kwargs = utils.strict_update(defaults.MINOR_TICK_PARAMS, minor_kwargs) fig, ax = plt.subplots(figsize=figsize) major_ticks, major_locs, minor_ticks, minor_locs = make_depth_ticks( self.depths, **tick_kwargs) ax.yaxis.set_major_formatter(ticker.FixedFormatter((major_ticks))) ax.yaxis.set_major_locator(ticker.FixedLocator((major_locs))) ax.yaxis.set_minor_formatter(ticker.FixedFormatter((minor_ticks))) ax.yaxis.set_minor_locator(ticker.FixedLocator((minor_locs))) ax.tick_params(which="major", **major_kwargs) ax.tick_params(which="minor", **minor_kwargs) ax.set_xticks([], []) ax.grid(False) ax.imshow(self.img) return fig, ax
def make_2d_ticks(ax, boundaries = None,transformed_formatters=False,scale_1 = 1, scale_2=1, num_1 = 8, num_2 = 8, x_mid_1=1, x_mid_2=1): if boundaries is None: boundaries = [None]*2 transf = ft.partial(compactification, x_mid=x_mid_1) inv_transf = ft.partial(inv_compactification, x_mid=x_mid_1) # xaxis - ticks if boundaries[0] is None: start, stop = 0, np.infty ax.set_xlim(0,1) else: start, stop = inv_transf(boundaries[0]) ax.set_xlim(*boundaries[0]) formatters, locators = ays_general.transformed_space(transf, inv_transf, axis_use=True, scale=scale_1,start=start, stop=stop, num=num_1) if transformed_formatters: new_formatters = [] for el, loc in zip(formatters, locators): if el: new_formatters.append("{:4.2f}".format(loc)) else: new_formatters.append(el) formatters = new_formatters #print(locators, formatters) ax.xaxis.set_major_locator(ticker.FixedLocator(locators)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(formatters)) # yaxis - ticks transf = ft.partial(compactification, x_mid=x_mid_2) inv_transf = ft.partial(inv_compactification, x_mid=x_mid_2) if boundaries[1] is None: start, stop = 0, np.infty ax.set_ylim(0,1) else: start, stop = inv_transf(boundaries[1]) ax.set_ylim(*boundaries[1]) formatters, locators = ays_general.transformed_space(transf, inv_transf, axis_use=True, scale=scale_2, start=start, stop=stop, num=num_2) if transformed_formatters: new_formatters = [] for el, loc in zip(formatters, locators): if el: new_formatters.append("{:4.2f}".format(loc)) else: new_formatters.append(el) formatters = new_formatters ax.yaxis.set_major_locator(ticker.FixedLocator(locators)) ax.yaxis.set_major_formatter(ticker.FixedFormatter(formatters))
def _prepare_plot(x_label='offer A', y_label='offer B', title='', z_label=None, z_ticks=None, ΔA=(0, 20), ΔB=(0, 20)): fig = plt.figure(figsize=(9, 10)) ax = fig.gca(projection='3d') ax.set_xlim(ΔA) ax.set_ylim(ΔB) ax.set_autoscaley_on(False) ax.invert_xaxis() ax.grid(linestyle='dashed') ax.grid(which='major', alpha=0.1) ax.view_init(azim=-35, elev=5) # Customize the z axis. # ax.set_zlim(-1.01, 1.01) # ax.zaxis.set_major_locator(IndexLocator(0.5, 0)) # ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # White background for item in (ax.xaxis, ax.yaxis, ax.zaxis): item.set_pane_color((1.0, 1.0, 1.0, 1.0)) item.label.set_size(7) for item in (ax.get_xticklabels(), ax.get_yticklabels(), ax.get_zticklabels()): plt.setp(item, fontsize=7) # Ticks x_ticks = [5*i for i in range(int(ΔA[1]/5)+1)] ax.xaxis.set_major_locator(ticker.FixedLocator(x_ticks)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(['{:d}'.format(tick) for tick in x_ticks])) y_ticks = [5*i for i in range(int(ΔB[1]/5)+1)] ax.yaxis.set_major_locator(ticker.FixedLocator(y_ticks)) ax.yaxis.set_major_formatter(ticker.FixedFormatter(['{:d}'.format(tick) for tick in y_ticks])) if z_ticks is not None: ax.zaxis.set_major_locator(ticker.FixedLocator(z_ticks)) # Labels if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: ax.set_ylabel(y_label) if z_label is not None: ax.set_zlabel(z_label) plt.title(title) return fig, ax
def graph_frequency(alignments, readcount): """ Make a histogram of normally distributed random numbers and plot the analytic PDF over it """ fig = plt.figure() ax = fig.add_subplot(111) x = np.arange(len(readcount)) plt.bar(x, readcount.values()) # Set the labels for the x-axis ax.xaxis.set_major_locator(ticker.FixedLocator(x+.75)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(readcount.keys())) # Set the angle of the X-axis labels. fig.autofmt_xdate(rotation=50) ax.set_xlabel('Genes') ax.set_ylabel('number of alignments') ax.set_title(r'$\mathrm{Count\ of\ read\ alignments\ per\ gene}$') plt.show()
def set_legends(fig, ax, image_size, query, ysubtitle, title): #remove frame bottom_side = ax.spines["bottom"] bottom_side.set_visible(False) left_side = ax.spines["left"] left_side.set_visible(False) right_side = ax.spines["right"] right_side.set_visible(False) top_side = ax.spines["top"] top_side.set_visible(False) #display tickers ax.xaxis.set_major_locator(ticker.NullLocator()) numlabel = map(lambda x: image_size[0] / 2 + (x) * (image_size[0] + 1), range(len(query))) ax.yaxis.set_major_locator(ticker.FixedLocator(numlabel)) labels = map(lambda x: x, list(sorted(query))) ax.yaxis.set_major_formatter(ticker.FixedFormatter(labels)) #display legends plt.suptitle(title, fontsize=15) plt.title("Memory", loc='right', fontsize=13) if ysubtitle == "": plt.ylabel("Inputs", fontsize=15) #left_side.set_visible(True) else: plt.title("Inputs", loc='left', fontsize=13) plt.ylabel(ysubtitle, fontsize=15)
def set_yticks_fixed(ax, locs, labels='%g'): """ Set custom yticks at fixed positions. Parameters ---------- ax: matplotlib axes Axes on which the yticks are set. locs: list of floats Locations of yticks. labels: string or list of strings Either a format string (e.g. '%.1f') or a list of labels for each tick position in `locs`. Notes ----- On logarithmic axis you may want to turn off minor ticks, e.g. via `ax.set_minor_yticks_off()`. See also -------- `set_xticks_fixed()` """ ax.yaxis.set_major_locator(ticker.FixedLocator(locs)) if isinstance(labels, (tuple, list)): ax.yaxis.set_major_formatter(ticker.FixedFormatter(labels)) else: ax.yaxis.set_major_formatter(ticker.FormatStrFormatter(labels))
def init_axes(self): """Sets configuration for axes. Creates a subplot for every data channel and configures the appropriate labels and tick marks.""" axes = self.figure.subplots(len(self.data_indices), 1, sharex=True) for i, channel in enumerate(self.data_indices): ch_name = self.channels[channel] axes[i].set_frame_on(False) axes[i].set_ylabel( ch_name, rotation=0, labelpad=self.yaxis_label_space, fontsize=self.yaxis_label_fontsize) # x-axis shows seconds in 0.5 sec increments tick_names = np.arange(0, self.seconds, 0.5) ticks = [(self.samples_per_second * sec) / self.downsample_factor for sec in tick_names] axes[i].xaxis.set_major_locator(ticker.FixedLocator(ticks)) axes[i].xaxis.set_major_formatter( ticker.FixedFormatter(tick_names)) axes[i].tick_params( axis='y', which='major', labelsize=self.yaxis_tick_fontsize) for tick in axes[i].get_yticklabels(): tick.set_fontname(self.yaxis_tick_font) axes[i].grid() return axes
def label_axes_with_config_types(config_types): names = sorted(set(config_types)) major_tics = [] minor_tics = [] idx1 = 0 for name1, name2 in zip(names, names[1:] + [None]): idx1 = config_types.index(name1) if name2 is not None: idx2 = config_types.index(name2) else: idx2 = len(config_types) half = (idx2 + idx1) / 2 minor_tics.append(half) major_tics.append(idx2) import matplotlib.ticker as ticker ax = gca() ax.xaxis.set_major_locator(ticker.FixedLocator(major_tics)) ax.xaxis.set_minor_locator(ticker.FixedLocator(minor_tics)) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.xaxis.set_minor_formatter(ticker.FixedFormatter(names)) for tick in ax.xaxis.get_minor_ticks(): tick.tick1line.set_markersize(0) tick.tick2line.set_markersize(0) tick.label1.set_horizontalalignment('center') tick.label1.set_rotation(90) draw()
def __init__(self): # Initializing the subplots and axes self.fig, self.ax = plt.subplots() self.fig.canvas.set_window_title('Your Generated Schedule') # Setting the title - note using plt plt.title('Your Generated Schedule') # Setting it to grid mode plt.grid() # Setting axes names plt.ylabel('Times') plt.xlabel('Days') # Setting formatter to null and then to days self.ax.xaxis.set_major_formatter(ticker.NullFormatter()) self.ax.xaxis.set_minor_locator(ticker.FixedLocator(x_ticks)) # Setting min and max for x self.ax.set_xlim(xmin=0, xmax=5) # Setting xaxis formatter to days self.ax.xaxis.set_minor_formatter(ticker.FixedFormatter(day_list)) # Setting spacing to half an hour self.ax.yaxis.set_major_locator(loc) # Using specific function for parsing hours self.ax.yaxis.set_major_formatter(ticker.FuncFormatter(self.time_format)) # Set limit to go from 0 to 24 self.ax.set_ylim(ymin=0, ymax=24) # Set the yaxis to inverted mode like WebReg self.ax.invert_yaxis()
def setup_ax(ax, elev, azim): ''' Basic formatting for 3D axes Parameters _________ ax : matplotlib.axes._subplots.AxesSubplot Axes instance elev, azim : int elevation and azimuth angles for viewing 3D axis Returns _______ ax : matplotlib.axes._subplots.AxesSubplot Updated Axes instance ''' ax.view_init(elev=elev, azim=azim) # Set view angle # Gamma ticks and label ax.xaxis.set_major_locator(tck.MultipleLocator(0.1)) ax.xaxis.set_label_text(r'$\gamma(x,y)$ [nm/nm]') # Theta ticks and label ax.yaxis.set_major_locator(tck.LinearLocator(3)) ax.yaxis.set_major_formatter( tck.FixedFormatter((r'0', r'$\pi$', r'$2\pi$'))) ax.yaxis.set_label_text(r'$\theta (x,y)$') # CRLB ticks ax.zaxis.set_major_locator(tck.MaxNLocator(5)) return ax
def plot_percentiles(percentiles, labels): fig, ax = plt.subplots(figsize=(16, 8)) # plot values for data in percentiles: ax.plot(data['Percentile'], data['Latency']) # set axis and legend ax.grid() ax.set(xlabel='Percentile', ylabel='Latency (milliseconds)', title='Latency Percentiles (lower is better)') ax.set_xscale('logit') plt.xticks([0.25, 0.5, 0.9, 0.99, 0.999, 0.9999, 0.99999, 0.999999]) majors = [ "25%", "50%", "90%", "99%", "99.9%", "99.99%", "99.999%", "99.9999%" ] ax.xaxis.set_major_formatter(ticker.FixedFormatter(majors)) ax.xaxis.set_minor_formatter(ticker.NullFormatter()) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, borderaxespad=0., labels=labels) return fig, ax
def _draw_chart(self, df): data = df.head(30) date = pd.to_datetime(data.index) xlist = [v.strftime("%m/%d") for v in date] self.chart.clear() ax = self.chart.add_subplot(111) dlist = range(len(xlist)) ax.xaxis.set_major_locator(ticker.FixedLocator(dlist)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(xlist)) ax.invert_xaxis() mpl.candlestick2_ohlc(ax, data["Open"], data["High"], data["Low"], data["Close"], width=0.5, colorup='r', colordown='b') #ax.legend(loc='best') ax.grid() self.canvas.draw()
def _reset_xticklabels(self): self.ax.xaxis.set_major_locator( mticker.FixedLocator(np.arange(len(self.plotdata.data)))) self.ax.xaxis.set_major_formatter( mticker.FixedFormatter(self.plotdata._data.index.tolist())) plt.setp(self.ax.get_xticklabels(), rotation=self.xticklabel_rotation)
def display_chart(self): if not len(self.chart): return self.ax.clear() # Axis ticker formatting if len(self.chart) // 30 > len(self.chart_locator) - 1: for index in range( len(self.chart_locator) * 30, len(self.chart), 30): time_format = self.chart.index[index].strftime('%H:%M') self.chart_locator.append(index) self.chart_formatter.append(time_format) self.ax.xaxis.set_major_locator(ticker.FixedLocator( self.chart_locator)) self.ax.xaxis.set_major_formatter( ticker.FixedFormatter(self.chart_formatter)) # Axis yticks & lines max_price = self.chart.High.max() min_price = self.chart.Low.min() if max_price > self.top_price or min_price < self.bottom_price: self.top_price = math.ceil( max_price / self.interval) * self.interval self.bottom_price = math.floor( min_price / self.interval) * self.interval self.interval_prices = np.arange(self.bottom_price, self.top_price + self.interval, self.interval) self.loss_cut_prices = np.arange( self.bottom_price + self.interval - self.loss_cut, self.top_price, self.interval) self.ax.grid(axis='x', alpha=0.5) self.ax.set_yticks(self.interval_prices) for price in self.interval_prices: self.ax.axhline(price, alpha=0.5, linewidth=0.2) for price in self.loss_cut_prices: self.ax.axhline(price, alpha=0.4, linewidth=0.2, color='Gray') # Current Price Annotation current_time = len(self.chart) current_price = self.chart.Close.iloc[-1] if self.chart_item_code[:3] == FUTURES_CODE: formatted_current_price = format(current_price, ',.2f') else: formatted_current_price = format(current_price, ',') # self.ax.text(current_time + 2, current_price, format(current_price, ',')) self.ax.text(current_time + 2, current_price, formatted_current_price) # Draw Chart candlestick2_ohlc(self.ax, self.chart.Open, self.chart.High, self.chart.Low, self.chart.Close, width=0.4, colorup='red', colordown='blue') self.fig.tight_layout() self.canvas.draw()
def plotDensityDistribution(self, ax=None): '''This plots density vs. depth distribution of the column. Parameters ---------- ax: axes The 2D axes for plotting the density vs. depth distribution ''' if (ax is None): fig, ax = plt.subplots(ncols=1, nrows=1) x_ticks = self.depths xticks_minor = [] for i in range(len(self.depths) - 1): xticks_minor.append((self.depths[i] + self.depths[i + 1]) / 2) xlbls = list(self.layer_df.region.unique()) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.xaxis.set_minor_locator(ticker.FixedLocator(xticks_minor)) ax.xaxis.set_minor_formatter(ticker.FixedFormatter(xlbls)) ax.set_xticks(self.depths) ax.grid(linestyle='--') ax.grid(linestyle='--') plt.plot(self.znew, self.depth_distribution(self.znew), '--') plt.xlabel("Depth (microns)") plt.ylabel("Density (10^3/mm^3)")