def init_sp(self, title='', xlabel='', ylabel='', xlim=None, ylim=None, xscale='linear', yscale='linear', *args, **kwargs): ''' initialize the sp[n] initialize ax[0]: .lG, .lGfit, .lp, .lpfit plot initialize ax[1]: .lB, .lBfit, plot ''' self.initax_xyy() self.ax[0].margins(x=0) self.ax[1].margins(x=0) self.ax[0].margins(y=.05) self.ax[1].margins(y=.05) # self.ax[0].autoscale() # self.ax[1].autoscale() self.l['lG'] = self.ax[0].plot( [], [], marker='.', linestyle='none', markerfacecolor='none', color=color[0] ) # G self.l['lB'] = self.ax[1].plot( [], [], marker='.', linestyle='none', markerfacecolor='none', color=color[1] ) # B # self.l['lGpre'] = self.ax[0].plot( # [], [], # marker='.', # linestyle='none', # markerfacecolor='none', # color='gray' # ) # previous G # self.l['lBpre'] = self.ax[1].plot( # [], [], # marker='.', # linestyle='none', # markerfacecolor='none', # color='gray' # ) # previous B # self.l['lPpre'] = self.ax[1].plot( # [], [], # marker='.', # linestyle='none', # markerfacecolor='none', # color='gray' # ) # previous polar self.l['lGfit'] = self.ax[0].plot( [], [], color='k' ) # G fit self.l['lBfit'] = self.ax[1].plot( [], [], color='k' ) # B fit self.l['strk'] = self.ax[0].plot( [], [], marker='+', linestyle='none', color='r' ) # center of tracking peak self.l['srec'] = self.ax[0].plot( [], [], marker='x', linestyle='none', color='g' ) # center of recording peak self.l['ltollb'] = self.ax[0].plot( [], [], linestyle='--', color='k' ) # tolerance interval lines self.l['ltolub'] = self.ax[0].plot( [], [], linestyle='--', color='k' ) # tolerance interval lines self.l['lP'] = self.ax[0].plot( [], [], marker='.', linestyle='none', markerfacecolor='none', color=color[0] ) # polar plot self.l['lPfit'] = self.ax[0].plot( [], [], color='k' ) # polar plot fit self.l['strk'] = self.ax[0].plot( [], [], marker='+', linestyle='none', color='r' ) # center of tracking peak self.l['srec'] = self.ax[0].plot( [], [], marker='x', linestyle='none', color='g' ) # center of recording peak self.l['lsp'] = self.ax[0].plot( [], [], color=color[2] ) # peak freq span # self.ax[0].xaxis.set_major_locator(plt.AutoLocator()) # self.ax[0].xaxis.set_major_locator(plt.LinearLocator()) # self.ax[0].xaxis.set_major_locator(plt.MaxNLocator(3)) # add text self.txt['sp_harm'] = self.fig.text(0.01, 0.98, '', va='top',ha='left') # option: weight='bold' self.txt['chi'] = self.fig.text(0.01, 0.01, '', va='bottom',ha='left') # set label of ax[1] self.set_ax(self.ax[0], title=title, xlabel=r'$f$ (Hz)',ylabel=r'$G_P$ (mS)') self.set_ax(self.ax[1], xlabel=r'$f$ (Hz)',ylabel=r'$B_P$ (mS)') self.ax[0].xaxis.set_major_locator(ticker.LinearLocator(3))
for xlim in xlims: axarr[i, j].plot(df[xlim[0]:xlim[1]], c='k', linewidth=1.1) axarr[i, j].set_xlim(xlim) ymax = float(df[(df.index > xlim[0]) & (df.index < xlim[1])].max().values) axarr[i, j].set_ylim(0 - ymax * 0.05, ymax * 1.05) """ axarr[i,j].text(0.95,0.9,mode+" "+shmode, size=labelsize, horizontalalignment = "right", verticalalignment = "top", transform=axarr[i,j].transAxes, bbox=dict(facecolor='w', alpha=0.5)) """ if j == 2: axarr[i, j].xaxis.set_major_locator(ticker.LinearLocator(3)) sample2 = mode + "-" + polarity[:3] + "-" + sample df2 = pd.read_excel(assignments + sample2 + ".xlsx") df2["NormAbun"] = df2[sample2] / df2[sample2].max() * 100 df2 = df2[df2['C'] != 0] df2 = df2[(df2['Mass'] < xlim[1]) & (df2['Mass'] > xlim[0])] for index, data in df2.iterrows(): if data['C13'] > 0: symbol = "+" else: symbol = "•" #"▼"#"•" axarr[i, j].text(data['Mass'] - 0.0006, data['NormAbun'], symbol, size=int(labelsize * 1.1), color='red',
linestyle='-', linewidth='1.00', label='Filtered') ax1.plot(y_value[0, :], linestyle='-', linewidth='1.00', label='Measured') ax1.legend(loc='upper right', fontsize=6) ax1.grid(b=True, which='both', color='silver', linestyle='-') ax1.set_ylim([Vmin, Vmax]) ax1.set_xlim([0, b - 1]) ax1.set_ylabel('Intensity, a.u.', fontsize=6, fontweight='bold') ax1.set_xlabel('UTC Date and time, YYYY-MM-DD HH:MM:SS.ms', fontsize=6, fontweight='bold') ax1.xaxis.set_major_locator(mtick.LinearLocator(7)) text = ax1.get_xticks().tolist() for i in range(len(text)): k = int(text[i]) text[i] = str(date_time[k][0:11] + '\n' + date_time[k][11:23]) ax1.set_xticklabels(text, fontsize=6, fontweight='bold') fig.subplots_adjust(top=0.92) pylab.savefig(result_path + '/' + parent_filename + ' Interferometric responce ' + source + ' ' + data_type + ' ' + text_freq + ' MHz.png', bbox_inches='tight', dpi=160) plt.close('all') if data_type == 'CIm' and source == 'SygA': ampl_list_SygA_CIm.append(ymax)
def draw_plot(path, closed, city_pos_map, routing_algorithm, cost_function, best_path): blit = False #True# draw_dots = False #True# print_text = False #True#True# fig_m, ax = plt.subplots(1, 1, sharex=True, sharey=True, figsize=(5 * 3, 5 * 3)) plt.rcParams.update({'font.size': 6}) fig_m.tight_layout(rect=[0.025, 0.025, 0.95, 0.95]) # fig_m.subplots_adjust(hspace=.1) ax0 = plt.subplot(111) #, sharex=ax0) min_x, max_x, min_y, max_y = 1000, -1000, 1000, -1000 city = path[-1] ind = len(path) while (city != "-1"): if city in city_pos_map: coord = city_pos_map[city] min_x = min(min_x, coord[0]) max_x = max(max_x, coord[0]) min_y = min(min_y, coord[1]) max_y = max(max_y, coord[1]) if draw_dots: if ind >= 0: ind -= 1 city = path[ind] else: city = "-1" elif not draw_dots: city = closed[city][0] ax0.set_xlim(min_x, max_x) ax0.set_ylim(min_y, max_y) ax0.xaxis.set_major_locator(ticker.LinearLocator(20)) ax0.xaxis.set_minor_locator(ticker.LinearLocator(20)) ax0.xaxis.grid(True, linestyle='--', which='major', color='black', alpha=1.0) ax0.yaxis.grid(True, linestyle='--', which='major', color='black', alpha=1.0) ax0.set_ylabel('longitude') ax0.set_xlabel('latitude') ax0.set_title('Map of cities- Path length: %d' % (closed[path[-1]][1] + 1)) # for key in city_pos_map.keys(): # ax0.text(city_pos_map[key][0], city_pos_map[key][1], key.split(',')[0], ha='center') if blit: fig_m.canvas.draw() # Printing city names from start to end city x, y = 40, -100 for ind, key in enumerate(best_path): offset = int(ind / 200) * 200 C = np.array([0 + ind - offset, 0 + ind - offset, 255]) if key in city_pos_map: x = city_pos_map[key][0] y = city_pos_map[key][1] else: y += 0.1 ax0.text(x, y, key.split(',')[0], ha='center', color=C / 255.0) plt.pause(1e-10) key = path[0] if key in city_pos_map: ax0.text(city_pos_map[key][0], city_pos_map[key][1], key.split(',')[0], ha='center', color='red', weight='bold') else: ax0.text(40, -100, city.split(',')[0], ha='center', color='red', weight='bold') key = path[-1] if key in city_pos_map: ax0.text(city_pos_map[key][0], city_pos_map[key][1], key.split(',')[0], ha='center', color='green', weight='bold') else: ax0.text(40, -100, city.split(',')[0], ha='center', color='green', weight='bold') plt.pause(1e-100) if blit: axbackground = fig_m.canvas.copy_from_bbox(ax0.bbox) if draw_dots: x, y = 40, -100 for ind, key in enumerate(path[1:-1]): offset = int(ind / 200) * 200 C = np.array([0 + ind - offset, 0 + ind - offset, 255]) if key in city_pos_map: x = city_pos_map[key][1] y = city_pos_map[key][0] else: y += 0.1 if print_text: ax0.text(x, y, key.split(',')[0], ha='center', color=C / 255.0) else: ax0.scatter(x, y, c=C / 255.0, marker='o') # if blit: fig_m.canvas.restore_region(axbackground) fig_m.canvas.blit(ax0.bbox) plt.pause(1e-10) plt.savefig("path_from_%s_to_%s_%s_%s" % (path[0], path[-1], routing_algorithm, cost_function)) #, bbox_inches='tight') plt.show() return best_path
def plot_heatmap(data, name, signals=None, ticks="both", minimum="auto", xlabel=None, title=None): if ticks == "both": ticks = "xy" fig, (ax, cbar_ax) = plt.subplots( 2, gridspec_kw=dict( left=0.2, right=0.95, top=0.86, bottom=0.1, hspace=0.05, height_ratios=(0.9, 0.05), ), figsize=(MARGIN_LENGTH, 1.15 * MARGIN_LENGTH), ) if data.max().max() - data.min().min() > 20: norm = colors.SymLogNorm(linthresh=0.001, base=10) locator = ticker.SymmetricalLogLocator(linthresh=0.0011, base=10) locator.set_params(numticks=5) else: norm = colors.Normalize() locator = ticker.LinearLocator(numticks=5) # if minimum == "auto": # _min = data.min().min() # data_min = np.sign(_min) * 10 ** min(10, floor(log10(np.abs(_min)))) # else: # data_min = minimum # data_max = 10 ** max(1, ceil(log10(data.max().max()))) # _ticks = [data_min, 0, data_max] # norm.autoscale(_ticks) sns.heatmap( data, ax=ax, annot=False, linewidths=1, cbar=True, cbar_ax=cbar_ax, cbar_kws={ "orientation": "horizontal", "ticks": locator }, square=True, norm=norm, cmap=CMAP_DIV, ) if xlabel is not None: ax.set_xlabel(xlabel) ax.xaxis.set_label_position('top') if title is not None: ax.set_title(title) ax.tick_params( bottom=False, left=False, labelbottom=False, labeltop="x" not in ticks, labelleft="y" not in ticks, ) plt.setp(ax.get_yticklabels(), rotation=0, ha="right", rotation_mode="default") if signals is not None: N = len(signals) pos_tick = np.linspace(0, 1, 2 * N + 1)[1::2] size = 1 / N * 0.9 if 'vocals' in signals: size *= 1.4 for i in range(N): if "x" in ticks: add_plot_tick(ax, signals[i], pos=pos_tick[i], where="x", size=size) if "y" in ticks: add_plot_tick(ax, signals[i], pos=pos_tick[-i - 1], where="y", size=size) savefig(name + "_hm", eps=True)
def meter_chart(cls, meters, dtime, temper, atmo, delta_atmo, chart_fname_path, ranges=None, alert=None, show=False): meter_id = meters[0] # chart for one meter only is implemented now fig, ax1 = plt.subplots() # fig.suptitle(f'Динаміка температура для {name}') if alert is not None: ax1.set_title(alert) else: ax1.set_title( f'Динаміка показників температури для місця {meter_id}') myFmt = DateFormatter("%m-%d %H:%M:%S") linestyle_temp = 'dotted' linestyle_diff = 'solid' # temperature: color_temp = 'tab:red' temp_plot, = ax1.plot(dtime, temper, color=color_temp, linestyle=linestyle_temp, marker='.', label=f'Температура') ax1.set_xlabel('Час') ax1.xaxis.set_major_formatter(myFmt) # ax1.xaxis.set_major_locator(ticker.LinearLocator(35)) ax1.grid(axis='x') # fig.autofmt_xdate() ax1.xaxis.set_tick_params(labelsize=8, rotation=45) # atmo color = 'tab:green' ax1.set_ylabel(f'Температура(\'C)', color=color) atmo_plot, = ax1.plot(dtime, atmo, color=color, linestyle=linestyle_temp, label=f'Темп.оточення') # ax1.legend(loc='best') # upper left') # atmo diff color = 'tab:blue' ax2 = ax1.twinx() ax2.set_ylabel(f'Різниця(\'C) з оточенням', color=color) ax2.xaxis.set_major_formatter(myFmt) ax2.xaxis.set_major_locator(ticker.LinearLocator(15)) diff_plot, = ax2.plot(dtime, delta_atmo, color=color, linestyle=linestyle_diff, marker='.', label=f'Різниця з оточ.') # ax2.legend(loc='best') # 'upper right') ax2.legend(handles=(temp_plot, atmo_plot, diff_plot), loc='upper left') # set range lines: # if ranges is not None: # temp_yellow, temp_red, atmo_yellow, atmo_red, _, _ = ranges # ax1.axhline(temp_yellow, color='tab:orange', linestyle=linestyle_temp, linewidth=0.5) # ax1.axhline(temp_red, color='tab:red', linestyle=linestyle_temp, linewidth=0.5) # ax2.axhline(atmo_yellow, color='tab:orange', linestyle=linestyle_diff, linewidth=0.5) # ax2.axhline(atmo_red, color='tab:red', linestyle=linestyle_diff, linewidth=0.5) if ranges is not None: temp_yellow, temp_red, atmo_yellow, atmo_red, _, _ = ranges ymin, ymax = ax1.get_ylim() ax1.axhspan(ymin, temp_yellow, color='g', alpha=0.1) # hatch='+', ax1.axhspan(temp_yellow, temp_red, color='y', alpha=0.1) ax1.axhspan(temp_red, ymax, color='r', alpha=0.1) fig.tight_layout() fig.savefig(chart_fname_path) if show: plt.show() plt.close()
def TwoLeverFig(fig, aRecord, levers, max_x_scale, max_y_scale): """ To Do: select X axis limit from radio button. 1L-PR uses L1 ("L") as PR lever 1L-PR uses only one block ("B") 2L-PR uses L2 ("J") as PR lever and L1 ("L") as HD lever 2L_PR uses "B" to signal access to HD Resolutions: aRecord.datalist - mSec 10800000 mSec in 180 minute session cumRecTimes - transforms all times into fractions of a minute so that it can be plotted in minutes binStartTimes - fractions of a minute binStartTimesSec - second testAreaFigureFrame - tk container (a Frame) self.matPlotTestFigure - the thing that axes and lines are drawn on self.threshold_tk_Canvas - drawing space for things like event records self.testArea_matPlot_Canvas - container for the MatPlotLib Figure - This is the thing that gets redrawn after things are changed. """ verbose = True # local - couple to a global variable and checkbox? PR_lever_Char = 'J' if levers == 1: PR_lever_Char = 'L' gs = gridspec.GridSpec(nrows=4, ncols=3) """ For positioning graphs see: https://matplotlib.org/tutorials/intermediate/gridspec.html?highlight=gridspec GridSpec defines how the figures fits into the space. Here we define a 4 row x 3 col space. The top figure uses a 2row and 3 cols and the bottom two graphs use 1 row and 3 columns. uses numpy two dimensional indexing for a 3x3 array >>> x = np.arange(10) >>> x array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> x[0:2] array([0, 1]) >>> x[0:3] array([0, 1, 2]) """ showLabels = False aCumRecGraph = fig.add_subplot(gs[0:2, 0:3], label="1") # row [0,1] and col [0,1,2] aBarGraph = fig.add_subplot(gs[2, 0:3], label="2") # row [2] and col [0,1,2] aCocConcGraph = fig.add_subplot(gs[3, 0:3], label='3') # row [3] and col [0,1,2] # Coc Conc graph in mSec so have to do the X axis labels maunally xLabels = [ '0', '30', '60', '90', '120', '150', '180', '210', '240', '270', '300', '330', '360', '390' ] if (showLabels): aCumRecGraph.set_title(aRecord.fileName) #aCumRecGraph.set_xlabel('Session Time (min)', fontsize = 12) aCumRecGraph.patch.set_facecolor("none") aCumRecGraph.spines['top'].set_color('none') aCumRecGraph.spines['right'].set_color('none') aCumRecGraph.set_ylabel('PR Lever Responses', fontsize=12) #aCumRecGraph.yaxis.labelpad = 15 aCumRecGraph.set_xscale("linear") aCumRecGraph.set_yscale("linear") aCumRecGraph.set_xlim(0, max_x_scale) aCumRecGraph.set_ylim(0, max_y_scale) aCumRecGraph.xaxis.set_major_locator( MultipleLocator(30)) # 30 min intervals aCumRecGraph.spines['left'].set_position(('axes', -0.02)) #aBarGraph.set_xlabel('Session Time (min)', fontsize = 12) aBarGraph.patch.set_facecolor("none") aBarGraph.spines['left'].set_position(('axes', -0.02)) aBarGraph.spines['top'].set_color('none') aBarGraph.spines['right'].set_color('none') aBarGraph.set_ylabel('Dose (mg)', fontsize=12) #aBarGraph.yaxis.labelpad = 15 aBarGraph.set_xscale("linear") aBarGraph.set_yscale("linear") aBarGraph.set_xlim(0, max_x_scale) aBarGraph.set_ylim(0, 1.5) aBarGraph.xaxis.set_major_locator(MultipleLocator(30)) # 30 min intervals #aBarGraph.set_xticklabels(xLabels) # Suppress tick labels aCocConcGraph.patch.set_facecolor("none") aCocConcGraph.spines['left'].set_position(('axes', -0.02)) aCocConcGraph.spines['top'].set_color('none') aCocConcGraph.spines['right'].set_color('none') aCocConcGraph.set_xlabel('Session Time (min)', fontsize=12) #aCocConcGraph.xaxis.labelpad = 20 aCocConcGraph.set_ylabel('Cocaine', fontsize=12) #aCocConcGraph.yaxis.labelpad = 15 aCocConcGraph.set_xscale("linear") aCocConcGraph.set_yscale("linear") aCocConcGraph.set_xlim(0, max_x_scale * 60000) aCocConcGraph.xaxis.set_major_locator( ticker.LinearLocator(int(max_x_scale / 30) + 1)) aCocConcGraph.set_xticklabels(xLabels) aCocConcGraph.set_ylim(0, 25) # make an array of x in fractions of a min. # make an array of y - total responses. pumpOn = False cumRecTimes = [] cumRecResp = [] totalDrugBins = 0 resets = 0 respTotal = 0 binPumpTime = 0 totalDose = 0 binStartTime = 0 binStartTime_mSec = 0 binEndTime_mSec = 0 totalBinTime_mSec = 0 binStartTimes = [] binStartTimesSec = [] tickPositionY = [] doseList = [] pumpTimeList = [] finalRatio = 0 trialResponses = 0 adjustedRespTotal = 0 maxTime = 360 # ************ Cummulative Record ************************* for pairs in aRecord.datalist: if pairs[1] == PR_lever_Char: # 1l = 'L'; 2L = 'J' trialResponses = trialResponses + 1 respTotal = respTotal + 1 adjustedRespTotal = respTotal - (resets * max_y_scale) if adjustedRespTotal == max_y_scale: resets = resets + 1 adjustedRespTotal = 0 x = pairs[0] / 60000 # fraction of a min if x < maxTime: cumRecTimes.append(x) cumRecResp.append(adjustedRespTotal) elif pairs[1] == 'B': # If 2L then "B" controls tick mark if levers == 2: binStartTime_mSec = pairs[0] finalRatio = trialResponses totalDrugBins = totalDrugBins + 1 t = pairs[0] / 1000 # in seconds binStartTimesSec.append(t) t = pairs[0] / 60000 # fraction of a minute binStartTimes.append(t) tickPositionY.append(adjustedRespTotal) elif pairs[1] == 'P': # If 1L then "P" controls tick mark if levers == 1: binStartTime_mSec = pairs[0] finalRatio = trialResponses totalDrugBins = totalDrugBins + 1 t = pairs[0] / 1000 # in seconds binStartTimesSec.append(t) t = pairs[0] / 60000 # fraction of a minute binStartTimes.append(t) tickPositionY.append(adjustedRespTotal) pumpStartTime = pairs[0] pumpOn = True elif pairs[1] == 'p': if pumpOn: pumpDuration = pairs[0] - pumpStartTime binPumpTime = binPumpTime + pumpDuration pumpOn = False if levers == 1: trialResponses = 0 pumpTimeList.append(binPumpTime) binDose = ( binPumpTime / 1000) * 5.0 * 0.025 # pumptime(mSec) * mg/ml * ml/sec) totalDose = totalDose + binDose doseList.append(binDose) #print(binStartTime,binDose) binPumpTime = 0 elif pairs[1] == 'b': # End of Drug Access Period binEndTime_mSec = pairs[0] totalBinTime_mSec = totalBinTime_mSec + (binEndTime_mSec - binStartTime_mSec) trialResponses = 0 pumpTimeList.append(binPumpTime) binDose = (binPumpTime / 1000) * 5.0 * 0.025 # pumptime(mSec) * mg/ml * ml/sec) totalDose = totalDose + binDose doseList.append(binDose) #print(binStartTime,binDose) binPumpTime = 0 aCumRec = Line2D(cumRecTimes, cumRecResp, color='black', ls='solid', drawstyle='steps') aCumRec.set_lw(1.0) # Example of setting and getting linewidth # print("line width =", aCumRec.get_linewidth()) aCumRecGraph.add_line(aCumRec) # ********* Draw Ticks ********************* for i in range(len(binStartTimes)): tickX = max_x_scale * 0.01 # make the tick mark proportional (1%) to the X axis length tickY = max_y_scale * 0.02 # make the tick mark proportional (2%) to the Y axis length tickMarkX = [binStartTimes[i], binStartTimes[i] + tickX] tickMarkY = [tickPositionY[i], tickPositionY[i] - tickY] aTickMark = Line2D(tickMarkX, tickMarkY, color="black") aTickMark.set_lw(1.0) aCumRecGraph.add_line(aTickMark) # *********** Draw Bar chart of doses ************************** """ binStartTimes are fractions of a minute. The problem was that the first bar was too thin because it was too close to the edge. Here, they are rounded up to an integer and shift 1 min which helps. There is still an issue that some of the bars are a slightly different width. Perhaps this has to do with the size of the x scale """ binStartTimesInt = [] for num in binStartTimes: binStartTimesInt.append(round(num) + 1) print("binStartTimes = ", binStartTimes) print("binStartTimesInt = ", binStartTimesInt) print("doseList =", doseList) print("pumpTimeList = ", pumpTimeList) bar_width = 2.5 # The units correspond to X values, so will get skinny with high max_x_scale. aBarGraph.bar(binStartTimesInt, doseList, bar_width, color="black") # *********** Cocaine Concentration curve ********************** resolution = 5 # seconds cocConcXYList = model.calculateCocConc(aRecord.datalist, aRecord.cocConc, aRecord.pumpSpeed, resolution) # cocConcXYList returns a list of [time,conc]. # The following separates these into two equal length lists to be plotted cocConcList = [] timeList = [] for i in range(len(cocConcXYList)): timeList.append( cocConcXYList[i][0]) # essentially a list in 5 sec intervals cocConcList.append(cocConcXYList[i][1]) cocConcLine = Line2D(timeList, cocConcList, color='black', ls='solid') aCocConcGraph.add_line(cocConcLine) # *********** Prediction of dose selected by cocaine levels # i.e. correlate binDose with the cocaine cencentration at time of the dose cocLevels = [] for i in range(len(binStartTimes)): t = int(binStartTimesSec[i] / 5) # Get time corresponding to 5 sec bin in cocConcList cocLevel = cocConcList[t] #if verbose: print(t,cocLevel,doseList[i]) cocLevels.append( cocLevel ) # Create a list of cocaine concentrations corresponding to binDose # ********** Create formated text strings ************************ averageBinLength = (totalBinTime_mSec / totalDrugBins) / 1000 drugAccessLengthStr = "Access Period = {:.0f} sec".format(averageBinLength) totalDrugBinsStr = "Break Point = {}".format(totalDrugBins) finalRatioStr = "Final Ratio = {}".format(finalRatio) totalDoseStr = "Total Dose = {:.3f} mg".format(totalDose) rStr = "" # r = pearsonr(doseList,cocLevels) # print("r =",r) # rStr = "r = {:.3f}".format(r[0]) if verbose: print(drugAccessLengthStr) print(totalDrugBinsStr) print(finalRatioStr) print(totalDoseStr) print(rStr) if (showLabels): self.matPlotTestFigure.text(0.1, 0.96, drugAccessLengthStr) self.matPlotTestFigure.text(0.1, 0.94, totalDrugBinsStr) self.matPlotTestFigure.text(0.1, 0.92, finalRatioStr) self.matPlotTestFigure.text(0.1, 0.90, totalDoseStr) self.matPlotTestFigure.text(0.8, 0.18, rStr)
def update_xlim(self): """Update the xlim of the axes and recalculate the histogram.""" if self._axes is None: return # Clear the axes and redraw everything #self._axes.cla() # Set the x limits and labels. xlabels = self._spike_plot._raster_axes.get_xticklabels() for item in xlabels: item.set_visible(False) xlim = self._spike_plot._raster_axes.get_xlim() # Go through spike_param dict and draw those histograms. for spike_param in self._spike_plot._spike_params.itervalues(): if spike_param.sth_style is not None: if spike_param.sth_redraw: spikes = spiketrain.get_spikes(\ [spike_param.flattened], window=(xlim[0], xlim[1])) if self._bins is None: bins = numpy.arange(xlim[0], xlim[1] + self._dt / 2, self._dt) else: bins = self._bins.copy() (discrete, bin_edges) = numpy.histogram(spikes, bins) self._filtered = hist_filter(numpy.asfarray(discrete), \ spike_param.sth_kernel, spike_param.sth_origin) bins = [] for i in xrange(len(self._filtered)): bins.append((i * spike_param.sth_dt) + xlim[0] + \ (spike_param.sth_dt / 2)) spike_len = len(discrete) rlen = xlim[1] - xlim[0] divisor = (spike_len - \ ((spike_len * spike_param.sth_dt) % \ float(rlen) / spike_param.sth_dt)) * 1.1 if self._style is 'bar': divisor *= 1.15 lwidth = 0.75 if numpy.float32(divisor) > 0.: lwidth = max(self._axes.bbox.width / divisor, lwidth) if self._style is 'bar' or self._style is 'stepfilled': self._drawn_lines[spike_param.label] = \ self._axes.vlines(bins, 0, self._filtered, \ linewidth = lwidth) elif self._style is 'step': x_coords = [] y_coords = [] for i in xrange(len(self._filtered)): xval = (i * spike_param.sth_dt) + xlim[0] if not (i == 0): x_coords.append(xval) x_coords.append(xval) y_coords.append(self._filtered[i]) y_coords.append(self._filtered[i]) xval = (len(self._filtered) * spike_param.sth_dt) + \ xlim[0] + (spike_param.sth_dt / 2) x_coords.append(xval) self._drawn_lines[spike_param.label] = \ self._axes.plot(x_coords, y_coords, \ linewidth=spike_param.sth_linewidth, \ color=spike_param.markercolor) elif self._style is 'lineto': x_coords = [] for i in xrange(len(self._filtered)): xval = (i * spike_param.sth_dt) + xlim[0] x_coords.append(xval) self._drawn_lines[spike_param.label] = \ self._axes.plot(x_coords, self._filtered, \ linewidth=spike_param.sth_linewidth, \ color=spike_param.markercolor) # Turn off the x-axis tick labels, except the first and last one if self._axes is not None: self._axes.tick_params(direction='out', length=4, width=.75, color='black') self._axes.set_xlim(self._spike_plot._raster_axes.get_xlim()) self._axes.yaxis.set_major_locator( ticker.LinearLocator(numticks=3)) self._axes.spines['top'].set_color('none') self._axes.get_yaxis().set_ticks_position('left') self._axes.get_xaxis().set_ticks_position('bottom')
def plot(self, slice_index=None, handle=False, figure=None, ax_xy=None, vmin=None, vmax=None, cmap=None, array=None): """Plot the grid using three orthogonal projections. Requires Matplotlib. """ import matplotlib.pyplot as plt from matplotlib import ticker if array is None: if self.array is None: return else: array = self.array ax_xy, ax_xz, ax_yz, ax_cb = self.get_plot_axes(figure, ax_xy) if figure is None: figure = ax_xy.get_figure() if slice_index is None: slice_index = list( map(int, (self.nx / 2, self.ny / 2, self.nz / 2))) if slice_index == 'max': slice_index = self.get_ijk_max() if slice_index == 'min': slice_index = self.get_ijk_min() if vmin is None: vmin = np.nanmin(array) if vmax is None: vmax = np.nanmax(array) hnd = ax_xy.imshow(np.transpose(array[:, :, slice_index[2]]), vmin=vmin, vmax=vmax, cmap=cmap, origin='lower', extent=self.get_xy_extent(), zorder=-10) ax_xz.imshow(np.transpose(array[:, slice_index[1], :]), vmin=vmin, vmax=vmax, cmap=cmap, origin='lower', extent=self.get_xz_extent(), aspect='auto', zorder=-10) ax_yz.imshow(array[slice_index[0], :, :], vmin=vmin, vmax=vmax, cmap=cmap, origin='lower', extent=self.get_zy_extent(), aspect='auto', zorder=-10) x_slice, y_slice, z_slice = self.get_xyz(*slice_index) ax_xy.axhline(y_slice, color='w', linestyle='dashed', zorder=-1) ax_xy.axvline(x_slice, color='w', linestyle='dashed', zorder=-1) ax_xz.axhline(z_slice, color='w', linestyle='dashed', zorder=-1) ax_yz.axvline(z_slice, color='w', linestyle='dashed', zorder=-1) fmt = '%.1e' if np.nanmax(array) <= 0.01 else '%.2f' cb = figure.colorbar(hnd, cax=ax_cb, orientation='horizontal', format=fmt) cb.locator = ticker.LinearLocator(numticks=3) cb.update_ticks() if handle: return (ax_xy, ax_xz, ax_yz), cb else: plt.show()
def plot_trace(axis, data, imagej=False, fps=None, x_span=0, x_end=None, frac=True, norm=False, invert=False, filter_lp=False, color='b', x_ticks=True): data_x, data_y = 0, 0 if imagej: if not x_end: x_end = len(data) # Includes X,Y header row (nan,nan) x_start = x_end - x_span # data_x = data[x_start:x_end, 0] # All rows of the first column (skip X,Y header row) data_x = data[1:x_span + 1, 0] # All rows of the first column (skip X,Y header row) if fps: # convert to ms data_x = ((data_x - 1) / fps) * 1000 # ensure range is 0 - max # data_x = data_x.astype(int) # axis.xaxis.set_major_locator(ticker.IndexLocator(base=1000, offset=500)) # axis.xaxis.set_major_locator(ticker.AutoLocator()) # axis.xaxis.set_minor_locator(ticker.AutoMinorLocator()) data_y_counts = data[x_start:x_end, 1].astype( int) # rows of the first column (skip X,Y header row) counts_min = data_y_counts.min() # data_y_counts_delta = data_y.max() - data_y_.min() # MAX_COUNTS_16BIT if frac: # # convert y-axis from counts to percentage range of max counts # data_y = data_y_counts / MAX_COUNTS_16BIT * 100 # axis.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f')) # Convert y-axis from counts to dF / F: (F_t - F0) / F0 axis.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f')) # Get max and min # data_min, data_max = np.nanmin(data_y_counts), np.nanmax(data_y_counts) f_0 = counts_min f_t = data_y_counts data_y = (f_t - f_0) / f_0 else: # Shift y-axis counts to start at zero data_y = data_y_counts - counts_min if filter_lp: print('* Filtering data: Low Pass') dt = 1 / 408 freq = 75 fs = 1 / dt wn = (freq / (fs / 2)) [b, a] = sig.butter(5, wn) data_y = sig.filtfilt(b, a, data_y) print('* Data Filtered') if norm: # Normalize each trace # Get max and min data_min, data_max = np.nanmin(data_y), np.nanmax(data_y) data_y = np.interp(data_y, (data_min, data_max), (0, 1)) if invert: data_y = 1 - data_y # Invert a normalized signal else: if invert: print('!***! Can\'t invert a non-normalized trace!') axis.tick_params(labelsize=fontsize4) if x_ticks: axis.xaxis.set_major_locator(ticker.MultipleLocator(1000)) axis.xaxis.set_minor_locator(ticker.MultipleLocator(int(1000 / 4))) else: axis.set_xticks([]) axis.set_xticklabels([]) ylim = [data_y.min(), data_y.max()] axis.set_ylim(ylim) # axis.set_ylim([0, 1.1]) axis.yaxis.set_major_locator(ticker.LinearLocator(2)) axis.yaxis.set_minor_locator(ticker.LinearLocator(5)) # axis.yaxis.set_major_locator(ticker.AutoLocator()) # axis.yaxis.set_minor_locator(ticker.AutoMinorLocator()) axis.spines['right'].set_visible(False) axis.spines['left'].set_visible(False) axis.spines['top'].set_visible(False) axis.spines['bottom'].set_visible(False) axis.plot(data_x, data_y, color, linewidth=0.2) else: # axis.plot(data, color=color, linewidth=0.5) print('***! Not imagej traces') return data_x, data_y
hes_other_d[counter].append(str(df1.loc[i][2])) elif str(df1.loc[i][1]) == "trust_doctors": trust_doctors_r[counter].append(df1.loc[i][0]) trust_doctors_d[counter].append(str(df1.loc[i][2])) counter += 1 fig, axes = plt.subplots(3, 3, gridspec_kw={'hspace': 1, 'wspace': 0.4}) fig.suptitle("A Comparison between " + sys.argv[1] + " and " + sys.argv[2]) line_labels = [sys.argv[1], sys.argv[2]] (ax1, ax2, ax3), (ax4, ax5, ax6), (ax7, ax8, ax9) = axes fmt = mdates.DateFormatter("%m-%b") loc = ticker.LinearLocator(9) #1 covid ax1.xaxis.set_major_formatter(fmt) ax1.xaxis.set_major_locator(loc) for entry in ax1.xaxis.get_ticklabels(): entry.set_rotation(45) d11 = [dt.datetime.strptime(d, "%Y%m%d").date() for d in covid_d[0]] d12 = [dt.datetime.strptime(d, "%Y%m%d").date() for d in covid_d[1]] l1 = ax1.plot(d11, covid_r[0], color="orange", label=sys.argv[0]) l2 = ax1.plot(d12, covid_r[1], color="blue", label=sys.argv[1]) ax1.set_title("Covid Like Illnesses") #2 flu ax2.xaxis.set_major_formatter(fmt) ax2.xaxis.set_major_locator(loc)
for filename in files: file = Tcxer(filename, 'time', 'watts') file.makeSoup() #parses xml file.findAll() #creates a couple of lists that can be accessed by _val file.movingAverage(21, 2) #creates a list that can be accessed by _movAv data.append(file._valx) data.append(file._valy) data.append(file._movAv) ax1.plot(file._valx, file._valy, label=filename) ax2.plot(file._valx[len(file._valx) - len(file._movAv):], file._movAv, label=filename + ' 21 sec MA poly 2') # datanp = np.array(data) #creates an array of lists (lists not guaranteed to have the same dimension) # ax1.plot(file1._valx, file1._valy, label='4iii') # ax1.plot(file2._valx, file2._valy, label='trainer') # ax2.plot(file1._valx[len(file1._valx)-len(file1._movAv):], file1._movAv, label='4iii 21 sec MA poly 2') # ax2.plot(file2._valx[len(file2._valx)-len(file2._movAv):], file2._movAv, label='trainer 21 sec MA poly 2') # plt.yticks(np.arange(min( file1._valy), max( file1._valy)+1, 10.0)) # plt.yticks(np.arange(min( file2._valy), max( file2._valy)+1, 10.0)) ax1.xaxis.set_major_locator(ticker.LinearLocator(5)) ax2.xaxis.set_major_locator(ticker.LinearLocator(5)) ax1.set_ylim(bottom=0) ax2.set_ylim(bottom=0) ax1.set_xlim(left=0) ax2.set_xlim(left=0) ax1.legend() ax2.legend() plt.show()
import matplotlib.dates as mdates import matplotlib.ticker as ticker # fig, ax1 = plt.subplots(sharey=True) fig, ax1 = plt.subplots() #Set tick labels and rotate by 45 degrees for readability years = mdates.YearLocator() # every year month = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%Y') ax1.xaxis.set_major_locator(years) ax1.xaxis.set_major_formatter(yearsFmt) ax1.xaxis.set_minor_locator(month) ax1.yaxis.set_major_locator(ticker.LinearLocator()) fig.autofmt_xdate() # ax1.plot(months, ios, 'r-', months, android, 'b-') #Create legend line_up, = plt.plot(months, ios, label='iOS') line_down, = plt.plot(months, android, label='Android') plt.legend([line_up, line_down], ['iOS', 'Android']) #Label Axes plt.ylabel('Market Share') plt.xlabel('Year') #Show plot
def init_sp_fit(self, title='', xlabel='', ylabel='', xlim=None, ylim=None, xscale='linear', yscale='linear', *args, **kwargs): ''' initialize the spectra fit initialize .lG, .lB, .lGfit, .lBfit .lf, .lg plot ''' self.initax_xyy() self.l['lG'] = self.ax[0].plot( [], [], marker='.', linestyle='none', markerfacecolor='none', color=color[0] ) # G self.l['lB'] = self.ax[1].plot( [], [], marker='.', linestyle='none', markerfacecolor='none', color=color[1] ) # B # self.l['lGpre'] = self.ax[0].plot( # [], [], # marker='.', # linestyle='none', # markerfacecolor='none', # color='gray' # ) # previous G # self.l['lBpre'] = self.ax[1].plot( # [], [], # marker='.', # linestyle='none', # markerfacecolor='none', # color='gray' # ) # previous B self.l['lGfit'] = self.ax[0].plot( [], [], color='k' ) # G fit self.l['lBfit'] = self.ax[1].plot( [], [], color='k' ) # B fit self.l['strk'] = self.ax[0].plot( [], [], marker='+', linestyle='none', color='r' ) # center of tracking peak self.l['srec'] = self.ax[0].plot( [], [], marker='x', linestyle='none', color='g' ) # center of recording peak self.l['lsp'] = self.ax[0].plot( [], [], color=color[2] ) # peak freq span # set label of ax[1] self.set_ax(self.ax[0], xlabel=r'$f$ (Hz)',ylabel=r'$G_P$ (mS)') self.set_ax(self.ax[1], xlabel=r'$f$ (Hz)',ylabel=r'$B_P$ (mS)') self.ax[0].xaxis.set_major_locator(ticker.LinearLocator(3)) # self.ax[0].xaxis.set_major_locator(plt.AutoLocator()) # self.ax[0].xaxis.set_major_locator(plt.LinearLocator()) # self.ax[0].xaxis.set_major_locator(plt.MaxNLocator(3)) self.ax[0].margins(x=0) self.ax[1].margins(x=0) self.ax[0].margins(y=.05) self.ax[1].margins(y=.05) # self.ax[1].sharex = self.ax[0] # self.ax[0].autoscale() # self.ax[1].autoscale() # add span selector self.span_selector_zoomin = SpanSelector( self.ax[0], self.sp_spanselect_zoomin_callback, direction='horizontal', useblit=True, button=[1], # left click minspan=5, span_stays=False, rectprops=dict(facecolor='red', alpha=0.2) ) self.span_selector_zoomout = SpanSelector( self.ax[0], self.sp_spanselect_zoomout_callback, direction='horizontal', useblit=True, button=[3], # right minspan=5, span_stays=False, rectprops=dict(facecolor='blue', alpha=0.2) )
linewidth=args.w, alpha=1.0) ax.yaxis.set_major_formatter( tk.FuncFormatter(lambda v, pos: "{:4.2f}".format(v * bin_width) + ' | ' + "{:4.2f}".format(v))) if args.a > 0: minorLocator = tk.AutoMinorLocator(args.a) ax.xaxis.set_minor_locator(minorLocator) if args.m > 0 and args.l <= 0: majorLocator = tk.MultipleLocator(args.m) ax.xaxis.set_major_locator(majorLocator) if args.l > 0: majorLocator = tk.LinearLocator(numticks=args.l) ax.xaxis.set_major_locator(majorLocator) axlim[3] = np.max(n) * 1.15 if axlim[2] == axlim[3]: axlim[2] -= 1 axlim[3] += 1 plt.axis(axlim) graph_legend = plt.legend(fancybox=True) graph_legend.get_frame().set_alpha(0.75) plt.draw() print output_str ##########################################################################
def plot_mean_frequency_error_ratio(show_plot, in_csv_file_list, out_plot_file_list, label_list): ### general plot configurations ### plt.rcParams['figure.figsize'] = 6.5, 5.5 # it was 12, 5.5 plt.rcParams["font.family"] = "Arial" plt.rcParams['font.size'] = 16 # plt.rcParams['legend.fontsize'] = 13 # plt.rcParams['axes.titlesize'] = 15 # plt.rcParams['ytick.labelsize'] = 16 # plt.rcParams['xtick.labelsize'] = 16 plt.rcParams['hatch.linewidth'] = 0.15 plt.rcParams['hatch.color'] = 'Black' # plt.title('Interesting Graph\nCheck it out') plt.rcParams['axes.axisbelow'] = True # fig, ax = plt.subplots() AX = gridspec.GridSpec(8, 1) AX.update(wspace=0.3, hspace=0.15) ax_top = plt.subplot(AX[1, 0]) ax = plt.subplot(AX[2:, 0]) # bar_width = 0.15 if len(in_csv_file_list)>4 else 0.2 bar_width = 0.6 / len(in_csv_file_list) x_ticks = [i for i in range(0, 10)] x_ticks_shifted = [ i - len(in_csv_file_list) * 0.5 * bar_width - bar_width * 0.5 for i in range(0, 10) ] y_list = [] y_mean_list = [] y_error_list = [] x_mean = [] for in_csv_idx in range(len(in_csv_file_list)): style_idx = in_csv_idx + 2 mean_precision_list = get_utilization_mean_precision_list( in_csv_file_list[in_csv_idx]) # ax.errorbar(x, y, y_stdev, marker='o', color='b', alpha=1, linestyle='-', label="ScheduLeak-FP", linewidth=1) # ax.plot(mean_precision_list.keys(), mean_precision_list.values(), marker='s', color='k', alpha=1, linestyle='-', label="$ScheduLeak$ (FP)", linewidth=1) #x_ticks = [float(i)-0.33 for i in range(0, 10)] ax.bar([i + bar_width * (in_csv_idx + 1) for i in x_ticks_shifted], mean_precision_list.values(), bar_width, color=PlotUtility.palletForManyDimCustom[style_idx], edgecolor='k', hatch=PlotUtility.hatch_list[style_idx], alpha=1, linestyle='-', label=label_list[in_csv_idx], linewidth=1) data_dict = np.genfromtxt(in_csv_file_list[in_csv_idx], delimiter=',', unpack=True, names=True) x = data_dict['Utilization'] this_y = data_dict['Mean_Mean_Task_Frequency_Error'] x_mean = [] y_mean = [] y_error = [] for u in range(10): util = u / 10 matched_values = np.array([]) for i in range(len(this_y)): if x[i] >= util and x[i] < (util + 0.1): matched_values = np.append(matched_values, this_y[i]) x_mean.append(u / 10 + 0.05) y_mean.append(matched_values.mean()) y_error.append(matched_values.std()) ax.errorbar( [i + bar_width * (in_csv_idx + 1) for i in x_ticks_shifted], y_mean, y_error, color="black", marker=PlotUtility.pattern_list[style_idx], linewidth=1, ls='none') y_mean_list.append(y_mean) y_error_list.append(y_error) ''' Deadline Miss Ratio (only for the last CSV) ''' data_dict = np.genfromtxt(in_csv_file_list[-1], delimiter=',', unpack=True, names=True) x_deadline_miss_ratio = data_dict['Utilization'] y_deadline_miss_ratio = data_dict['Deadline_Miss_Ratio'] tasksets_with_deadline_misses_count = [] for i in range(10): tasksets_with_deadline_misses_count.append(0) for j in range(len(x_deadline_miss_ratio)): if i / 10 <= x_deadline_miss_ratio[j] < (i + 1) / 10: if y_deadline_miss_ratio[j] > 0.0: tasksets_with_deadline_misses_count[i] += 1 # print(tasksets_with_deadline_misses_count[-1]) ax_top.set_xlim(-0.5, 9.5) # ax_top_ytop = math.ceil(max(y_deadline_miss_ratio)/0.1)*0.1 ax_top_ytop = math.ceil(max(tasksets_with_deadline_misses_count) / 50) * 50 # # ax_top.set_ylim(0, max(y_deadline_miss_ratio)) ax_top.set_ylim(0, ax_top_ytop) # ax_top.get_yaxis().set_major_locator(ticker.LinearLocator(numticks=(ax_top_ytop/0.1)+1)) ax_top.get_yaxis().set_major_locator( ticker.LinearLocator(numticks=(ax_top_ytop / 50) + 1)) ax_top.yaxis.tick_right() ax_top.tick_params(top=False, bottom=False, left=False, right=True, labelleft=False, labelbottom=False, labeltop=False, labelright=False, direction='in') ax_top.spines["left"].set_visible(False) ax_top.spines["top"].set_visible(False) # ax_top.scatter(x_deadline_miss_ratio, y_deadline_miss_ratio, marker='o', facecolors='grey', color='grey', alpha=0.5, s=[5 for i in range(len(y_deadline_miss_ratio))],) # ax_top.bar(range(10), tasksets_with_deadline_misses_count) ax_top.plot(range(10), tasksets_with_deadline_misses_count, marker='.', markersize=10, color='black') ax_top.text( 0, 1.1, "The Number of Task Sets that Have\nDeadline Misses in {}".format( label_list[-1]), transform=ax_top.transAxes, fontsize=14, verticalalignment='top', horizontalalignment='left') for i in range(10): if tasksets_with_deadline_misses_count[i] > 0: ax_top.text(i, tasksets_with_deadline_misses_count[i] + 10, '$\\frac{' + str(tasksets_with_deadline_misses_count[i]) + '}{600}$', fontsize=12, ha='center', va='bottom') ### post plot configurations ### plt.xlabel('Task Set Utilization') plt.ylabel('Mean Frequency Error Ratio') # plt.legend(loc='upper center', shadow=True, edgecolor='k', ncol=3) plt.legend(bbox_to_anchor=(0.5, 1.4), loc="upper center", shadow=True, edgecolor='k', ncol=2) #legend = plt.legend(shadow=True, loc='top') #legend.get_frame().set_edgecolor('k') # plt.xlim(0, 5) plt.xticks(x_ticks) ax.set_xticklabels([ '[0.0,0.1]', '[0.1,0.2]', '[0.2,0.3]', '[0.3,0.4]', '[0.4,0.5]', '[0.5,0.6]', '[0.6,0.7]', '[0.7,0.8]', '[0.8,0.9]', '[0.9,1.0]' ], rotation=0) ax.xaxis.set_tick_params(rotation=45) plt.ylim(0, 1.0) # plt.grid(True, 'major', 'both', color='0.8', linestyle='--', linewidth=1) plt.grid(True, 'major', 'y', color='0.8', linestyle='--', linewidth=1) minor_ticks = [tmp / 10 for tmp in range(0, 11)] ax.set_yticks(minor_ticks, minor=True) plt.grid(True, 'minor', 'y', color='0.8', linestyle='--', linewidth=1) ''' Save the plot to files with the specified format ''' for outFileName in out_plot_file_list: print("Exporting the plot ...") # if outFileName == "png" or outFileName == "pdf": # outFileName = "{}.{}".format(inFileName.split('.')[0], outFileName) outputFormat = outFileName.split('.')[-1] if outputFormat == "pdf" or outputFormat == "png" or True: print('Saving the plot to "{}" ...'.format(outFileName), end=" ") plt.savefig(outFileName, pad_inches=0.02, bbox_inches='tight') print("Done") if show_plot: plt.show()
plt.title(title, fontsize=16) plt.xlabel(xlabel) # Making the twin axes ax2=ax.twinx() # Switching axes so that percentage is on the left and frequency on the right ax2.yaxis.tick_left() ax.yaxis.tick_right() # We also need to switch the labels ax.yaxis.set_label_position('right') ax2.yaxis.set_label_position('left') # Labelling our axes ax2.set_ylabel('Percentage') ax.set_ylabel('Frequency Count') for p in ax.patches: x=p.get_bbox().get_points()[:,0] y=p.get_bbox().get_points()[1,1] # Setting text alignment ax.annotate('{:.1f}%'.format(100.*y/ncount), (x.mean(), y), ha='center', va='bottom') # Use a LinearLocator to ensure the correct number of ticks ax.yaxis.set_major_locator(ticker.LinearLocator(11)) # Setting the y-axis ticks ax2.yaxis.set_ticks(np.arange(0, 101, 10)) ax2.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.0f%%')) # Setting the axes range ax2.set_ylim(0, 100) ax.set_ylim(0, ncount) # Use a MultipleLocator to ensure a tick spacing of 10 ax2.yaxis.set_major_locator(ticker.MultipleLocator(10)) # Grid lines ax2.grid(None)
def paint_posteriors(self): """Create posterior plots.""" print('\n\t\tPAINTING POSTERIORS.') for t in tqdm(range(self.ntemps), desc='Brush temperature'): chain = self.chains[t] post = self.posteriors[t] leftovers = len(chain) % self.nwalkers if leftovers == 0: pass else: chain = chain[:-leftovers] post = post[:-(len(post) % self.nwalkers)] quasisteps = len(chain) // self.nwalkers color = sp.arange(quasisteps) colors = sp.array([color for i in range(self.nwalkers)]).reshape(-1) # Auxiliary variables to coordinate labels and filenames. tcount = 0 pcount = 1 acc = True ins = 0 ins_count = 1 for i in tqdm(range(self.ndim), desc='Brush type'): fig, ax = plt.subplots(figsize=self.post_figsize) im = ax.scatter(chain[:, i], post, s=self.post_size, c=colors, lw=0, cmap=self.post_cmap, alpha=self.post_alpha) ax.axvline(chain[sp.argmax(post), i], color=self.post_v_color, linestyle=self.post_v_linestyle, alpha=self.post_v_alpha, zorder=10) ax.tick_params(axis='both', which='major', labelsize=self.tick_labelsize) ax.tick_params(axis='x', rotation=45) ax.set_ylabel('Posterior', fontsize=self.label_fontsize) cb = plt.colorbar(im, ax=ax) cb.set_label('Step Number', fontsize=self.label_fontsize, rotation=270, labelpad=self.cbar_labelpad) cb.ax.tick_params(labelsize=self.tick_labelsize) xaxis = ax.get_xaxis() xaxis.set_major_locator( ticker.LinearLocator(numticks=self.post_ticknum)) yaxis = ax.get_yaxis() yaxis.set_major_locator( ticker.LinearLocator(numticks=self.post_ticknum)) # plot only accel and instrumental chains. if not self.kplanets: if i == 0: title = self.chain_titles[5] ax.set_xlabel(title + self.chain_units[-1], fontsize=self.label_fontsize) counter = 0 else: title = self.chain_titles[6 + counter % 2] ax.set_xlabel(title + self.chain_units[1], fontsize=self.label_fontsize) counter += 1 else: if pcount <= self.kplanets: title = self.chain_titles[tcount % 5] ax.set_xlabel(title + self.chain_units[tcount % 5], fontsize=self.label_fontsize) tcount += 1 else: if acc: title = self.chain_titles[5] ax.set_xlabel(title + self.chain_units[-1], fontsize=self.label_fontsize) acc = False counter = 0 else: title = self.chain_titles[6 + counter % 2] ax.set_xlabel(title + self.chain_units[1], fontsize=self.label_fontsize) counter += 1 if pcount <= self.kplanets: if self.pdf: plt.savefig(self.working_dir + 'posteriors/' + title + '_K' + str(pcount) + '_T' + str(t) + '.pdf') if self.png: plt.savefig(self.working_dir + 'posteriors/' + title + '_K' + str(pcount) + '_T' + str(t) + '.png') else: if self.pdf: plt.savefig(self.working_dir + 'posteriors/' + title + '_INS' + str(ins) + '_T' + str(t) + '.pdf') if self.png: plt.savefig(self.working_dir + 'posteriors/' + title + '_INS' + str(ins) + '_T' + str(t) + '.png') ins_count += 1 ins += 1 if ins_count % 2 == 0 else 0 pcount += 1 if tcount % 5 == 0 else 0 plt.close('all')
def fig1_2L_PR(aFigure, aRecordList): """ This function was written in a separate branch to draw a figure the 2L-PR-HD paper "Load 2L-PR Files loads four specific files. This function uses the first three files and assumes that File 1: 8_H383_Mar_10.str - 1L-FR - 20 injection max File 2: 8_H383_Mar_10.str - 1L-HD - 3h session File 3: 8_H383_Mar_10.str - 2L-FR-HD 4h session A radio button (showOn_tkCanvas) controls whether the figure is drawn to a canvas or to a separate window that can be saved as a prn file. """ gs = gridspec.GridSpec(nrows=30, ncols=1) max_x_scale = 360 xLabels = [ '0', '30', '60', '90', '120', '150', '180', '210', '240', '270', '300', '330', '360', '390' ] # Spacing of each subplot eventRecord0 = aFigure.add_subplot(gs[0, 0], label="1") # row [0] and col [0]] cocGraph0 = aFigure.add_subplot(gs[2:8, 0], label='2') # rows 2 - 7, col 0 eventRecord1 = aFigure.add_subplot(gs[10, 0], label="3") # row [10] and col [0]] cocGraph1 = aFigure.add_subplot(gs[12:18, 0], label='4') # rows 2 - 7, col 0 eventRecord2 = aFigure.add_subplot(gs[20, 0], label="5") # row [10] and col [0]] accessLine = aFigure.add_subplot(gs[21, 0], label="5") # row [11] and col [0]] eventRecordL2 = aFigure.add_subplot(gs[22, 0], label="5") # row [12] and col [0]] cocGraph2 = aFigure.add_subplot(gs[24:30, 0], label='6') # rows 2 - 7, col 0 # *** Top *** injNum = 0 injTimeList = [] record0 = aRecordList[0] for pairs in record0.datalist: if pairs[1] == 'P': injNum = injNum + 1 injTimeList.append(pairs[0] / 60000) # Min eventRecord0.axes.get_yaxis().set_visible(False) eventRecord0.axes.get_xaxis().set_ticklabels([]) # suppress tick labels eventRecord0.axes.get_yaxis().set_ticklabels([]) eventRecord0.text(-0.05, 0.0, 'FR1', ha='center', transform=eventRecord0.transAxes, color='black') eventRecord0.set_xlim(0, max_x_scale) eventRecord0.xaxis.set_major_locator(MaxNLocator(7)) # six major intervals eventRecord0.xaxis.set_minor_locator( AutoMinorLocator(4)) # 5 ticks per interval eventRecord0.spines['left'].set_color('none') eventRecord0.spines['left'].set_position(('axes', -0.02)) eventRecord0.spines['top'].set_color('none') eventRecord0.spines['right'].set_color('none') eventRecord0.set_ylim(0.01, 1) eventRecord0.eventplot(injTimeList, lineoffsets=0, linelengths=1.5, colors="black") # *********** Cocaine Concentration curve ********************** cocGraph0.patch.set_facecolor("none") cocGraph0.spines['left'].set_position(('axes', -0.02)) cocGraph0.spines['top'].set_color('none') cocGraph0.spines['right'].set_color('none') #cocGraph0.set_xlabel('Session Time (min)', fontsize = 12) #cocGraph0.xaxis.labelpad = 20 cocGraph0.set_ylabel('Cocaine', fontsize=12) #cocGraph0.yaxis.labelpad = 15 cocGraph0.set_xscale("linear") cocGraph0.set_yscale("linear") cocGraph0.set_xlim(0, max_x_scale * 60000) cocGraph0.xaxis.set_major_locator( ticker.LinearLocator(int(max_x_scale / 30) + 1)) cocGraph0.yaxis.set_major_locator(MaxNLocator(6)) # five major intervals cocGraph0.yaxis.set_minor_locator( AutoMinorLocator(4)) # 5 ticks per interval cocGraph0.set_xticklabels(xLabels) cocGraph0.set_ylim(0, 25) resolution = 5 # seconds cocConcXYList = model.calculateCocConc(record0.datalist, record0.cocConc, record0.pumpSpeed, resolution) # cocConcXYList returns a list of [time,conc]. # The following separates these into two equal length lists to be plotted cocConcList = [] timeList = [] for i in range(len(cocConcXYList)): timeList.append( cocConcXYList[i][0]) # essentially a list in 5 sec intervals cocConcList.append(cocConcXYList[i][1]) cocConcLine = Line2D(timeList, cocConcList, color='black', ls='solid') cocGraph0.text(0.85, 0.5, '1L-FR1 (20 inj max)', ha='center', transform=cocGraph0.transAxes, fontsize=14) cocGraph0.add_line(cocConcLine) # *** Middle *** injNum = 0 injTimeList = [] record1 = aRecordList[1] for pairs in record1.datalist: if pairs[1] == 'P': injNum = injNum + 1 injTimeList.append(pairs[0] / 60000) # Min eventRecord1.axes.get_yaxis().set_visible(False) eventRecord1.axes.get_xaxis().set_ticklabels([]) # suppress tick labels eventRecord1.axes.get_yaxis().set_ticklabels([]) eventRecord1.text(-0.05, 0.0, 'HD', ha='center', transform=eventRecord1.transAxes, color='black') eventRecord1.set_xlim(0, max_x_scale) eventRecord1.xaxis.set_major_locator(MaxNLocator(7)) # six major intervals eventRecord1.xaxis.set_minor_locator( AutoMinorLocator(4)) # 5 ticks per interval eventRecord1.spines['left'].set_color('none') eventRecord1.spines['left'].set_position(('axes', -0.02)) eventRecord1.spines['top'].set_color('none') eventRecord1.spines['right'].set_color('none') eventRecord1.set_ylim(0.01, 1) eventRecord1.eventplot(injTimeList, lineoffsets=0, linelengths=1.5, colors="black") # *********** Cocaine Concentration curve ********************** cocGraph1.patch.set_facecolor("none") cocGraph1.spines['left'].set_position(('axes', -0.02)) cocGraph1.spines['top'].set_color('none') cocGraph1.spines['right'].set_color('none') #cocGraph1.set_xlabel('Session Time (min)', fontsize = 12) #cocGraph1.xaxis.labelpad = 20 cocGraph1.set_ylabel('Cocaine', fontsize=12) #cocGraph1.yaxis.labelpad = 15 cocGraph1.set_xscale("linear") cocGraph1.set_yscale("linear") cocGraph1.set_xlim(0, max_x_scale * 60000) cocGraph1.xaxis.set_major_locator( ticker.LinearLocator(int(max_x_scale / 30) + 1)) cocGraph1.yaxis.set_major_locator(MaxNLocator(6)) # five major intervals cocGraph1.yaxis.set_minor_locator( AutoMinorLocator(4)) # 5 ticks per interval cocGraph1.set_xticklabels(xLabels) cocGraph1.set_ylim(0, 25) resolution = 5 # seconds cocConcXYList = model.calculateCocConc(record1.datalist, record1.cocConc, record1.pumpSpeed, resolution) # cocConcXYList returns a list of [time,conc]. # The following separates these into two equal length lists to be plotted cocConcList = [] timeList = [] for i in range(len(cocConcXYList)): timeList.append( cocConcXYList[i][0]) # essentially a list in 5 sec intervals cocConcList.append(cocConcXYList[i][1]) cocConcLine = Line2D(timeList, cocConcList, color='black', ls='solid') cocGraph1.text(0.85, 0.5, '1L-HD (3h)', ha='center', transform=cocGraph1.transAxes, fontsize=14) cocGraph1.add_line(cocConcLine) # *** Bottom *** injNum = 0 injTimeList = [] record2 = aRecordList[2] for pairs in record2.datalist: if pairs[1] == 'J': injNum = injNum + 1 injTimeList.append(pairs[0] / 60000) # Min eventRecord2.axes.get_yaxis().set_visible(False) eventRecord2.axes.get_xaxis().set_ticklabels([]) # suppress tick labels eventRecord2.axes.get_yaxis().set_ticklabels([]) eventRecord2.text(-0.05, 0.0, 'FR1', ha='center', transform=eventRecord2.transAxes, color='black') eventRecord2.set_xlim(0, max_x_scale) eventRecord2.xaxis.set_major_locator(MaxNLocator(7)) # six major intervals eventRecord2.xaxis.set_minor_locator( AutoMinorLocator(4)) # 5 ticks per interval eventRecord2.spines['left'].set_color('none') eventRecord2.spines['left'].set_position(('axes', -0.02)) eventRecord2.spines['top'].set_color('none') eventRecord2.spines['right'].set_color('none') eventRecord2.set_ylim(0.01, 1) eventRecord2.eventplot(injTimeList, lineoffsets=0, linelengths=1.5, colors="black") # Access ["=","."], "Lever 1") # ["-",","], "Lever 2") accessList = [0] timeList = [0] access = False record2 = aRecordList[2] for pairs in record2.datalist: if pairs[1] == ',': #draw horizontal line to timestamp then draw vertical line up timeList.append(pairs[0] / 60000) # Min accessList.append(access) access = True timeList.append(pairs[0] / 60000) # Min accessList.append(access) elif pairs[1] == '-': #draw horizontal line to timestamp then draw vertical line down timeList.append(pairs[0] / 60000) # Min accessList.append(access) access = False timeList.append(pairs[0] / 60000) # Min accessList.append(access) elif pairs[1] == 'E': # End of session timeList.append(pairs[0] / 60000) # Min accessList.append(access) access = False timeList.append(pairs[0] / 60000) # Min accessList.append(access) accessLine.axes.get_yaxis().set_visible(False) accessLine.axes.get_xaxis().set_ticklabels([]) # suppress tick labels accessLine.axes.get_yaxis().set_ticklabels([]) accessLine.text(-0.05, 0.0, 'Access', ha='center', transform=accessLine.transAxes, color='black') accessLine.set_xlim(0, max_x_scale) accessLine.xaxis.set_major_locator(MaxNLocator(7)) # six major intervals accessLine.xaxis.set_minor_locator( AutoMinorLocator(4)) # 5 ticks per interval accessLine.spines['left'].set_color('none') accessLine.spines['left'].set_position(('axes', -0.02)) accessLine.spines['top'].set_color('none') accessLine.spines['right'].set_color('none') accessLine.set_ylim(0, 1) accessLine.set_xlim(0, 360) accessL1 = Line2D(timeList, accessList, color='black', ls='solid') accessLine.add_line(accessL1) injNum = 0 injTimeList = [] record2 = aRecordList[2] for pairs in record2.datalist: if pairs[1] == 'P': injNum = injNum + 1 injTimeList.append(pairs[0] / 60000) # Min eventRecordL2.axes.get_yaxis().set_visible(False) eventRecordL2.axes.get_xaxis().set_ticklabels([]) # suppress tick labels eventRecordL2.axes.get_yaxis().set_ticklabels([]) eventRecordL2.text(-0.05, 0.0, 'HD', ha='center', transform=eventRecordL2.transAxes, color='black') eventRecordL2.set_xlim(0, max_x_scale) eventRecordL2.xaxis.set_major_locator( MaxNLocator(7)) # six major intervals eventRecordL2.xaxis.set_minor_locator( AutoMinorLocator(4)) # 5 ticks per interval eventRecordL2.spines['left'].set_color('none') eventRecordL2.spines['left'].set_position(('axes', -0.02)) eventRecordL2.spines['top'].set_color('none') eventRecordL2.spines['right'].set_color('none') eventRecordL2.set_ylim(0.01, 1) eventRecordL2.eventplot(injTimeList, lineoffsets=0, linelengths=1.5, colors="black") # *********** Cocaine Concentration curve ********************** cocGraph2.patch.set_facecolor("none") cocGraph2.spines['left'].set_position(('axes', -0.02)) cocGraph2.spines['top'].set_color('none') cocGraph2.spines['right'].set_color('none') cocGraph2.set_xlabel('Session Time (min)', fontsize=12) #cocGraph2.xaxis.labelpad = 20 cocGraph2.set_ylabel('Cocaine', fontsize=12) #cocGraph2.yaxis.labelpad = 15 cocGraph2.set_xscale("linear") cocGraph2.set_yscale("linear") cocGraph2.set_xlim(0, max_x_scale * 60000) cocGraph2.xaxis.set_major_locator( ticker.LinearLocator(int(max_x_scale / 30) + 1)) cocGraph2.yaxis.set_major_locator(MaxNLocator(6)) # five major intervals cocGraph2.yaxis.set_minor_locator( AutoMinorLocator(4)) # 5 ticks per interval cocGraph2.set_xticklabels(xLabels) cocGraph2.set_ylim(0, 25) resolution = 5 # seconds cocConcXYList = model.calculateCocConc(record2.datalist, record2.cocConc, record2.pumpSpeed, resolution) # cocConcXYList returns a list of [time,conc]. # The following separates these into two equal length lists to be plotted cocConcList = [] timeList = [] for i in range(len(cocConcXYList)): timeList.append( cocConcXYList[i][0]) # essentially a list in 5 sec intervals cocConcList.append(cocConcXYList[i][1]) cocConcLine = Line2D(timeList, cocConcList, color='black', ls='solid') cocGraph2.text(0.85, 0.5, '2L-FR1-HD (4h)', ha='center', transform=cocGraph2.transAxes, fontsize=14) cocGraph2.add_line(cocConcLine)
def plot_frequency(obj, f, plot_type=None, **kwargs): obj = obj.doit() # Much of the hoop jumping is to speed up plotting since # obj.real can be slow. Instead we evaluate complex # objects and then convert to phase, magnitude, etc. norm = kwargs.pop('norm', False) npoints = kwargs.pop('npoints', 400) log_magnitude = kwargs.pop('log_magnitude', False) log_frequency = kwargs.pop( 'log_frequency', False) or kwargs.pop('log_scale', False) if kwargs.pop('loglog', False): log_magnitude = True log_frequency = True dbmin = kwargs.pop('dbmin', -120) label = kwargs.pop('label', None) nyticks = kwargs.pop('nyticks', None) color2 = kwargs.pop('color2', None) linestyle2 = kwargs.pop('linestyle2', '--') unwrap = kwargs.pop('unwrap', False) # FIXME, determine useful frequency range... if f is None: if norm: f = (-0.5, 0.5) else: f = (0, 2) if isinstance(f, (int, float)): f = (0, f) if isinstance(f, tuple): if log_frequency: fmin, fmax = parse_range(f, 1e-1, positive=True) f = np.geomspace(fmin, fmax, npoints) else: fmin, fmax = parse_range(f, 1e-1, positive=False) f = np.linspace(fmin, fmax, npoints) # Objects can have a `part` attribute that is set by methods such # as real, imag, phase, magnitude. If this is defined, # `plot_type` is ignored. plot1_type = 'default' plot2_type = None V = obj.evaluate(f) types = ['dB-phase', 'dB-radians', 'dB-phase-degrees', 'dB-degrees', 'mag-phase', 'magnitude-phase', 'mag-phase-degrees', 'magnitude-phase-degrees', 'real-imag', 'mag', 'magnitude', 'phase', 'radians', 'phase-degrees', 'degrees', 'real', 'imag', 'dB', 'abs'] if plot_type is not None and plot_type not in types: raise ValueError('Unknown plot type %s, expecting: %s ' % (plot_type, ', '.join(types))) if not V.dtype == complex: if plot_type is None: plot_type = 'real' elif obj.part == '': if plot_type is None: plot_type = 'dB-phase' if plot_type in ('dB_phase', 'dB-phase', 'dB-radians'): plot1_type = 'dB' plot2_type = 'radians' elif plot_type in ('dB_phase_degrees', 'dB-phase-degrees', 'dB-degrees'): plot1_type = 'dB' plot2_type = 'degrees' elif plot_type in ('mag_phase', 'magnitude_phase', 'mag-phase', 'magnitude-phase'): plot1_type = 'magnitude' plot2_type = 'radians' elif plot_type in ('mag_phase_degrees', 'magnitude_phase_degrees', 'mag-phase-degrees', 'magnitude-phase-degrees'): plot1_type = 'magnitude' plot2_type = 'degrees' elif plot_type in ('real_imag', 'real-imag'): plot1_type = 'real' plot2_type = 'imag' elif plot_type in ('mag', 'magnitude'): plot1_type = 'magnitude' elif plot_type in ('phase', 'radians'): plot1_type = 'radians' elif plot_type in ('phase-degrees', 'degrees'): plot1_type = 'degrees' elif plot_type == 'abs': plot1_type = 'abs' elif plot_type == 'real': plot1_type = 'real' elif plot_type == 'imag': plot1_type = 'imag' elif plot_type == 'dB': plot1_type = 'dB' else: raise RuntimeError('Internal error') deltas = None if kwargs.pop('plot_deltas', True) and obj.has(DiracDelta): cls = obj.__class__ rest, deltas = separate_dirac_delta(obj.expr) obj = cls(rest, **obj.assumptions) V = obj.evaluate(f) ax = make_axes(figsize=kwargs.pop('figsize', None), axes=kwargs.pop('axes', None)) if label is None: label = plot1_type lines = plotit(ax, obj, f, V, plot1_type, deltas, log_frequency=log_frequency, log_magnitude=log_magnitude, norm=norm, label=label, dbmin=dbmin, unwrap=unwrap, **kwargs) if plot2_type is None: return ax if color2 is None: color2 = lines[0].get_color() kwargs2 = kwargs.copy() for key in ('color', 'linestyle', 'xlabel', 'xlabel2', 'ylabel', 'title', 'xscale', 'yscale'): kwargs2.pop(key, None) # Dummy plot to add label to legend. ax.plot([], [], label=plot2_type, color=color2, linestyle=linestyle2, **kwargs2) ax2 = ax.twinx() kwargs['axes'] = ax2 kwargs.pop('color', None) plotit(ax2, obj, f, V, plot2_type, deltas, log_frequency=log_frequency, log_magnitude=log_magnitude, norm=norm, second=True, color=color2, linestyle=linestyle2, unwrap=unwrap, **kwargs) if plot2_type in ('phase', 'radians') and not unwrap: ax2.set_ylim(-np.pi, np.pi) elif plot2_type in ('phase-degrees', 'degrees') and not unwrap: ax2.set_ylim(-180, 180) if plot1_type == 'dB': Vabs = abs(V) Vmin = 10**(dbmin / 20) if np.all(Vabs < Vmin): warn('All values below dbmin') Vabs[Vabs < Vmin] = Vmin m = np.isinf(Vabs) if any(m): warn('Approximating infinite value!') Vabs[m] = 1e30 dB = 20 * np.log10(Vabs) dBmin = min(dB) dBmax = max(dB) ymin = np.floor(dBmin / 10) * 10 ymax = np.ceil(dBmax / 10) * 10 yrange = ymax - ymin if False: # Provide some wiggle room ymin -= yrange / 10 ymax += yrange / 10 yrange = ymax - ymin # This will clobber previous plot values ax.set_ylim(ymin, ymax) if nyticks is None: # An odd number is better to show zero phase. for nyticks in (7, 6, 5, 8, 9): if yrange / (nyticks - 1) in (20, 10, 5, 2): break from matplotlib import ticker if nyticks is None: nyticks = 5 ax.yaxis.set_major_locator(ticker.LinearLocator(nyticks)) ax2.yaxis.set_major_locator(ticker.LinearLocator(nyticks)) ax.legend() return ax, ax2
def _cont_target_vs_nominal_features(self): '''Visualize Discrete Univariate Statistics''' # Loop through each column name for feature in self.feature_col_names: plt.figure(figsize=(15, 5)) # Frequency Plot ### plt.subplot(1, 2, 1) feature += self.suffix ax = sns.countplot(x=feature, data=self.dataset) plt.title(f"{feature}") plt.xlabel(feature) plt.ylabel('Count') # Make twin axis ax2 = ax.twinx() # Switch so count axis is on right, frequency on left ax2.yaxis.tick_left() ax.yaxis.tick_right() # Also switch the labels over ax.yaxis.set_label_position('right') ax2.yaxis.set_label_position('left') ax2.set_ylabel('Frequency [%]') # Add Frequency values to Plot ncount = len(self.dataset) for p in ax.patches: x = p.get_bbox().get_points()[:, 0] y = p.get_bbox().get_points()[1, 1] ax.annotate('{:.1f}%'.format(100. * y / ncount), (x.mean(), y), ha='center', va='bottom') # set the alignment of the text # Use a LinearLocator to ensure the correct number of ticks ax.yaxis.set_major_locator(ticker.LinearLocator(10)) # Fix the frequency range to 0-100 ax2.set_ylim(0, 100) ax.set_ylim(0, ncount) # And use a MultipleLocator to ensure a tick spacing of 10 ax2.yaxis.set_major_locator(ticker.MultipleLocator(10)) ### TargetVar Box Plot Split on cats ### plt.subplot(1, 2, 2) sns.boxplot(data=self.dataset, x=feature, y=self.target_col_name) plt.title(f"{feature}") plt.show() ### ANOVA 1-Way Analysis ### mod = ols(f'lastsoldprice ~ {feature}', data=self.dataset[[self.target_col_name, feature]]).fit() aov_table = sm.stats.anova_lm(mod, typ=2) display(aov_table) print(''' ''')
def plot_color_wheel(name, output_dir=None, dpi=500, xlabel='Elevation', ylabel='Azimuth', fontsize=10, num_xticks=4, yticks=(-90, 90)): """Plots the color wheel for visualizations of 3D orintation. Parameters ---------- name : str Indicates the name of the output png file. output_dir : str Indicates the path to the output folder where the image will be stored. dpi : integer Indicates the DPI of the output image. xlabel : str Indicates the text along the x-axis. ylabel : str Indicates the text along the y-axis. fontsize : int Indicates the font size of labels along axes. num_xticks : int Indicates the number of ticks along axes. yticks : tuple Indicates the range of minimum and maximum values along the y-axis. """ azth, lat = np.linspace(0., 1., num=180), np.linspace(0., 1., num=90) rgb_arr = np.zeros((len(azth), len(lat), 3)) for i in xrange(len(azth)): for j in xrange(len(lat)): rgb_arr[i, j, :] = colors.hsv_to_rgb([azth[i], lat[j], 1.0]) fig, ax = plt.subplots(figsize=(2, 2)) ax.set_facecolor('red') ax.set_xlim([0, 90]) ax.set_ylim([0, 181]) ax.set_yticks(np.linspace(0, 180, num=7).astype(np.int32)) ax.set_yticklabels( np.linspace(yticks[0], yticks[1], num=7).astype(np.int32)) ax.set_xlabel(xlabel, fontsize=fontsize, labelpad=0, color='w') ax.set_ylabel(ylabel, fontsize=fontsize, labelpad=0, color='w') xmajorlocator = ticker.LinearLocator(num_xticks) ax.xaxis.set_major_locator(xmajorlocator) ax.tick_params(direction='out', length=2, width=0, labelsize=fontsize, pad=0, colors='w') ax.imshow(rgb_arr) if output_dir is not None: if not os.path.exists(output_dir): os.makedirs(output_dir) fig.savefig(os.path.join(output_dir, f'{name}_color_bar.png'), transparent=True, bbox_inches='tight', pad_inches=0.1, dpi=dpi) plt.show()
df_v['timestamp'] = df_v.index df_v.modularity = df_v.modularity.astype(float) df_v.var_info = df_v.var_info.astype(float) #df_v['modularity'].plot() fig, ax = plt.subplots(figsize=(12, 7)) plt.xticks(rotation=45) #plt.ylim(0.75, plot_df['resolution'].max()+0.05) ax.margins(x=0) g = sns.lineplot(data=df_v.iloc[:1501], x='timestamp', y='modularity', ax=ax, color='black') g.xaxis.set_major_locator(ticker.LinearLocator(10)) ax1 = g.axes #ax1.hlines(1.032, ls='--', color='red', linewidth=4, xmin = plot_df.loc[0, 'timestamp'], xmax = plot_df.loc[81300, 'timestamp']) #ax1.hlines(1.031, ls='--', color='blue', linewidth=4, xmin = plot_df.loc[81301, 'timestamp'], xmax = plot_df.loc[162600, 'timestamp']) #ax1.hlines(1.037, ls='--', color='green', linewidth=4, xmin = plot_df.loc[162601, 'timestamp'], xmax = plot_df.loc[243999, 'timestamp']) ax1.vlines(x=plot_df.loc[81300, 'timestamp'], colors='purple', ymin=0, ymax=df_v['modularity'].max() + 0.05, linewidths=4) #ax1.vlines(x = df_v.iloc[1510, 2], colors='purple', ymin = 0, ymax = df_v['modularity'].max()+0.05, linewidths = 4) ax1.vlines(x=plot_df.loc[162600, 'timestamp'], colors='purple', ymin=0, ymax=df_v['modularity'].max() + 0.05, linewidths=4)
Ym, dense, levels=[-1, 1], cmap=cm.bwr, linestyles='dashed', linewidths=[2, 2]) plt.contour(Xm, Ym, dense, levels=[0], colors='black', linestyles='dashed', linewidths=[2]) cb = plt.colorbar(cr, format='%+.1e') cb.solids.set_edgecolor('face') cb.set_ticks(ticker.LinearLocator(6)) cb.ax.tick_params(labelsize=12) rect.scatter(data0[:, 0], data0[:, 1], marker='v', facecolor='red', edgecolor='black', s=30, lw=1) rect.scatter(data1[:, 0], data1[:, 1], marker='^', facecolor='blue', edgecolor='black', s=30, lw=1)
p = str(t[1]) st = f"The week of {d} the average conventional motor oil stock price was ${p}" output.write(str(st) + "\n") #============================================================================================================================================================================================================================================================================================================================================================= #create visualization of multiple line lineplot for each area fig, ax = plt.subplots() ax.plot(date_list, eastcoast_list, "-r", label="East Coast") ax.plot(date_list, gulfcoast_list, "-m", label="Gulf Coast") ax.plot(date_list, midwest_list, "-y", label="Midwest") ax.plot(date_list, rockymountain_list, "-b", label="Rocky Mountains") ax.plot(date_list, westcoast_list, "-g", label="West Coast") ax.legend(loc="upper left") plt.xticks(fontsize=5, rotation=45) ax.xaxis.set_major_locator(ticker.LinearLocator(10)) ax.set_xlabel("Date") ax.set_ylabel("Ending Stock of Conventional Motor Gasoline (Dollars) Per Week") ax.set_title( "Ending Stock of Conventional Motor Gasoline Per Week By Area in U.S.") ax.grid fig.savefig("AreaOilPriceWeekly.png") plt.show() # ======================================================================================================= #create visualization of average gas price line plot fig, ax = plt.subplots() ax.plot(date_list, avg_list)
for i in np.linspace(XMin, XMax, NX): XList.append("%.f" % (i / 1000)) for i in np.linspace(YMin, YMax, NY): YList.append("%.f" % (i / 1000)) fig = plt.figure() ax = fig.add_subplot(111) norm = mplc.LogNorm() img = ax.imshow(data, norm=norm) ax.set_xlabel("Mpc") ax.set_ylabel("") ax.set_title("Gas Density(z=%.2f)" % (z)) xloc = tik.LinearLocator(NX) xfmt = tik.FixedFormatter(XList) yloc = tik.LinearLocator(NY) yfmt = tik.FixedFormatter(YList) ax.xaxis.set_major_locator(xloc) ax.xaxis.set_major_formatter(xfmt) ax.yaxis.set_major_locator(yloc) ax.yaxis.set_major_formatter(yfmt) ax.invert_yaxis() cbar = fig.colorbar(img) cbar.set_label(r"$gcm^{-2}$") fn_png = sys.argv[1][:-4] + '.png' print('save image to ' + fn_png)
def test_LinearLocator(): loc = mticker.LinearLocator(numticks=3) test_value = np.array([-0.8, -0.3, 0.2]) assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value)
def generate_diagram(t_current, data_files, diag_titles, diag_filename, errFlag): fig = plt.figure(constrained_layout=True, figsize=(16, 9)) gs = GridSpec(2, 1, figure=fig) axs = [fig.add_subplot(gs[0, 0]), fig.add_subplot(gs[1, 0])] for data_file, diag_title, ax, i in zip(data_files, diag_titles, axs, [0, 1]): if not(data_file is None): df = pd.read_csv(data_file, index_col='matplotlib_date') df.pop('year') df.pop('month') df.pop('day') df.pop('hour') df.pop('minute') df.pop('second') df.plot(ax=ax) else: ax.text(x=0.5, y=0.5, s='No temperature data available for this time period.', color='grey', alpha=0.35, fontsize=28, horizontalalignment='center', verticalalignment='center') if errFlag: loc = ['left', 'right'] msg = "An error occurred. Search log file \'{}\' for entries tagged as \'ERROR\' " \ "for more information.".format(constant.LOG_FILE) else: # No error, so put the title in the center. The error message that technically goes # to the right is empty and therefore doesn't matter. loc = ['center', 'right'] msg = '' ax.set_title(diag_title, color='blue', style='oblique', fontsize=14, loc=loc[0]) ax.set_title(msg, color='red', style='oblique', fontsize=14, loc=loc[1]) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.grid(color='grey', linestyle=':', linewidth=0.4) if not(data_file is None): if i == 0: yesterday = t_current - dt.timedelta(days=1) low = mdates.date2num(dt.datetime(yesterday.year, yesterday.month, yesterday.day, 21)) high = mdates.date2num(dt.datetime(t_current.year, t_current.month, t_current.day, 9)) ax.set_xlim(low, high) else: low = mdates.date2num(dt.datetime(t_current.year, t_current.month, t_current.day, 9)) high = mdates.date2num(dt.datetime(t_current.year, t_current.month, t_current.day, 21)) ax.set_xlim(low, high) xa = ax.get_xaxis() xa.set_label_text("Time") ma_x_form = mdates.DateFormatter('%H:%M') xa.set_major_formatter(ma_x_form) ma_x_loc = mdates.MinuteLocator(interval=30) xa.set_major_locator(ma_x_loc) mi_x_loc = mdates.MinuteLocator(interval=10) xa.set_minor_locator(mi_x_loc) ya = ax.get_yaxis() ya.set_label_text("Celsius") ma_y_form = ticker.StrMethodFormatter('{x:.2f}') ya.set_major_formatter(ma_y_form) ma_y_loc = ticker.LinearLocator(numticks=20) ya.set_major_locator(ma_y_loc) mi_y_loc = ticker.LinearLocator(numticks=39) ya.set_minor_locator(mi_y_loc) plt.savefig(diag_filename) plt.close('all') log.info("Diagram written to file system: %s", diag_filename)
setup(ax) majors = [0, 1, 5] ax.xaxis.set_major_locator(ticker.FixedLocator(majors)) minors = np.linspace(0, 1, 11)[1:-1] ax.xaxis.set_minor_locator(ticker.FixedLocator(minors)) ax.text(0.0, 0.1, "ticker.FixedLocator([0, 1, 5])", family=family, fontsize=fontsize, transform=ax.transAxes) # Linear Locator ax = plt.subplot(n, 1, 4) setup(ax) ax.xaxis.set_major_locator(ticker.LinearLocator(3)) ax.xaxis.set_minor_locator(ticker.LinearLocator(31)) ax.text(0.0, 0.1, "ticker.LinearLocator(numticks=3)", family=family, fontsize=fontsize, transform=ax.transAxes) # Index Locator ax = plt.subplot(n, 1, 5) setup(ax) ax.plot(range(0, 5), [0] * 5, color='white') ax.xaxis.set_major_locator(ticker.IndexLocator(base=.5, offset=.25)) ax.text(0.0, 0.1,
ticks = np.linspace(minv, maxv, 3) ax.tick_params(**tick_options) ax.text(0.05, 0.95, 'b', transform=ax.transAxes, fontsize=13, fontweight='bold', va='top') c = ax.tricontourf(x, y, v, levels=levels, cmap=plt.get_cmap(cmap)) cbar = plt.colorbar(c, ticks=ticks, pad=0.05, orientation="horizontal", format=ticker.FormatStrFormatter('%1.1e')) cbar.ax.xaxis.set_major_locator(ticker.LinearLocator(3)) cbar.ax.set_xlabel(r'$\sigma$ ($Pa^{0.5}$ $m^{-0.5}$ $yr^{0.5}$)') ax = fig.add_subplot(233) ax.set_aspect('equal') v = uv.compute_vertex_values(mesh) levels = np.linspace(10, 30, numlev) ticks = np.linspace(10, 30, 3) ax.tick_params(**tick_options) ax.text(0.05, 0.95, 'c', transform=ax.transAxes, fontsize=13, fontweight='bold',