parser.add_argument(metavar="simulation directories", dest="directories", help="simulation base directories", action="store", nargs="+") args = parser.parse_args() directories = args.directories # prepare plot of data plt.figure(figsize=(10, 5)) plt.title("charge conservation over time", fontsize=22) major_locator1 = LinearLocator() major_locator2 = LinearLocator() major_formatter = FormatStrFormatter('%1.1e') ax1 = plt.subplot(121) ax1.set_xlabel(r"$t\,[\Delta t]$", fontsize=20) ax1.set_ylabel(r"$\mathrm{max}|d|\,[\rho_\mathrm{max}(0)]$", fontsize=20) plt.xticks(fontsize=14) plt.yticks(fontsize=14) # always use scientific notation ax1.yaxis.set_major_locator(major_locator1) ax1.yaxis.set_major_formatter(major_formatter) ax2 = plt.subplot(122) ax2.set_xlabel(r"$t\,[\Delta t]$", fontsize=20) ax2.set_ylabel(r"$\left<|d|\right> \pm \sigma_d\,[\rho_\mathrm{max}(0)]$", fontsize=20) plt.xticks(fontsize=14)
def set_lj(self, count_rs, target, sd, series, count_series, compute_average, compute_sd, compute_cv, x_labels, dates): if self.nametowidget(".").engine.get_show_error_bar() != 0: show_error_bar = True et = self.nametowidget(".").engine.get_te(target, compute_average, compute_cv) else: show_error_bar = False self.lj.clear() self.lj.grid(True) um = self.get_um() lines = ([], [], [], [], [], [], []) for i in range(len(series) + 1): lines[0].append(target + (sd * 3)) lines[1].append(target + (sd * 2)) lines[2].append(target + sd) lines[3].append(target) lines[4].append(target - sd) lines[5].append(target - (sd * 2)) lines[6].append(target - (sd * 3)) #it's show time self.lj.set_xticks(range(0, len(series) + 1)) self.lj.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(21)) self.lj.yaxis.set_major_formatter(FormatStrFormatter("%.2f")) self.lj.set_xticklabels(x_labels, rotation=70, size=6) self.lj.plot(series, marker="8", label="data") for x, y in enumerate(series): self.lj.text( x, y, str(y), ) if show_error_bar: self.lj.errorbar(x, y, yerr=self.nametowidget(".").engine.percentage( et, y), uplims=True, lolims=True, ecolor="green") self.lj.plot(lines[0], color="red", label="+3 sd", linestyle="--") self.lj.plot(lines[1], color="yellow", label="+2 sd", linestyle="--") self.lj.plot(lines[2], color="green", label="+1 sd", linestyle="--") self.lj.plot(lines[3], label='target', linewidth=2) self.lj.plot(lines[4], color="green", label="-1 sd", linestyle="--") self.lj.plot(lines[5], color="yellow", label="-2 sd", linestyle="--") self.lj.plot(lines[6], color="red", label="-3 sd", linestyle="--") if um is not None: self.lj.set_ylabel(str(um[0])) else: self.lj.set_ylabel("No unit assigned yet") s = "{0} {1}".format( self.selected_test[1], self.selected_batch[2], ) self.lj.set_title(s, weight="bold", loc="center") bottom_text = ( "from %s to %s" % (dates[0].strftime("%Y-%m-%d"), dates[-1].strftime("%Y-%m-%d")), count_series, count_rs) self.lj.text(0.95, 0.01, '%s computed %s on %s results' % bottom_text, verticalalignment='bottom', horizontalalignment='right', transform=self.lj.transAxes, color='black', weight='bold')
continue fig = plt.figure() ax = fig.add_subplot(111) frequency,count, a = ax.hist(data_list, bins = 500, color = 'steelblue') #plot histogram ax.set_xlabel('Pixel Count', size='15') ax.set_ylabel('Frequency', size='15') ax.set_title('Image Upper Bound', fontweight = 'bold', size = '15') ax.xaxis.grid(True, ls = '--', which= 'minor') ax.yaxis.grid(True, ls = '--', which= 'minor') ax.xaxis.grid(True, ls = '-', which= 'major') ax.yaxis.grid(True, ls = '-', which= 'major') ax.xaxis.set_major_locator(MultipleLocator(2000)) ax.xaxis.set_major_formatter(FormatStrFormatter('%.2e')) ax.xaxis.set_minor_locator(MultipleLocator(1000)) ax.yaxis.set_major_locator(MultipleLocator(200)) ax.yaxis.set_minor_locator(MultipleLocator(100)) fig.savefig('UpperBoundtest') plt.show() #%% """ Identify brightest stars/galaxies """ def max_brightness(image_input, mask_image_ones): image_high = image_input * mask_image_ones #multiply mask image by CCD Image ind = np.unravel_index(np.argmax(image_high, axis=None), image_input.shape) #returns location of brightest pixel return ind
rdata.set_title('Full Time Series') s1 = 1200 s2 = 3200 rdataZ = fig.add_subplot(622) rdataZ.plot(t1[s1:s2], stRefRaw[0][s1:s2], 'r', label=labelRef) rdataZ.plot(t1[s1:s2], stNomRaw[0][s1:s2], 'b', label=labelNom) rdataZ.set_title('Zoomed Time Series') rdataZ.tick_params(labelleft='off') ## now plot up resp removed data noResp = fig.add_subplot(623) noResp.plot(t1, trNom.data, 'b', label=labelNom) noResp.plot(t1, trRef.data, 'r', label=labelRef) noResp.set_ylabel('Resp removed, \nDisplacement') noResp.yaxis.set_major_formatter(FormatStrFormatter('%g')) noRespZ = fig.add_subplot(624) noRespZ.yaxis.set_label_position("right") noRespZ.plot(t1[s1:s2], trNom.data[s1:s2], 'b', label=labelNom) noRespZ.plot(t1[s1:s2], trRef.data[s1:s2], 'r', label=labelRef) noRespZ.yaxis.set_major_formatter(FormatStrFormatter('%g')) ## now the .1 hz filtered data filtp1 = fig.add_subplot(625) filtp1.plot(t1, trNomfiltp1.data, 'b', label=labelNom) filtp1.plot(t1, trReffiltp1.data, 'r', label=labelRef) filtp1.set_ylabel('Filtered,0.1 Hz, \nDisplacement') s1 = 1000 s2 = 2000
# =================================================================== Run = "Run_1" F = open("Current_and_Power.txt", 'a') data = [] t = [] DataList = [] Current = [] Power = [] Voltage = 240.0 sum_Of_t = [] sum_Of_t.append(0) #fig1 = plt.figure(num=1, figsize=(12,8)) plt.figure(num=2, figsize=(12,8)) majorLocator = MultipleLocator(50) majorFormatter = FormatStrFormatter('%d') minorLocator = MultipleLocator(10) for infile in sorted(glob.glob('../InnovateUK/'+Run+'/*.csv'), key=numericalSort): print ("Current File Being Processed is: " + infile) DataList.append(infile) print (DataList[-1]) # 1:24:18 run time = 84.3 mins. # The drop off when the run ends is at csv number 1196 TimePerFile = 84.3/1196 for ii, file in enumerate(DataList): data, t = ReadCSV(file)
for line in sysems[list(sysemp.keys())[n][1:]] ][:dim], np.array([ float(line.strip().split()[12]) for line in sysemp[list(sysemp.keys())[n]] ][:dim]), label='%s' % (list(sysemp.keys())[n][1:])) ax2.plot([ float(line.strip().split()[0]) for line in sysems[list(sysemp.keys())[n][1:]] ][:dim], np.array([ float(line.strip().split()[12]) for line in sysemp[list(sysemp.keys())[n]] ][:dim]) / np.array([ float(line.strip().split()[12]) for line in sysemp[list(sysemp.keys())[1]] ][:dim]), label='%s' % (list(sysemp.keys())[n][1:])) #ax1.set_ylim([0, 5]) ax1.yaxis.set_major_formatter(FormatStrFormatter('%d')) plt.legend(loc='center left', numpoints=1, fontsize=14, bbox_to_anchor=(1.0, .4)) strFile = 'rms_radii.pdf' if os.path.isfile(strFile): os.remove(strFile) plt.savefig(strFile)
) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax[0].plot(sa_tsp.best_y_history) ax[0].set_ylabel("Distance") ax[0].set_xlabel("Iteration") ax[0].set_title('Distance improvements over each iteration') ax[1].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], marker='o', markerfacecolor='b', color='c', linestyle='-') ax[1].xaxis.set_major_formatter(FormatStrFormatter('%.3f')) ax[1].yaxis.set_major_formatter(FormatStrFormatter('%.3f')) ax[1].set_title( 'Final minimum travelled path: minimum distance = {0:.2f}km '.format( best_distance)) ax[1].set_xlabel("Longitude") ax[1].set_ylabel("Latitude") plt.show() # %% Now Plot the animation import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation best_x_history = sa_tsp.best_x_history fig2, ax2 = plt.subplots(1, 1)
def make_figure_7b(ax): import matplotlib matplotlib.rcParams['text.usetex'] = True import matplotlib.pyplot as plt #to implement plots import csv #to read and process CSV files import numpy as np #to format numbers from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator) es = [] #x-axis data qstnm = [] #y-axis data 1 qstqst = [] #y-axis data 2 #open CSV file with open('../fig7b.csv') as csvDataFile: csvReader = csv.reader(csvDataFile) #file handler for row in csvReader: #loop through file handler es.append(row[0]) #load up second column element qstnm.append(row[1]) #load up third column element qstqst.append(row[2]) qstnmFloat = list(map(float, qstnm)) qstqstFloat = list(map(float, qstqst)) #fig, ax = plt.subplots() x = np.arange(len(es)) #label locations width = 0.1 #width of the bars plt.rcParams['font.size'] = '16' rects1 = ax.bar(x - 0.15, qstnmFloat, width, label=r'$T_1$', color=c_list['mid-red']) rects2 = ax.bar(x - 0.05, qstqstFloat, width, label=r'$S_1$', color=c_list['mid-blue']) def autolabel(rects, xpos='center', jr=0): ha = {'center': 'center', 'right': 'left', 'left': 'right'} offset = {'center': 0, 'right': 1, 'left': -1} for rect in rects: y_value = rect.get_height() x_value = rect.get_x() + rect.get_width() / 2 space = 5 va = 'bottom' if y_value < 0: space = 1 #*= -1 #va = 'top' label = "{:.1f}".format(y_value) ax.annotate( label, # Use `label` as label (x_value, 20 - 3 * (jr // 2)), # Place label at end of the bar xytext=(0, space), # Vertically shift label by `space` textcoords= "offset points", # Interpret `xytext` as offset in points ha='center', # Horizontally center label va=va, fontsize=20) # Vertically align label differently for # positive and negative values. if (y_value > 0): ax.plot([x_value, x_value], [20 - 3 * (jr // 2) + 0.5, y_value + 0.5], linestyle='--', color='black', linewidth=0.8) else: ax.plot([x_value, x_value], [20 - 3 * (jr // 2) + 0.5, 0.5], linestyle='--', color='black', linewidth=0.8) jr += 1 return jr jr = 0 jr = autolabel(rects1, "center", jr) jr = autolabel(rects2, "center", jr) ax.set_xticks(x) #axis setting of X ticks ax.set_xticklabels(es) #axis setting of X tick labels ax.set_title('(b) 2F-PSPCz', pad=10) ax.set_ylabel(r' $ \Delta \Delta E_{Exact}$', fontsize=20) ax.get_yaxis().set_major_formatter(FormatStrFormatter('% 1.1f'))
def tornado( data, namesX, namesY, x, dist, dem, varValues, varUnits, dfHSC, imagepath, best, figSize=0, saveFig=False, savePath='C:\\Alles\\Sciebo\\Python\\Trunk\\Images\\default\\', saveName='FigureTornado'): ''' ''' dataMin = np.min(data) - 0.5 dataMax = np.max(data) + 0.5 maxValues=best names = namesY names[names == 'electricityCostLow'] = 'electricityCost\nRES' names[names == 'electricityCostHigh'] = 'electricityCost\navg' # title=namesX[x] bases = np.array(data[:, x, 1]) base = bases[0] lows = np.array(data[:, x, 0]) highs = np.array(data[:, x, 2]) changeLows = (lows / bases - 1) * 100 changeHighs = (highs / bases - 1) * 100 sorts = np.absolute(highs - lows) sorts, lows, highs, names, bases, changeLows, changeHighs, varValues, varUnits = zip( *sorted(zip(sorts, lows, highs, names, bases, changeLows, changeHighs, varValues, varUnits), reverse=True)) sorts, lows, highs, names, bases, changeLows, changeHighs, varValues, varUnits = sorts[:maxValues], lows[:maxValues], highs[:maxValues], names[:maxValues], bases[:maxValues], changeLows[:maxValues], changeHighs[:maxValues], varValues[:maxValues], varUnits[:maxValues] ########################################################################### # The actual drawing part # The y position for each variable ys = range(len(highs))[::-1] # top to bottom if figSize==0: fig = plt.figure() else: fig=plt.figure(figsize=figSize) ########################################################################### # Images of the Supplychain imageDf = {} steps = [ 'Production', 'Connector1', 'Storage', 'Connector2', 'Transport', 'Station'] for i, step in zip(range(len(steps)), steps): imageDf[step] = mpimg.imread(imagepath + dfHSC[step][x] + '.png') technology = dfHSC[step][x] # imageDf[step]=mpimg.imread(path+system+'.png') sp = fig.add_subplot(6, 6, i + 1) imgplot = sp.imshow(imageDf[step]) sp.get_xaxis().set_visible(False) sp.get_yaxis().set_visible(False) if technology == "Nothing2" or technology == "Nothing3": continue # if styleUsed == "\matplotlibrcEES.mplstyle": # sp.set_title(technology) # elif styleUsed == "\matplotlibrc.mplstyle": # sp.set_title(technology) ########################################################################### axes = plt.subplot2grid((20, 20), (4, 1), colspan=17, rowspan=16) # Plot the bars, one by one for y, low, high, base, changeLow, changeHigh, varValue, varUnit in zip( ys, lows, highs, bases, changeLows, changeHighs, varValues, varUnits): # The width of the 'low' and 'high' pieces low_width = base - low high_width = high - base # Each bar is a "broken" horizontal bar chart axes.broken_barh( [(low, low_width), (base, high_width)], (y - 0.4, 0.8), # Try different colors if you like facecolors=[(81 / 255, 83 / 255, 86 / 255), (0 / 255, 91 / 255, 130 / 255)], edgecolors=['black', 'black'], # 'none', linewidth=1) strValue = str(varValue) + ' ' + varUnit plt.text(dataMax + 0.1, y, strValue, va='center', ha='left', color='black') # Display the change as text z = 0.6 if low_width > 0: if low_width > z: plt.text(base - low_width / 2, y, str(np.around(changeLow, 1)) + '%', va='center', ha='center', color='white') else: plt.text(low - z / 2, y, str(np.around(changeLow, 1)) + '%', va='center', ha='center', bbox=dict(facecolor='white', alpha=0.5, edgecolor='none',pad=0.1)) else: if low_width < -z: plt.text(base - low_width / 2, y, str(np.around(changeLow, 1)) + '%', va='center', ha='center', color='white') else: plt.text(low + z / 2, y, str(np.around(changeLow, 1)) + '%', va='center', ha='center', bbox=dict(facecolor='white', alpha=0.5, edgecolor='none',pad=0.1)) if high_width > 0: if high_width > z: plt.text(base + high_width / 2, y, str(np.around(changeHigh, 1)) + '%', va='center', ha='center', color='white') else: plt.text(high + z / 2, y, str(np.around(changeHigh, 1)) + '%', va='center', ha='center', bbox=dict(facecolor='white', alpha=0.5, edgecolor='none',pad=0.1)) else: if high_width < -x: plt.text(base + high_width / 2, y, str(np.around(changeHigh, 1)) + '%', va='center', ha='center', color='white') else: plt.text(high - z / 2, y, str(np.around(changeHigh, 1)) + '%', va='center', ha='center', bbox=dict(facecolor='white', alpha=0.5, edgecolor='none',pad=0.1)) # Draw a vertical line down the middle axes.axvline(base, color='black',linewidth=1) # Additional Information info = str(dist) + ' km distance\n' + \ str(dem / 1000).rstrip('0').rstrip('.') + ' t/day demand' # Position the x-axis on the top, hide all the other spines (=axis lines) # axes.xaxis.set_ticks_position('top') axes.xaxis.set_major_formatter(FormatStrFormatter('%.2f €')) axes.set_xlabel('Total Cost of Hydrogen [€/kg]') #axes.xaxis.set_label_coords(0.5, 1.1) # Make the y-axis display the variables plt.grid() plt.yticks(ys, names) lowPatch = mpatches.Patch( color=( 81 / 255, 83 / 255, 86 / 255), label='-20%') highPatch = mpatches.Patch( color=( 0 / 255, 91 / 255, 130 / 255), label='+20%') infoPatch = mpatches.Patch(color='w', label=info) if styleUsed == "\matplotlibrcEES.mplstyle": if(dataMin + dataMax) / 2 > base: plt.legend(handles=[lowPatch, highPatch], loc=4) else: plt.legend(handles=[lowPatch, highPatch], loc=3) elif styleUsed == "\matplotlibrc.mplstyle": if(dataMin + dataMax) / 2 > base: plt.legend(handles=[infoPatch, lowPatch, highPatch], loc=4) else: plt.legend(handles=[infoPatch, lowPatch, highPatch], loc=3) # Set the portion of the x- and y-axes to show axes.set_xlim([dataMin, dataMax]) if saveFig==True: #plt.savefig(savePath+'Tornados\\'+saveName+str(x)) png1=BytesIO() fig.savefig(png1,format='png') png2 = Image.open(png1) png2.save(savePath+'Tornados\\'+saveName+str(x)+'.tiff') png1.close() plt.show() return names[0], names[1], names[2]
def main(): print('Loading Data...') f_vid_front_load = glob.glob( os.path.join( p_vid_load, 'rat{}*VG_{}_{}_Front.mkv'.format(RATNUM, WHISKER_ID, TRIAL)))[0] f_vid_top_load = glob.glob( os.path.join( p_vid_load, 'rat{}*VG_{}_{}_Top.mkv'.format(RATNUM, WHISKER_ID, TRIAL)))[0] f_3D_data = glob.glob( os.path.join( p_3D_data, 'rat{}*VG_{}_{}_E3D_PROC.mat'.format(RATNUM, WHISKER_ID, TRIAL)))[0] f_2D_data = glob.glob( os.path.join( p_2D_data, 'rat{}*VG_{}_{}_toMerge.mat'.format(RATNUM, WHISKER_ID, TRIAL)))[0] f_1K_data = glob.glob( os.path.join(p_3D_data, 'rat{}*VG_{}_{}_1K.mat'.format(RATNUM, WHISKER_ID, TRIAL)))[0] if not os.path.isfile(f_vid_front_load): raise ValueError('Front Video is not a valid video file') elif not os.path.isfile(f_vid_top_load): raise ValueError('Top Video is not a valid video file') elif not os.path.isfile(f_2D_data): raise ValueError('2D Whisker Data is not a valid file') elif not os.path.isfile(f_3D_data): raise ValueError('3D Whisker Data is not a valid file') elif not os.path.isfile(f_1K_data): raise ValueError('1K Mechanics data is not a valid file') frames = np.arange(START_FRAME, STOP_FRAME, FRAME_STEP) # === LOAD IN DATA FILES === # v_front = pims.open(f_vid_front_load) v_top = pims.open(f_vid_top_load) # dat2D = h5py.File(f_2D_data,'r') # NOT IMPLEMENTING 2D TRACKING. Could possibly dp back projections? dat_3D = loadmat(f_3D_data) dat_1K = loadmat(f_1K_data) # === CALCULATE REQUIRED VARIABLES === # print('Calculating Vars...') # get spikes sp_1k = dat_1K['sp'][0][CELL_NUM] spbool = get_spbool(dat_1K, cell_num=CELL_NUM) # get a contact boolean Cbool = dat_1K['use_flags'].ravel() Cbool[np.isnan(Cbool)] = 0 Cbool = Cbool.astype('bool') # get moment and its bounds M = dat_1K['filtvars'][0]['M'][0] * 10**6 temp1 = get_ms_idx(dat_3D, frames[0], T_RANGE)[0] - T_RANGE temp2 = get_ms_idx(dat_3D, frames[-1], T_RANGE)[0] + T_RANGE maxM = np.nanmax(np.nanmax(M[temp1:temp2, :], axis=0)) minM = np.nanmin(np.nanmin(M[temp1:temp2, :], axis=0)) # set noncontact moment to zero M[np.invert(Cbool), :] = 0 F = dat_1K['filtvars'][0]['F'][0] * 10**6 maxF = np.nanmax(np.nanmax(F[temp1:temp2, :], axis=0)) minF = np.nanmin(np.nanmin(F[temp1:temp2, :], axis=0)) # set noncontact moment to zero F[np.invert(Cbool), :] = 0 # init spike frames for spike induced 3DCP plot spike_frames = [] R = get_rotation(dat_1K) maxR = np.nanmax(np.nanmax(R[temp1:temp2, :], axis=0)) minR = np.nanmin(np.nanmin(R[temp1:temp2, :], axis=0)) # set noncontact vars to zero M[np.invert(Cbool), :] = 0 F[np.invert(Cbool), :] = 0 R[np.invert(Cbool), :] = 0 # get 3D contact point Xcp = dat_3D['CPm'][:, 0] Ycp = dat_3D['CPm'][:, 1] Zcp = dat_3D['CPm'][:, 2] # get axis bounds on the 3D whisker bds = get_bounds(dat_3D, frames) # make sure we dont try to grab frames past the length of the video if (frames[-1] >= len(v_front)) or (frames[-1] >= len(v_top)): raise ValueError('Desired frame range exceeds size of videos') # === SET UP PLOTTING === # # Initialize subplot axes and positioning fig = plt.figure(figsize=(11, 9), dpi=150) axVid = plt.subplot2grid((6, 2), (0, 0), rowspan=3, colspan=2) ax3 = plt.subplot2grid((6, 2), (3, 0), rowspan=3, projection='3d') axMoment = plt.subplot2grid((6, 2), (3, 1)) axForce = plt.subplot2grid((6, 2), (4, 1)) axRotation = plt.subplot2grid((6, 2), (5, 1)) plt.tight_layout() # Set count for iteration of frame numbers count = 0 # === Loop over the frames to plot === # for frame in frames: print('\tFrame {} of {}'.format(frame, frames[-1])) # append the current contact point if a spike happened since the last frame if spikes_in_frame(dat_3D, frame) > 0: spike_frames.append(frame) # ============ 2D video ============== # # get image If = v_front.get_frame(frame)[:, :, 0] It = v_top.get_frame(frame)[:, :, 0] I = np.concatenate([If, It], axis=1) # plot and format axes of 2D vid axVid.cla() axVid.imshow(I, cmap='gray') axVid.set_xticklabels([]) axVid.set_yticklabels([]) axVid.grid('off') axVid.set_title('2D video in Front and Top') axVid.set_xticks([]) axVid.set_yticks([]) # ============= plot 3D whisker and contact point ======================== # grab 3D points for whisker and contact point history xx, yy, zz = get_whisker_3D_pts(dat_3D, frame) # xx,yy,zz = rotate_pts(xx,yy,zz,frame,dat_1K) xcp = Xcp[frame - HISTORY:frame] ycp = Ycp[frame - HISTORY:frame] zcp = Zcp[frame - HISTORY:frame] # xcp,ycp,zcp = rotate_pts(xcp,ycp,zcp,frame,dat_1K) # plot and format 3D whisker shape plotting. # Multiplying by 1000 to convert meters to mm ax3.cla() ax3.axis('equal') # 3D whisker ax3.plot((xx - xx[0]) * 1000, (yy - yy[0]) * 1000, (zz - zz[0]) * 1000, 'k') # Basepoint ax3.scatter(0, 0, 0, 'o', c='r') # Contact point history ax3.scatter((xcp - xx[0]) * 1000, (ycp - yy[0]) * 1000, (zcp - zz[0]) * 1000, 'ko', c=np.linspace(0, 0.3, HISTORY)) # Contact point when a spike occured ax3.plot((Xcp[spike_frames] - xx[0]) * 1000, (Ycp[spike_frames] - yy[0]) * 1000, (Zcp[spike_frames] - zz[0]) * 1000, c='r', marker='o', alpha=0.05) ax3.patch.set_facecolor('w') ax3.view_init(15, 200) # Rotate plot for better view # set background color ax3.w_xaxis.set_pane_color((0., 0., 0., 0.4)) ax3.w_yaxis.set_pane_color((0., 0., 0., 0.4)) ax3.w_zaxis.set_pane_color((0., 0., 0., 0.4)) # labeling ax3.set_title('3D whisker shape') ax3.set_xlabel('X(mm)', labelpad=10) ax3.set_ylabel('Y(mm)', labelpad=10) ax3.set_zlabel('Z(mm)', labelpad=2) # format numbers of labels ax3.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax3.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax3.zaxis.set_major_formatter(FormatStrFormatter('%.0f')) # set axes limits based on min-max extent of the whisker ax3.set_xlim([bds['minx'] * 1000, bds['maxx'] * 1000]) ax3.set_ylim([bds['miny'] * 1000, bds['maxy'] * 1000]) ax3.set_zlim([bds['minz'] * 1000, bds['maxz'] * 1000]) # ========= Mechanics and spike =================== # # get the indices in ms for the desired frame range. # Since the frame data is sampled at 300/500 fps and the filtered mechanics are at 1000fps, need to use the # time of the frames to index to the closest ms. This is approximate, and could be off by ~1ms in either direction. ms_idx = get_ms_idx(dat_3D, frame, t_range=T_RANGE) for ii, axis in enumerate([axMoment, axForce, axRotation]): # set up axes axis.cla() axis.axis( 'normal' ) # need to do this because of the previous call to equal axes? axis.set_xlim([ms_idx[0], ms_idx[1]]) # plot mechanics for the given time. if ii == 0: cmap = sns.color_palette('Reds_d', 3) axis.set_prop_cycle(color=cmap) axis.plot(np.arange(ms_idx[0], ms_idx[1]), M[ms_idx[0]:ms_idx[1], :]) axis.set_ylim([minM, maxM]) elif ii == 1: cmap = sns.color_palette('Blues_d', 3) axis.set_prop_cycle(color=cmap) axis.plot(np.arange(ms_idx[0], ms_idx[1]), F[ms_idx[0]:ms_idx[1], :]) axis.set_ylim([minF, maxF]) elif ii == 2: cmap = sns.color_palette('Greens_d', 3) axis.set_prop_cycle(color=cmap) axis.plot(np.arange(ms_idx[0], ms_idx[1]), R[ms_idx[0]:ms_idx[1], :]) axis.set_ylim([minR, maxR]) # plot spikes for the given time sp_idx = np.logical_and(sp_1k > ms_idx[0], sp_1k < ms_idx[1]) axis.vlines(sp_1k[sp_idx], axis.get_ylim()[0], axis.get_ylim()[1] / 2, alpha=0.5) # plot a vertical line to indicate the current frame axis.vlines(dat_3D['frametimes'][frame][0] * 1000, axis.get_ylim()[0], axis.get_ylim()[1], colors='r', linestyles='dashed') # labelling if ii == 0: axis.legend(['M$_x$', 'M$_y$', 'M$_z$', 'spikes'], loc=1, labelspacing=0) # axis.set_title('Moment over time') axis.set_xlabel('') axis.set_xticks([]) axis.set_ylabel('Moment ($\mu$N-m)') sns.despine(ax=axis) elif ii == 1: axis.legend(['F$_x$', 'F$_y$', 'F$_z$'], loc=1, labelspacing=0) # axis.set_title('Force') axis.set_xlabel('') axis.set_xticks([]) axis.set_ylabel('Force ($\mu$N)') sns.despine(ax=axis) elif ii == 2: axis.legend(['$\Delta\\theta$', '$\Delta\phi$'], loc=1, labelspacing=0) # axis.set_title('Rotation') axis.set_xlabel('Time (ms)') axis.set_ylabel('Rotation') sns.despine(ax=axis) # save the image and iterate image number sns.despine(ax=axVid, left=True, bottom=True) plt.savefig(os.path.join(p_vid_save, f_vid_save + '{:05d}.png'.format(count)), dpi=300) count += 1 audio = gen_spike_track(dat_3D, frames, fps=FPS) wavfile.write(os.path.join(p_vid_save, f_vid_save + '.wav'), 44100, audio) subprocess.call([ 'ffmpeg', '-f', 'image2', '-r', str(FPS), '-i', os.path.join(p_vid_save, f_vid_save + '%05d.png'), '-i', os.path.join(p_vid_save, f_vid_save + '.wav'), '-c:v', 'libx264', '-c:a', 'libvo_aacenc', '-y', os.path.join(p_vid_save, f_vid_save + '.mp4') ]) # move all pngs new_subdir = os.path.join(p_vid_save, f_vid_save) os.makedirs(os.path.join(new_subdir)) for item in os.listdir(p_vid_save): if item.endswith('.png') or item.endswith('.wav'): shutil.move(os.path.join(p_vid_save, item), os.path.join(new_subdir, item))
return noise_z x = np.arange(0, 1, 0.025) y = np.arange(0, 1, 0.025) x, y = np.meshgrid(x,y) z = FrankeFunction(x, y) + f_noise_franke(x, y) # Plot the surface. fig = plt.figure() ax = fig.gca(projection="3d") surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,linewidth=0, antialiased=False) # Customize the z axis. ax.set_zlim(-0.10, 1.40) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter("%.02f")) # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() # Unravel xy meshgrid and z matrix into vectors x = np.ravel(x) y = np.ravel(y) z = np.ravel(z) # Create design matrix of polynomial degree 5 X = np.c_[np.ones(len(x)), # We have to try different polynomial degrees for the report and discuss which ones are best x, y, x*x, y*y, x*y, x*x*x, x*x*y, x*y*y, y*y*y, x*x*x*x, x*x*x*y, x*x*y*y, x*y*y*y, y*y*y*y,
def execute2(): global cx global cy global cyaw global ck global s global global_path_x global global_path_y global state global last_idx global x global y global yaw global v global t global time global accelPub_ global brakePub_ global steerPub_ global history_x, history_y state = State(x=global_path_x[0], y=global_path_y[0]) while True: if len(cx) >0 and len(cy) > 0 and len(global_path_x)>0 and len(global_path_y)>0 : #state = State(x=global_path_x[0], y=global_path_y[0], yaw=np.radians(20.0), v=0.0) accel_ = Int16() brake_ = Int16() # accel_.data, brake_.data = PID() accel_.data = 2000 accelPub_.publish(accel_) brakePub_.publish(brake_) target_idx, error_front_axle = calc_target_index(state, cx, cy) di, target_idx = stanley_control(state, cx, cy, cyaw, target_idx) msg = Int16() state.update(di) # 추후 주석 처리하기~ if math.isnan(di): di = 0.0 # print("delta: ", di) # print("error_front_axle: ", error_front_axle) print("target_idx: ", target_idx) # down_delta = float(di * 180/(math.pi)/1800) # print("down_delta: ", down_delta) # 71 = 2000/28.1690 raw_steer = int(-di*(180/(math.pi))*(525/35.75)) print("raw_steer: ", raw_steer) if -530 < raw_steer < 530: msg.data = raw_steer elif raw_steer <= -530: msg.data = -530 elif raw_steer >= 530: msg.data = 530 print("Steer: ", msg.data) steerPub_.publish(msg) # deaccel_speed = deacceleration(di) # print("deaccel_speed: ", deaccel_speed) print("Accel: ", accel_.data) print("Brake: ", brake_.data) print("utm_x: ", utm_x) print("utm_y: ", utm_y) print("-----------------------------------------------") #print("limitedSteer: ", msg.data) #print("pidout: ", pid_out) time += dt x.append(state.x) y.append(state.y) yaw.append(state.yaw) v.append(state.v) t.append(time) history_x.append(state.x) history_y.append(state.y) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) # course가 local path의 역할을 함. # course를 그릴 때 cx, cy가 필요함. plt.plot(cx, cy, ".y", label="course") # plt.scatter(global_path_x, global_path_y) plt.plot(x, y, "-b", label="trajectory") plt.plot(history_x, history_y, "-c", label="history") try: plt.plot(cx[target_idx], cy[target_idx], "xk", label="target") except: print("plot error") #plt.axis("equal") plt.grid(True) plt.title("Speed[km/h]:" + str(gpsvel)[:4]) plt.axis([min(global_path_x)-5, max(global_path_x)+5, min(global_path_y)-5, max(global_path_y)+5]) # plt.axis("equal") plt.pause(0.001) majorLocator = MultipleLocator(20) majorFormatter = FormatStrFormatter('%d') minorLocator = MultipleLocator(5) ''' while last_idx - 10 <= target_idx <= last_idx: accel_ = Int16() brake_ = Int16() accel_.data = 0 brake_.data = int(15*(8-gpsvel)) accelPub_.publish(accel_) brakePub_.publish(brake_) print("Accel: ", accel_.data) print("Brake: ", brake_.data) if last_idx -5 < target_idx: break ''' pass
def data_graph(graph=False): """ Gets data from folder or list of files or file and graphs it in some manner :param graph: :return: """ def axes_data(use_cols1, data1, domain=None): if domain is not None: axis = [0] * (2 * len(use_cols1)) for k in range(len(use_cols1)): axis[2 * k] = domain axis[2 * k + 1] = data1[k] return axis else: axis = [data1[k] for k in use_cols1] return axis if graph: axes = axes_data(use_cols, data, domain=data_domain) if scatter: for i in range(int(len(axes) / 2)): if i % 2 == 0: plt.scatter(axes[2 * i], axes[2 * i + 1], color_list[i], label=labo[i]) else: plt.scatter(axes[2 * i], axes[2 * i + 1], color_list[i], label=labo[i]) if connect: for i in range(int(len(axes) / 2)): if i % 2 == 0: plt.plot(axes[2 * i], axes[2 * i + 1], color_list[i], label=labo[i]) else: plt.plot(axes[2 * i], axes[2 * i + 1], color_list[i], label=labo[i]) if errorbar: plt.errorbar(*axes, yerr=data[std_col], fmt='o', label=labo) if contour: from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter fig = plt.figure() ax = fig.gca(projection='3d') z = axes[2][:100] len_z = len(z) n = np.sqrt(len_z) x = np.arange(0, n) y = x x, y = np.meshgrid(x, y) two_dz = z.reshape((int(n), int(n))) surf = ax.plot_surface(x, y, two_dz, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. ax.set_zlim(0, 0.18) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5) # heat_map = plt.pcolor(two_dz) # heat_color = plt.colorbar(heat_map, orientation = 'horizontal') # heat_color.set_label('Average Fidelity') plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.legend() plt.show()
ax1.set_ylabel(r'$x_2$') ax1.set_xlim([min(df['x1']), max(df['x1'])]) ax1.set_ylim([min(df['x2']), max(df['x2'])]) #ax1.set_aspect(abs((max(df['x1'] - min(df['x1']))) / (max(df['x2'] - min(df['x2']))))) ax2.set_xlabel(r'$x_1$') ax2.set_ylabel(r'$x_2$') ax2.set_xlim([min(df['x1']), max(df['x1'])]) ax2.set_ylim([min(df['x2']), max(df['x2'])]) #ax2.set_aspect(abs((max(df['x1'] - min(df['x1']))) / (max(df['x2'] - min(df['x2']))))) ax3.set_xlabel(r'1/k') ax3.set_ylabel('error') ax3.set_xscale('log') ax3.set_xlim([1 / k_max, 1]) ax3.xaxis.set_major_formatter(FormatStrFormatter('%.3f')) ax3.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) ax3.set_title('Error rates vs. 1/k') ax4.set_xlabel(r'1/k') ax4.set_ylabel('sensitivity / specificity') ax4.set_xscale('log') ax4.set_xlim([1 / k_max, 1]) ax4.xaxis.set_major_formatter(FormatStrFormatter('%.3f')) ax4.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) ax4.set_title('Sens./Spec. vs. 1/k') # plot prediction regions ax1.pcolor(ee, nn, decision_regions, cmap=custom_colors) ax2.pcolor(ee, nn, decision_regions, cmap=custom_colors)
#filt_lvf = blocking * np.ones(fp_pix[0]) eta_lvf = eta_lvf * np.ones(fp_pix[0]) eta_tot = eta_opt * eta_fpa * eta_lvf if verbose == 2: ax.semilogx(lam, eta_opt, linestyle='-', label='AU Optics, 5 reflections') ax.semilogx(lam, eta_lvf, linestyle='-', label='Dispersive Element') ax.semilogx(lam, eta_fpa, linestyle='-', label='FPA QE') ax.semilogx(lam,eta_tot,linestyle='-',marker='',\ label='Total System Efficiency',linewidth=2) ax.set_xlabel(r'$\lambda$ ($\mu$m)') ax.set_ylabel(r'Optical Efficiency') ax.set_xlim([0.75, 7.5]) ax.xaxis.set_ticks(tmpl) ax.xaxis.set_major_formatter(FormatStrFormatter('%1.1f')) plt.legend(loc=4) plt.tight_layout() plt.savefig('cdim_sbsens_eta_R' + str(R) + '.pdf') # compute entendue of a detector AOmega = 0.25 * np.pi * (Apert**2) * ( ((th_pix / 3600) * np.pi / 180.)**2) #m^2/sr if verbose: print "Entendue is: " + str(AOmega) + " m^2 sr." # generate an array of appropriate read noise dQ_lam = np.zeros(fp_pix[0]) dQ_lam[np.where(fp_det_type == 1)] = dQ[0] dQ_lam[np.where(fp_det_type == 2)] = dQ[1]
ax_list[0].set_ylabel(r"$n$", fontsize='large', rotation=0, labelpad=20) ax_list[0].tick_params( axis='x', labelbottom='off') # Remove top plot's x-axis labels plt.ylim((the_mins[1], the_maxs[1])) ax_list.append(ax_list[0].twinx()) temp_plot = ax_list[1].plot(x, temperature, label=r"$T$",\ color='red', linewidth=2) ax_list[1].set_ylabel(r"$T$", fontsize='large', rotation=0, labelpad=20) plt.ylim((the_mins[2], the_maxs[2])) ax_list[1].set_yticks(numpy.linspace(ax_list[1].get_yticks()[0],\ ax_list[1].get_yticks()[-1], len(ax_list[0].get_yticks()))) ax_list[0].grid(True) ax_list[0].yaxis.set_major_formatter(FormatStrFormatter('%.1e')) ax_list[1].grid(True) ax_list[1].yaxis.set_major_formatter(FormatStrFormatter('%.0f')) # BOTTOM STATE PLOT ax_list.append(plt.subplot(2, 1, 2)) Z_plot = ax_list[2].plot(x, Z, label=r"$Z$", color='green', linewidth=2) ax_list[2].set_ylabel(r"$Z$", fontsize='large', rotation=0, labelpad=20) plt.ylim((min(the_mins[3], the_mins[4]), max(the_maxs[3], the_maxs[4] + 0.1))) ax_list.append(ax_list[2].twinx()) D_plot = ax_list[3].plot(x, Diffusivity, label=r"$D$",\ color='orange', linewidth=2) ax_list[3].set_ylabel(r"$D$", fontsize='large', rotation=0, labelpad=20) plt.ylim((min(the_mins[3], the_mins[4]), max(the_maxs[3],
axs[0].set_ylabel(r'$\delta\rho_d/\rho_d$') lines1, labels1 = axs[0].get_legend_handles_labels() axs[0].legend(lines1, labels1, loc=(0.6,-0.07), frameon=False, ncol=1, labelspacing=0.3, handletextpad=0.1) title=r"Z={0:1.2f}, St={1:4.0e}, $\delta$={2:4.0e}".format(metal, stokes, delta) axs[0].set_title(title,weight='bold') axs[1].plot(z_1f, W1f.real, linewidth=2, label=r'one-fluid, real', color='black') axs[1].plot(z_1f, W1f.imag, linewidth=2, label=r'one-fluid, imag', color='m') axs[1].plot(z, W.real, linewidth=2, label=r'two-fluid, real', color='red', linestyle='dashed') axs[1].plot(z, W.imag, linewidth=2, label=r'two-fluid, imag', color='c', linestyle='dashed') axs[1].set_ylabel(r'$\delta\rho_g/\rho_{g}$') axs[1].ticklabel_format(axis='y', style='sci',scilimits=(-2,2)) axs[1].yaxis.set_major_formatter(FormatStrFormatter('%3.0e')) #lines1, labels1 = axs[1].get_legend_handles_labels() #axs[1].legend(lines1, labels1, loc='right', frameon=False, ncol=1) axs[2].plot(z_1f, np.abs(Ux), linewidth=2, label=r'one-fluid', color='black') axs[2].plot(z, np.abs(Udx), linewidth=2, label=r'dust', color='red', linestyle='dashed') axs[2].plot(z, np.abs(Ugx), linewidth=2, label=r'gas', color='lime', linestyle='dotted') #axs[2].plot(z_1f, Ux_norm.imag, linewidth=2, color='black') #axs[2].plot(z, Ugx_norm.imag, linewidth=2, color='red', linestyle='dashed') #axs[2].plot(z, Udx_norm.imag, linewidth=2, color='blue', linestyle='dotted') axs[2].set_ylabel(r'$|\delta v_{x}|$') lines1, labels1 = axs[2].get_legend_handles_labels() axs[2].legend(lines1, labels1, loc='right', frameon=False, ncol=1, labelspacing=0.3, handletextpad=0.1)
axes.set_ylim(0, 35) axes2.set_ylim(bottom=0) axes2.set_ylabel(r"$m_{\rm c}$", labelpad = 40, rotation = 270) ############################################# axes.legend(loc = 2, fontsize = 14, frameon = False, numpoints=1, markerscale=1.0, handletextpad=0.5) axes2.legend(loc = 1, fontsize = 14, frameon = False, numpoints=1, markerscale=1.0, handletextpad=0.5) # ## Set ticks space and minor ticks space ############ # #####################################################. xtics = 0.2 # space between two ticks mxtics = xtics / 2. # space between two minor ticks majorFormatter = FormatStrFormatter('%g') # put the format of the number of ticks axes.xaxis.set_major_locator(MultipleLocator(xtics)) axes.xaxis.set_major_formatter(majorFormatter) axes.xaxis.set_minor_locator(MultipleLocator(mxtics)) ###################################################### plt.show() fig.savefig(figures_path, bbox_inches = "tight") # #################################################### # ## Plot Parameters #################################
if 0: ax, g = plot_data(xh, yh, zh, fig, 5, colorflag=True) ax.text(.98, .20, '0 KV', fontsize=14, horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, color='white') ax.set_ylabel(ylabel) ax.set_xlabel(xlabel) ax.xaxis.set_minor_formatter(NullFormatter()) ax.set_ylim(ylim) ax.set_xlim(xlim) fmt = FormatStrFormatter('%0.3g') # or whatever ax.xaxis.set_major_formatter(fmt) ax.xaxis.set_major_locator(MaxNLocator(5)) if 0: ax, g = plot_data(xi, yi, zi, fig, 6, colorflag=True) ax.text(.98, .20, '-1.3 KV', fontsize=14, horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, color='white') ax.set_xlabel(xlabel) ax.yaxis.set_major_formatter(NullFormatter()) ax.xaxis.set_minor_formatter(NullFormatter())
plotfirst = i break for j in xrange(0, time_len): if cleantime[j] == plottime2: plotlast = j break fig,ax = plt.subplots() plt.xlim(40,430) plt.xlabel('Diameter (nm)') plt.ylabel('Concentration') ax.set_xscale('log') plt.tick_params(axis='x', which='both', length = 5) ax.xaxis.set_minor_formatter(FormatStrFormatter("%d")) ax.xaxis.set_major_formatter(FormatStrFormatter("%d")) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(9) for tick in ax.xaxis.get_minor_ticks(): tick.label.set_fontsize(9) plt.ticklabel_format(style='sci', axis = 'y', scilimits = (0,4)) imgs = [] for i in xrange(plotfirst,plotlast): img, = plt.plot(size_list[0], part_sizes[i,:], 'o', color = 'b') title = plt.text(250, 2.5E6, cleantime[i], fontsize = 20) imgs.append([img, title]) ani = animation.ArtistAnimation(fig, imgs, interval = 300, blit = True, repeat_delay = 2000) plt.show()
def plot_hrrr_dayfromtxt(matrix, final_unit, numdates=None, date=None, loc=None, ps=HRRR_PS, hour=0, scaling=1, figsize=[15, 8], log=True, invert=True, ylabel='Pressure Level in hPa'): if numdates != None: datetimes = matplotlib.dates.num2date(numdates) timeshift = datetime.timedelta(hours=hour) hrrr_hours = [(c + timeshift).hour for c in datetimes] hrrr_hours.append(hrrr_hours[-1] + 1) times = np.array(hrrr_hours) else: times = np.array(range(matrix.shape[0] + 1)) from matplotlib.ticker import MultipleLocator, FormatStrFormatter if type(matrix) == list: values = np.array(matrix) else: values = matrix if date != None and loc != None: dateset = [ date - datetime.timedelta(days=1), date, date + datetime.timedelta(days=1) ] u = [] v = [] for i in dateset: f = get_sun(i, loc=loc, no_dst=True) u.append((f[1][0] - date).total_seconds() / (60 * 60)) v.append((f[1][1] - date).total_seconds() / (60 * 60)) plt.figure(figsize=figsize) ax = plt.gca() if log: ax.set_yscale('log') # x axis xmajorLocator = MultipleLocator(1) ax.xaxis.set_major_locator(xmajorLocator) xmajorFormatter = FormatStrFormatter('%d') ax.xaxis.set_major_formatter(xmajorFormatter) # y axis ymajorLocator = MultipleLocator(10**(int(np.log10(max(ps))) - 1)) ax.yaxis.set_major_locator(ymajorLocator) ymajorFormatter = FormatStrFormatter('%d') ax.yaxis.set_major_formatter(ymajorFormatter) pc = plt.pcolor(times, ps, np.transpose(values)) ax.set_ylim([min(ps), max(ps)]) ax.set_xlim([0, 24]) if invert: ax.invert_yaxis() plt.colorbar(mappable=pc, label=final_unit) plt.xlabel('Time in hrs') plt.ylabel(ylabel) yval = (max(ps) + min(ps)) / 2 if date != None and loc != None: for i in range(len(u)): if u[i] != None and u[i] < max(times) and u[i] > min(times): ax.text(u[i], yval, 'Sunrise') ax.axvline(u[i], linestyle='--', color='k') if v[i] != None and v[i] < max(times) and v[i] > min(times): ax.axvline(v[i], linestyle='--', color='k') ax.text(v[i], yval, 'Sunset') plt.show() return # else: (not contour) # if hinp == None: # values = np.array(data[:]) # values = values.max(axis=1) # else: # pind = HRRR_PS.index(hinp) # values = np.array(data[:,pind]) # # u = [] # v = [] # dateset = np.unique(np.array([i.date() for i in dates])).tolist() # dateset = [datetime.datetime(i.year,i.month,i.day) for i in dateset] # # dateset.insert(0,dateset[0]-datetime.timedelta(days = 1)) # dateset.append(dateset[-1]+datetime.timedelta(days = 1)) # # # for i in dateset: # f = get_sun(i,loc = loc,no_dst = True) # u.append((f[1][0]-datetimestart).total_seconds()/(60*60)) # v.append((f[1][1]-datetimestart).total_seconds()/(60*60)) # # # # plt.figure(figsize =figsize) # ax = plt.gca() # # plt.plot(times,values) # ax.set_xlim([min(times),max(times)]) # plt.xlabel('Time hrs') # # plt.ylabel(parameter+' '+final_unit) # # # yval = (max(values)+min(values))/2 # # for i in range(len(u)): # if u[i] != None and u[i]<max(times) and u[i]>min(times): # ax.text(u[i],yval, 'Sunrise') # ax.axvline(u[i], linestyle = '--', color='k') # if v[i] != None and v[i]<max(times) and v[i]>min(times): # ax.axvline(v[i], linestyle = '--', color='k') # ax.text(v[i],yval,'Sunset') # # os.chdir(wkdir) # # return
annotations.add_artist(mb) # set up stream plots for each seismometer for i in range(waveform.count()): if i == 0: # bottom axis first, including tick labels axes.append(fig.add_axes([margin, margin + ((theight + spacing) * i), twidth, theight])) else: # tick labels switched off for subsequent axes axes.append(fig.add_axes([margin, margin + ((theight + spacing) * i), twidth, theight], sharex=axes[0])) plt.setp(axes[i].get_xticklabels(), visible=False) # Create a list of elapsed times for the stream file (what does this do in the case of data gaps? time = np.arange(0, waveform[i].count()/100, 0.01) # set up plot parameters axes[i].set_xlim([PSTART,PEND]) if not SAMESCALE: ylim = abs(waveform[i].max()) * 1.1 axes[i].set_ylim([-1*ylim,ylim]) axes[i].yaxis.set_major_formatter(FormatStrFormatter('%.1e')) axes[i].tick_params(axis="both", direction="in", which="both", right=True, top=True) # plot the data axes[i].plot(time, waveform[i], linewidth=0.75) textstr = loaded[i][0] + " " + str(round(loaded[i][3], 2)) + "° " + loaded[i][4] plt.text(0.5, 0.96, textstr, transform=axes[i].transAxes, horizontalalignment='center', verticalalignment='top') # Add the arrival times and vertical lines plotted_arrivals = [] for j, phase in enumerate(PHASES): color = COLORS[PHASES.index(phase) % len(COLORS)] arrivals = model.get_travel_times(source_depth_in_km=EQZ, distance_in_degree=loaded[i][3], phase_list=[phase]) printed = False if arrivals: for k in range(len(arrivals)): instring = str(arrivals[k]) phaseline = instring.split(" ")
def main(plotroutine=None, excel_filename=None, var_dict=None, figurename=None, titlestr=None, flag=None, timebegin=None, timeend=None, timemarker=None, hour_interval=3, time_freq='D'): # define some methods register_matplotlib_converters() def set_visuals(ax, pl, spine_location): # set all kinds of visuals to correspond to the line color ax.yaxis.label.set_color(pl.get_color()) ax.tick_params(axis='y', colors=pl.get_color()) ax.spines[spine_location].set_color(pl.get_color()) ax.spines[spine_location].set_linewidth(2) return None def set_time_axis(ax, time, withDate=True, hour_interval=2): # set labelling, lim and some visuals for the time/x-axis ax.set_xlabel('time UTC') hours = mdates.HourLocator(interval=hour_interval) if withDate: ax.set_xlim([time[0], time[-1]]) ax.spines['top'].set_linewidth(2) ax.spines['bottom'].set_linewidth(2) h_fmt = mdates.DateFormatter('%d.%m.%y - %H:%M') fig.autofmt_xdate(rotation=45) else: dt2 = (time[1]-time[0])/2 ax.set_xlim([time[0]-dt2, time[-1]+dt2]) h_fmt = mdates.DateFormatter('%H') ax.xaxis.set_major_locator(hours) ax.xaxis.set_major_formatter(h_fmt) return None def set_time_axis_compare(ax, time, hour_interval=2): ax.set_xlabel('time UTC') hours = mdates.HourLocator(interval=hour_interval) ax.set_xlim([time[0], time[-1]]) h_fmt = mdates.DateFormatter('%d.%m.%y - %H:%M') fig.autofmt_xdate(rotation=45) ax.xaxis.set_major_locator(hours) ax.xaxis.set_major_formatter(h_fmt) return None # create figure directory fig_dir = 'figures' try: os.makedirs(fig_dir) except OSError as e: if e.errno != errno.EEXIST: raise # timeseries from hobo csv file if plotroutine == 'hobo_single': df = pd.read_excel(os.path.join('data', 'excel', excel_filename), skiprows=1) # fix column header from hobo file output (remove serial num) for i, x in enumerate(df.columns): newstr = x.split(' ') df.columns.values[i] = " ".join(newstr[:2]).strip(',') # get important data # include time meta for old and new versions if isinstance(df['Datum Zeit'].values[0], str): time_vec = df['Datum Zeit'].values elif isinstance(df['Datum Zeit'].values[0], np.datetime64): time = pd.to_datetime(df['Datum Zeit'].values) new_time_vec = [] for i in range(len(time)): new_time = time[i].strftime('%d.%m.%Y %H:%M:%S') new_time_vec.append(new_time) time_vec = np.array(new_time_vec) # check if data from excel file uses a , or . as decimal if isinstance(df['Windgeschwindigkeit, m/s'].values[0], float): v_spd = np.array([v for v in df['Windgeschwindigkeit, m/s'].values], dtype=float) # m/s v_spd_boeen = np.array([vb for vb in df['Böengeschwindigkeit, m/s'].values], dtype=float) # m/s v_dir = np.array([vd for vd in df['Windrichtung, ø'].values], dtype=float) # deg T = np.array([t for t in df['Temp., °C'].values], dtype=float) # deg C RH = np.array([rh for rh in df['RH, %'].values], dtype=float) # % p = np.array([pp for pp in df['Druck, mbar'].values], dtype=float) # hPa try: sun_rad = np.array([l for l in df['Sonnenstrahlung, W/m²'].values], dtype=float) # W/m2 except: pass else: v_spd = np.array([float(v.replace(',', '.')) for v in df['Windgeschwindigkeit, m/s'].values], dtype=float) # m/s v_spd_boeen = np.array([float(vb.replace(',', '.')) for vb in df['Böengeschwindigkeit, m/s'].values], dtype=float) # m/s v_dir = np.array([float(vd.replace(',', '.')) for vd in df['Windrichtung, ø'].values], dtype=float) # deg T = np.array([float(t.replace(',', '.')) for t in df['Temp., °C'].values], dtype=float) # deg C RH = np.array([float(rh.replace(',', '.')) for rh in df['RH, %'].values], dtype=float) # % p = np.array([float(pp.replace(',', '.')) for pp in df['Druck, mbar'].values], dtype=float) # hPa try: sun_rad = np.array([float(l.replace(',', '.')) for l in df['Sonnenstrahlung, W/m²'].values], dtype=float) # W/m2 except: pass # read into dataframe from csv file if len(time_vec[0]) > 18: time = [datetime.strptime(tt, '%d.%m.%Y %H:%M:%S') for tt in time_vec] else: time = [datetime.strptime(tt, '%d.%m.%y %H:%M:%S') for tt in time_vec] # create figure fig, ax = plt.subplots(figsize=(12, 6)) plt.subplots_adjust(left=0.20, right=0.8) axr1 = ax.twinx() # iterate through dictionary and plot specified parameters pls = [] # used for the legend for index, item in enumerate(var_dict.items()): if item[1]: if item[0] == 'wind_spd': y = v_spd # plotting p1, = ax.plot(time, y, 'cyan', label='wind speed') ax.set_ylabel('wind speed [m/s]') set_visuals(ax, p1, 'left') pls.append(p1) elif item[0] == 'wind_gusts': y = v_spd_boeen # plotting p2, = ax.plot(time, y, 'magenta', label='wind gusts') ax.set_ylabel('wind speed [m/s]') pls.append(p2) elif item[0] == 'wind_dir': y = v_dir # plotting p3, = axr1.plot(time, y, 'k*', label='wind direction') axr1.set_ylabel('wind direction [°]') axr1.set_ylim([0, 360]) axr1.set_yticks(np.arange(0,361,45)) axr1.set_yticklabels(['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N']) set_visuals(axr1, p3, 'right') pls.append(p3) elif item[0] == 'temp': y = T # plotting if axr1.lines: axr2 = ax.twinx() axr2.spines['right'].set_position(('axes', 1.1)) axr2.spines['right'].set_visible(True) p4, = axr2.plot(time, y, 'r', label='temperature') axr2.set_ylabel('temperature [°C]') set_visuals(axr2, p4, 'right') else: p4, = axr1.plot(time, y, 'r', label='temperature') axr1.set_ylabel('temperature [°C]') set_visuals(axr1, p4, 'right') pls.append(p4) elif item[0] == 'rel_hum': y = RH # plotting if axr1.lines: try: if axr2.lines: axr3 = ax.twinx() axr3.spines['right'].set_position(('axes', 1.2)) axr3.spines['right'].set_visible(True) p5, = axr3.plot(time, y, 'g', label='relative humidity') axr3.set_ylabel('relative humidity [%]') axr3.set_ylim([35, 100]) set_visuals(axr3, p5, 'right') except: axr2 = ax.twinx() axr2.spines['right'].set_position(('axes', 1.1)) axr2.spines['right'].set_visible(True) p5, = axr2.plot(time, y, 'g', label='relative humidity') axr2.set_ylabel('relative humidity [%]') axr2.set_ylim([35, 100]) set_visuals(axr2, p5, 'right') else: p5, = axr1.plot(time, y, 'g', label='relative humidity') axr1.set_ylabel('relative humidity [%]') axr1.set_ylim([35, 100]) set_visuals(axr1, p5, 'right') pls.append(p5) elif item[0] == 'pres': y = p # plotting if ax.lines: axl2 = ax.twinx() axl2.yaxis.tick_left() axl2.yaxis.set_label_position('left') axl2.set_ylabel('air pressure [hPa]') axl2.spines['left'].set_position(('axes', -0.1)) axl2.spines['left'].set_visible(True) p6, = axl2.plot(time, y, 'b', label='pressure') axl2.yaxis.set_major_formatter(FormatStrFormatter('%.1f')) set_visuals(axl2, p6, 'left') else: p6, = ax.plot(time, y, 'b', label='pressure') ax.set_ylabel('air pressure [hPa]') ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f')) set_visuals(ax, p6, 'left') pls.append(p6) elif item[0] == 'radiation': y = sun_rad # plotting if ax.lines: try: if axl2.lines: axl3 = ax.twinx() axl3.yaxis.tick_left() axl3.yaxis.set_label_position('left') axl3.set_ylabel('sun radiation [W/m2]') axl3.spines['left'].set_position(('axes', -0.22)) axl3.spines['left'].set_visible(True) p7, = axl3.plot(time, y, 'y', label='radiation') set_visuals(axl3, p7, 'left') except: axl2.yaxis.tick_left() axl2.yaxis.set_label_position('left') axl2.set_ylabel('sun radiation [W/m2]') axl2.spines['left'].set_position(('axes', -0.1)) axl2.spines['left'].set_visible(True) p7, = axl2.plot(time, y, 'y', label='radiation') set_visuals(axl2, p7, 'left') else: ax.set_ylabel('sun radiation [W/m2]') p7, = ax.plot(time, y, 'y', label='radiation') set_visuals(ax, p7, 'left') pls.append(p7) # set title if not titlestr: plt.title("".join(['HOBO time series from ', time[0].strftime('%d.%m.%Y - %H:%M'), ' to ', time[-1].strftime('%d.%m.%Y - %H:%M')])) else: plt.title(titlestr) # set time/x-axis and legend set_time_axis(ax, time, withDate=True) labels = [pl.get_label() for pl in pls] fig.legend(pls, labels, loc='upper center', ncol=len(labels)) ax.grid(True) # save figure print('Saving figure ...') plt.savefig(os.path.join(fig_dir, figurename)) if plotroutine == 'hobo_multi': # height correction for stations: dp = -g * rho * dz station_heights = {'Campingplatz': 771, 'Lanzenkreuz': 791, 'Seetal': 842, 'Stübming': 824, 'UnterDerLanzen': 733} metrs = [] for num, itm in enumerate(station_heights.items()): metrs.append(itm[1]) avg_height = np.mean(metrs) # read into dataframe from csv file id = [] dflist = [] dplist = [] for index, item in enumerate(excel_filename.items()): height_corr = station_heights[item[0]] - avg_height dp = -9.81*1.1*height_corr id.append(item[0]) df = pd.read_excel(os.path.join('data', 'excel', item[1]), skiprows=1) # fix column header from hobo file output (remove serial num) for i, x in enumerate(df.columns): newstr = x.split(' ') df.columns.values[i] = " ".join(newstr[:2]).strip(',') dflist.append(df) dplist.append(dp) def get_time_vec(df): # include time meta for old and new versions if isinstance(df['Datum Zeit'].values[0], str): time_vec = df['Datum Zeit'].values elif isinstance(df['Datum Zeit'].values[0], np.datetime64): time = pd.to_datetime(df['Datum Zeit'].values) new_time_vec = [] for i in range(len(time)): new_time = time[i].strftime('%d.%m.%Y %H:%M:%S') new_time_vec.append(new_time) time_vec = np.array(new_time_vec) if len(time_vec[0]) > 18: time = [datetime.strptime(tt, '%d.%m.%Y %H:%M:%S') for tt in time_vec] else: time = [datetime.strptime(tt, '%d.%m.%y %H:%M:%S') for tt in time_vec] return time # create figure # 1) wind gusts, wind speed, wind direction comparison for i, flags in enumerate(flag.items()): if flags[0] == 'wind_gusts': if flags[1]: fig, (ax, ax2, ax3) = plt.subplots(nrows=3, sharex=True, figsize=(13, 8)) switch = 1 else: fig, (ax, ax2) = plt.subplots(nrows=2, sharex=True, figsize=(12, 7)) switch = 0 pls = [] colrs = ['b', 'g', 'r', 'orange', 'magenta', 'cyan'] for ind, df in enumerate(dflist): colr = colrs[ind] lab = id[ind] time = get_time_vec(df) if isinstance(df['Windgeschwindigkeit, m/s'].values[0], float): v_spd = [v for v in df['Windgeschwindigkeit, m/s'].values] # m/s else: v_spd = [float(v.replace(',', '.')) for v in df['Windgeschwindigkeit, m/s'].values] # m/s y = v_spd p, = ax.plot(time, y, color=colr, label=lab) ax.set_ylabel('wind speed [m/s]') pls.append(p) if switch == 1: if isinstance(df['Böengeschwindigkeit, m/s'].values[0], float): v_spd_boeen = [vb for vb in df['Böengeschwindigkeit, m/s'].values] # m/s else: v_spd_boeen = [float(vb.replace(',', '.')) for vb in df['Böengeschwindigkeit, m/s'].values] # m/s y = v_spd_boeen ax3.plot(time, y, '--', color=colr) ax3.set_ylabel('wind gusts [m/s]') ax3.grid(True) if isinstance(df['Windrichtung, ø'].values[0], float): v_dir = [vd for vd in df['Windrichtung, ø'].values] # deg else: v_dir = [float(vd.replace(',', '.')) for vd in df['Windrichtung, ø'].values] # deg y = v_dir ax2.plot(time, y, '*', color=colr) ax2.set_ylabel('wind direction [°]') ax2.set_ylim([0, 360]) ax2.set_yticks(np.arange(0,361,45)) ax2.set_yticklabels(['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N']) # set title if not titlestr: ax.set_title("".join(['HOBO time series from ', time[0].strftime('%d.%m.%Y - %H:%M'), ' to ', time[-1].strftime('%d.%m.%Y - %H:%M')])) else: ax.set_title(titlestr) # set time/x-axis and legend set_time_axis_compare(ax, time) labels = [pl.get_label() for pl in pls] plt.xlabel('time [UTC]') fig.legend(pls, labels, loc='upper center', ncol=len(labels)) ax.grid(True) ax2.grid(True) # save figure print('Saving figure ...') if switch == 1: savename = 'wind_speed_direction_gusts.png' else: savename = 'wind_speed_direction.png' plt.savefig(os.path.join(fig_dir, "".join([figurename, savename]))) # create figure # 2) Temperature, RH, pressure for i, flags in enumerate(flag.items()): if flags[0] == 'pressure': if flags[1]: fig, (ax, ax2, ax3) = plt.subplots(nrows=3, sharex=True, figsize=(13, 8)) switch = 1 else: fig, (ax, ax2) = plt.subplots(nrows=2, sharex=True, figsize=(12, 7)) switch = 0 pls = [] colrs = ['b', 'g', 'r', 'orange', 'magenta', 'cyan'] for ind, df in enumerate(dflist): colr = colrs[ind] lab = id[ind] time = get_time_vec(df) if isinstance(df['Temp., °C'].values[0], float): T = [t for t in df['Temp., °C'].values] # deg C else: T = [float(t.replace(',', '.')) for t in df['Temp., °C'].values] # deg C y = T p, = ax.plot(time, y, color=colr, label=lab) ax.set_ylabel('temperature [°C]') pls.append(p) if isinstance(df['RH, %'].values[0], float): RH = [rh for rh in df['RH, %'].values] # % else: RH = [float(rh.replace(',', '.')) for rh in df['RH, %'].values] # % y = RH ax2.plot(time, y, '--', color=colr) ax2.set_ylabel('relative humidity [%]') ax2.set_ylim([35, 100]) if switch == 1: if isinstance(df['Druck, mbar'].values[0], float): p = [pp for pp in df['Druck, mbar'].values] # hPa else: p = [float(pp.replace(',', '.')) for pp in df['Druck, mbar'].values] # hPa y = p dp = dplist[ind] # station height, density and gravitational acceleration need to be verified # and calculated with higher precision before applying the correction succesfully #ax3.plot(time, y-dp/100, '-.', color=colr) ax3.plot(time, y, '-.', color=colr) ax3.set_ylabel('pressure [hPa]') ax3.grid(True) # set title if not titlestr: ax.set_title("".join(['HOBO time series from ', time[0].strftime('%d.%m.%Y - %H:%M'), ' to ', time[-1].strftime('%d.%m.%Y - %H:%M')])) else: ax.set_title(titlestr) # set time/x-axis and legend set_time_axis_compare(ax, time) labels = [pl.get_label() for pl in pls] fig.legend(pls, labels, loc='upper center', ncol=len(labels)) ax.grid(True) ax2.grid(True) plt.xlabel('time [UTC]') # save figure print('Saving figure ...') if switch == 1: savename = 'temp_rh_pressure.png' else: savename = 'temp_rh.png' plt.savefig(os.path.join(fig_dir, "".join([figurename, savename]))) elif plotroutine == 'hobo_precip': # read into dataframe from excel file df = pd.read_excel(os.path.join('data', 'excel', excel_filename), skiprows=1) # fix column header from hobo file output (remove serial num) for i, x in enumerate(df.columns): newstr = x.split(' ') df.columns.values[i] = " ".join(newstr[:2]).strip(',') # get important data # include time meta for old and new versions if isinstance(df['Datum Zeit'].values[0], str): time_vec = df['Datum Zeit'].values elif isinstance(df['Datum Zeit'].values[0], np.datetime64): time = pd.to_datetime(df['Datum Zeit'].values) new_time_vec = [] for i in range(len(time)): new_time = time[i].strftime('%d.%m.%Y %H:%M:%S') new_time_vec.append(new_time) time_vec = np.array(new_time_vec) if len(time_vec[0]) > 18: time = [datetime.strptime(tt, '%d.%m.%Y %H:%M:%S') for tt in time_vec] else: time = [datetime.strptime(tt, '%d.%m.%y %H:%M:%S') for tt in time_vec] # accumulated ticks precip_ticks = precip_ticks = df['Event, units'].values precip_num = [np.float(str(ti).split(',')[0].replace(' ', '')) for ti in precip_ticks] # diff and transform in precipitation mm precip_amount = np.diff(precip_num)*0.2 new_pd_ticks = pd.Series(data=precip_ticks, index=time) new_pd_series = pd.Series(data=precip_amount, index=time[:-1]) precip_hourly = new_pd_series.resample('H', label='right', closed='right').sum() precip_3hourly = new_pd_series.resample('3H', label='right', closed='right').sum() # create figure width_hourly = np.min(np.diff(mdates.date2num(precip_hourly.index))) width_3hourly = np.min(np.diff(mdates.date2num(precip_3hourly.index))) #ax.bar(x_values, y_values, width=width, ec="k") fig, (ax, ax2, ax3) = plt.subplots(nrows=3, figsize=(12, 9)) ax.grid(True) ax2.grid(True) ax3.grid(True) ax.plot(time, precip_num) ax.set_title('precipitation ticks') ax.set_ylabel('precipitation ticks [0.2 mm]') ax2.bar(precip_hourly.index, precip_hourly, width=-width_hourly*0.9, align='edge') ax2.set_title('hourly precipitation') ax2.set_ylabel('hourly precipitation [mm/h]') ax3.bar(precip_3hourly.index, precip_3hourly, width=-width_3hourly*0.9, align='edge') ax3.set_title('3-hourly precipitation') ax3.set_ylabel('3-hourly precipitation [mm/3h]') if timebegin is not None: time = pd.date_range(datetime.strptime(timebegin, '%Y%m%d%H'), end=datetime.strptime(timeend, '%Y%m%d%H'), freq=time_freq) #ax.set_xlim([time[0], time[1]]) set_time_axis_compare(ax, time, hour_interval=hour_interval) set_time_axis_compare(ax2, time, hour_interval=1) set_time_axis_compare(ax3, time, hour_interval=3) # set title if not titlestr: plt.suptitle('observed precipitation', fontsize=20) else: plt.suptitle(titlestr, fontsize=20) # save figure print('Saving figure ...') plt.savefig(os.path.join(fig_dir, "".join([figurename, 'precip.png']))) # synoptic observations elif plotroutine == 'syn_observation': # read into dataframe from csv file df = pd.read_excel(os.path.join('data', 'excel', excel_filename)) ## get important data # time timestr = df['UTC'].values timestr_iter = [str(tt1) for tt1 in timestr] time = [datetime.strptime(tt, '%H:%M:%S') for tt in timestr_iter] # assmann T_assmann = df['T_assmann'].values TF_assmann = df['Tf_assmann'].values TD_assmann = df['Td_assmann'].values RH_assmann = df['RH_assmann'].values # davis T_davis = df['T_davis'].values TD_davis = df['Td_davis'].values RH_davis = df['RH_davis'].values # dew-point mirror TD_mirror = df['Td_mirror'].values # kestrel T_kestrel = df['T_kestrel'].values TD_kestrel = df['Td_kestrel'].values RH_kestrel = df['RH_kestrel'].values p_kestrel = df['p_kestrel'].values # davis-station T_davisstation = df['T_davis-station'].values TD_davisstation = df['Td_davis-station'].values RH_davisstation = df['RH_davis-station'].values # humiport T_humiport = df['T_humiport'].values RH_humiport = df['RH_humiport'].values # vaisala p_vaisala = df['p_vaisala'].values visibility = df['visibility'].values clouds_high = df['clouds_high'].values clouds_medium = df['clouds_medium'].values clouds_low = df['clouds_low'].values cloudiness = df['cloudiness'].values cloud_base = df['cloud_base'].values cloudiness_low = df['cloudiness_low'].values # define colors Cassmann = 'r' Cdavis = 'b' Ckestrel = 'g' Cdavisstation = 'purple' Chumiport = 'orange' # define labels Lassmann = 'Assmann' Ldavis = 'Davis' Lkestrel = 'Kestrel' Ldavisstation = 'Davis-Station' Lhumiport = 'Humiport' # create figure fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True, figsize=(12, 8)) plt.subplots_adjust(right=0.85) axr1 = ax1.twinx() axr11 = ax1.twinx() axr2 = ax2.twinx() # plot temperature, dew-point temperature and relative humidity def plot_t_td_rh(axleft, axright, time, t, td, rh, label, color): p = axleft.plot(time, t, '-', label=label, color=color, linewidth=2) axleft.plot(time, td, '--', label=label, color=color, linewidth=2) axright.plot(time, rh, ':', label=label, color=color, linewidth=2) return p # plots p1 = plot_t_td_rh(ax1, axr1, time, T_assmann, TD_assmann, RH_assmann, label=Lassmann, color=Cassmann) p2 = plot_t_td_rh(ax1, axr1, time, T_davis, TD_davis, RH_davis, label=Ldavis, color=Cdavis) p3 = plot_t_td_rh(ax1, axr1, time, T_kestrel, TD_kestrel, RH_kestrel, label=Lkestrel, color=Ckestrel) p4 = plot_t_td_rh(ax1, axr1, time, T_davisstation, TD_davisstation, RH_davisstation, label=Ldavisstation, color=Cdavisstation) p5 = plot_t_td_rh(ax1, axr1, time, T_humiport, np.zeros(len(time))*np.nan, RH_humiport, label=Lhumiport, color=Chumiport) axr1.set_ylim([35, 100]) # set lim for relative humidity # set spine position axr11.spines['right'].set_position(('axes', 1.1)) axr11.spines['right'].set_visible(True) # plot pressure p6 = axr11.plot(time, p_vaisala, '-.', label='Vaisala - pressure', color='k', linewidth=2) axr11.yaxis.set_major_formatter(FormatStrFormatter('%.1f')) axr11.set_ylabel('pressure [hPa]') # set title and legend ax1.set_title(titlestr) pls = p1+p2+p3+p4+p5+p6 labels = [pl.get_label() for pl in pls] fig.legend(pls, labels, loc=[0.125, 0.483], ncol=len(labels), prop={'size': 8}) ax1.grid(True) ax1.set_ylabel('temperature [°C]') axr1.set_ylabel('relative humidity [%]') # plot synoptic observations # height (y) and time (x) axis z = np.arange(0, 8001, 10) set_time_axis(ax2, time, withDate=False, hour_interval=1) timeticks = ax2.get_xticks() # difference between ticks on x-axis; used for positioning and horizontal scaling dx = (timeticks[1] - timeticks[0])/2 # add a path patch for the cloud structure def create_cloud_patch(axis, x, dx, y, calpha, ctype, scaling_factor): x = x-dx/3. height_scaling = 150*0.3 + 150*0.7*scaling_factor/8. # used for scaling the patch vertically dx = dx*0.3 + dx*0.7*scaling_factor/8. Path = mpath.Path # points and type of line path path_data = [ (Path.MOVETO, [x, y]), (Path.LINETO, [x-dx, y]), (Path.CURVE4, [x-dx*2, y+height_scaling*2]), (Path.CURVE4, [x-dx*2, y+height_scaling*10]), (Path.CURVE4, [x-dx/1.3, y+height_scaling*7]), (Path.LINETO, [x-dx/1.3, y+height_scaling*7]), (Path.CURVE4, [x-dx*1.5, y+height_scaling*12]), (Path.CURVE4, [x-dx*0.2, y+height_scaling*17]), (Path.CURVE4, [x, y+height_scaling*10]), (Path.LINETO, [x, y+height_scaling*10]), (Path.CURVE4, [x+dx*0.2, y+height_scaling*17]), (Path.CURVE4, [x+dx*1.5, y+height_scaling*12]), (Path.CURVE4, [x+dx/1.3, y+height_scaling*7]), (Path.LINETO, [x+dx/1.3, y+height_scaling*7]), (Path.CURVE4, [x+dx*2, y+height_scaling*10]), (Path.CURVE4, [x+dx*2, y+height_scaling*2]), (Path.CURVE4, [x+dx, y]), (Path.LINETO, [x, y]), (Path.CLOSEPOLY, [0, 0])] codes, verts = zip(*path_data) path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, FaceColor=[1*calpha, 1*calpha, 1*calpha]) axis.add_patch(patch) # add text about the cloud type information (can be omitted) #ptred = axis.text(x+dx/3, y+1400, int(ctype), FontSize=15, Color='m') return None # plots text about the cloudiness def plot_cloudiness(axis, x, dx, y, cl, cl_low): if np.isnan(cl): cl_str = None else: cl_str = str(int(cl))+'/8' axis.text(x-dx/1.7, -z[-1]/4., cl_str, FontSize=15, Color='k') if np.isnan(cl_low): cl_low = None else: cl_low = str(int(cl_low)) if y > 500: axis.text(x-dx/3, y-500, cl_low, FontSize=15, Color='c') else: axis.text(x-dx/3, y, cl_low, FontSize=15, Color='c') return None # plot cloudiness text for i in range(len(timeticks)): if not (np.isnan(cloud_base[i]) or cloud_base[i]>4000): plot_cloudiness(ax2, timeticks[i], dx, cloud_base[i], cloudiness[i], cloudiness_low[i]) else: plot_cloudiness(ax2, timeticks[i], dx, -2000, cloudiness[i], np.nan) # create low clouds for i in range(len(clouds_low)): if not np.isnan(clouds_low[i]): create_cloud_patch(ax2, timeticks[i], dx, cloud_base[i], calpha=0.3, ctype=clouds_low[i], scaling_factor=cloudiness_low[i]) # create medium clouds for i in range(len(clouds_medium)): if not np.isnan(clouds_medium[i]): if np.isnan(cloudiness_low[i]): scaling_low = 0 else: scaling_low = cloudiness_low[i] create_cloud_patch(ax2, timeticks[i], dx, 4000, calpha=0.6, ctype=clouds_medium[i], scaling_factor=cloudiness[i]-scaling_low) # create high clouds for i in range(len(clouds_high)): if not np.isnan(clouds_high[i]): if np.isnan(cloudiness_low[i]): scaling_low = 0 else: scaling_low = cloudiness_low[i] create_cloud_patch(ax2, timeticks[i], dx, 6000, calpha=0.85, ctype=clouds_high[i], scaling_factor=cloudiness[i]-scaling_low) # create descriptive text #ax2.text(timeticks[5], z[-1]*1.02, 'cloud type', FontSize=8, color='m', backgroundcolor=[0.9, 0.9, 0.9]) ax2.text(timeticks[0]-dx/1.7, -z[-1]/6, 'cloudiness total', FontSize=10, color='k') ax2.text(timeticks[0]-dx*0.8, z[-1]*1.02, 'cloudiness low', FontSize=8, color='c', backgroundcolor=[0.9, 0.9, 0.9]) ax2.text(timeticks[0]-dx*0.8, z[-1]*1.15, 'T: drawn through; Td: dashed; RH: dotted', FontSize=8, color='k') #ax2.text(timeticks[0]+dx*0.9, z[-1]*1.02, 'visibility', FontSize=8, color='y', backgroundcolor=[0.9, 0.9, 0.9]) #ax2.add_patch(mpatches.Rectangle((timeticks[0]-dx, z[-1]*0.99), dx*13, 700, FaceColor=[0.9, 0.9, 0.9], EdgeColor='k')) # set lims, labels, time axis properties ax2.set_ylim([0, 8001]) axr2.bar(timeticks+dx/3, visibility, width=0.005, fill=False, hatch='/', EdgeColor='y', linewidth=1.2) axr2.set_ylabel('horizontal visibility [km]', color='y') axr2.tick_params(axis='y', colors='y') ax2.set_ylabel('height above ground [m]') ax2.set_xlabel('time UTC') set_time_axis(ax2, time, withDate=False, hour_interval=1) # save figure print('Saving figure ...') plt.savefig(os.path.join(fig_dir, "".join([figurename, '.png']))) ## barplot height of cloud base # approximation: spread * 125 cb_assmann = (T_assmann - TD_assmann) * 125 cb_davis = (T_davis - TD_davis) * 125 cb_kestrel = (T_kestrel - TD_kestrel) * 125 cb_davisstation = (T_davisstation - TD_davisstation) * 125 # plot bars fig, ax = plt.subplots(figsize=(12, 8)) ax.bar(timeticks-dx/6*4, cloud_base, width=dx/3, color='y', align='center', label='observation') ax.bar(timeticks-dx/6*2, cb_assmann, width=dx/3, color='r', align='center', label='assmann') ax.bar(timeticks, cb_davis, width=dx/3, color='b', align='center', label='davis') ax.bar(timeticks+dx/6*2, cb_kestrel, width=dx/3, color='g', align='center', label='kestrel') ax.bar(timeticks+dx/6*4, cb_davisstation, width=dx/3, color='purple', align='center', label='davis-station') set_time_axis(ax, time, withDate=False, hour_interval=1) plt.title('Cloud base height') ax.set_ylabel('height [m]') plt.legend(loc=2) # save figure print('Saving figure ...') plt.savefig(os.path.join(fig_dir, "".join([figurename, '_cloudbase.png']))) # synoptic forecast elif plotroutine == 'syn_forecast': df = pd.read_excel(os.path.join('data', 'excel', excel_filename)) ## get important data # time timestr = df['UTC'].values timestr_iter = [str(tt1) for tt1 in timestr] time = [datetime.strptime(tt.split('.')[0], '%Y-%m-%dT%H:%M:%S') for tt in timestr_iter] # T_fcst = df['T_forecast [°C]'].values # Td_fcst = df['Td_forecast [°C]'].values # vs_fcst = df['wind_speed_forecast [m/s]'].values # vd_fcst = df['wind_direction_forecast [m/s]'].values T_fcst = df['T_forecast'].values Td_fcst = df['Td_forecast'].values vs_fcst = df['wind_speed_forecast'].values vd_fcst = df['wind_direction_forecast'].values fig, ax = plt.subplots(nrows=4, ncols=2, sharex='col', figsize=(12, 15)) ax[0,0].plot(time, T_fcst, 'b') ax[0,0].set_ylabel('temperature [°C]') ax[0,0].set_title('temperature forecast') ax[1,0].plot(time, Td_fcst, 'b-') ax[1,0].set_ylabel('dew-point temperature [°C]') ax[1,0].set_title('dew-point temperature forecast') ax[2,0].plot(time, vs_fcst, 'b') ax[2,0].set_ylabel('wind speed [m/s]') ax[2,0].set_title('wind speed forecast') ax[3,0].plot(time, vd_fcst, 'b*') ax[3,0].set_ylabel('wind direction') ax[3,0].set_title('wind direction forecast') ax[3,0].set_ylim([0, 360]) ax[3,0].set_yticks(np.arange(0,361,45)) ax[3,0].set_yticklabels(['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N']) if not titlestr: plt.suptitle('synoptic forecast and validation example\n forecast: blue - validation: red', fontsize=20) else: plt.suptitle("".join([titlestr, '\n forecast: blue - validation: red']), fontsize=20) cl_fcst = df['cloudiness_forecast'].values # clb_fcst = df['cloud_base_forecast [m]'].values # ra_fcst = df['rain_amount_forecast [mm/h]'].values # rp_fcst = df['rain_probability_forecast [%]'].values # cl_fcst = df['cloudiness_forecast'].values clb_fcst = pd.to_numeric(df['cloud_base_forecast'].values) ra_fcst = df['rain_amount_forecast'].values rp_fcst = df['rain_probability_forecast'].values #fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=4, sharex=True, figsize=(12, 15)) ax[0,1].plot(time, cl_fcst, 'b') ax[0,1].set_ylabel('cloudiness') ax[0,1].set_title('cloudiness forecast') ax[0,1].set_ylim([-0.3, 8.3]) ax[1,1].plot(time, clb_fcst, 'b') ax[1,1].set_ylabel('cloud base [m]') ax[1,1].set_title('cloud base forecast') ax[2,1].plot(time, ra_fcst, 'b') ax[2,1].set_ylabel('amount of rain [mm/h]') ax[2,1].set_title('rain amount forecast') ax[3,1].plot(time, rp_fcst, 'b') ax[3,1].set_ylabel('probability of rain') ax[3,1].set_title('rain probability forecast') ax[3,1].set_ylim([0, 100]) for axit in ax.ravel(): axit.grid(True) # validation # T_vali = df['T_validation [°C]'].values # Td_vali = df['Td_validation [°C]'].values # vs_vali = df['wind_speed_validation [m/s]'].values # vd_vali = df['wind_direction_validation [m/s]'].values # cl_vali = df['cloudiness_validation'].values # clb_vali = df['cloud_base_validation [m]'].values # ra_vali = df['rain_amount_validation [mm/h]'].values # rp_vali = df['rain_probability_validation'].values T_vali = df['T_validation'].values Td_vali = df['Td_validation'].values vs_vali = df['wind_speed_validation'].values vd_vali = df['wind_direction_validation'].values cl_vali = df['cloudiness_validation'].values clb_vali = df['cloud_base_validation'].values ra_vali = df['rain_amount_validation'].values rp_vali = df['rain_probability_validation'].values ax[0,0].plot(time, T_vali, 'r') ax[1,0].plot(time, Td_vali, 'r-') ax[2,0].plot(time, vs_vali, 'r') ax[3,0].plot(time, vd_vali, 'r*') ax[0,1].plot(time, cl_vali, 'r') ax[1,1].plot(time, clb_vali, 'r') ax[2,1].plot(time, ra_vali, 'r') ax[3,1].plot(time, rp_vali, 'r') if timebegin is not None: time = pd.date_range(datetime.strptime(timebegin, '%Y%m%d%H'), end=datetime.strptime(timeend, '%Y%m%d%H'), freq='H') if timemarker is not None: timemark = datetime.strptime(timemarker, '%Y%m%d%H') for axit in ax.reshape(-1): axit.axvline(x=timemark, color='k', linestyle='--') set_time_axis_compare(ax[3,0], time, hour_interval=3) set_time_axis_compare(ax[3,1], time, hour_interval=3) print('Saving figure ...') plt.savefig(os.path.join(fig_dir, "".join([figurename, '_new.png']))) return None
def plot_results(self): """ Plot results generates a plot with the variables typically outputted by Maxim's code :return: nothing """ # Check the time array is not, if so then raise error, otherwise if len(self.results["run_values"]["time"]) != 0: # Extract the concerning results time = self.results["run_values"]["time"] thrust = self.results["run_values"]["thrust"] isp = self.results["run_values"]["isp"] radius = self.results["run_values"]["radius"] v_reg = self.results["run_values"]["regression_rate"] of_ratio = self.results["run_values"]["of"] Go = self.results["run_values"]["Go"] chamber_sound_speed = self.results["run_values"]["chamber_sound_speed"] else: raise ValueError("No values found for time, check results before plotting. \n") # Set the font dictionaries (for plot title and axis titles) title_font = {'size': '20', 'color': 'black', 'weight': 'normal', 'verticalalignment': 'bottom'} # Bottom vertical alignment for more space axis_font = {'size': '16'} # Generate the plots fig = plt.figure(facecolor='w', figsize=(30, 30)) fig.suptitle('Combustion Module results', **title_font) axs = [plt.subplot2grid((4, 2), (0, 0), rowspan=1, colspan=1), plt.subplot2grid((4, 2), (1, 0), rowspan=1, colspan=1), plt.subplot2grid((4, 2), (2, 0), rowspan=1, colspan=1), plt.subplot2grid((4, 2), (3, 0), rowspan=1, colspan=1), plt.subplot2grid((4, 2), (0, 1), rowspan=2, colspan=1), plt.subplot2grid((4, 2), (2, 1), rowspan=1, colspan=1), plt.subplot2grid((4, 2), (3, 1), rowspan=1, colspan=1)] # Set the tick labels font for ax in axs: for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontname('Arial') label.set_fontsize(14) # Thrust-plot axs[0].plot(time, thrust, label='Thrust', color='blue', linewidth=2.0) axs[0].set_title('') axs[0].set_ylabel('Thrust (N)', **axis_font) axs[0].grid(b=True, axis='both') axs[0].set_xlim(left=time[0]) axs[0].set_ylim(bottom=0, top=max(thrust)*1.5) # R-plot axs[1].plot(time, radius, linestyle='--', label='Radius', color='red') axs[1].set_title('') axs[1].set_ylabel('R (m)', **axis_font) axs[1].yaxis.set_major_formatter(FormatStrFormatter('%.2E')) axs[1].grid(b=True, axis='both') axs[1].set_xlim(left=time[0]) # Isp-plot axs[2].plot(time, isp, label='Isp', color='r', linewidth=2.0) axs[2].set_title('') axs[2].set_ylabel('Isp (s)', **axis_font) axs[2].grid(b=True, axis='both') axs[2].set_xlim(left=time[0]) axs[2].set_ylim(bottom=0, top=max(isp)*1.5) # of_ratio-plot axs[3].plot(time, of_ratio, linestyle='--', color='green', label='O/F ratio', linewidth=2.0) axs[3].set_title('') axs[3].set_xlabel('Time (s)', **axis_font) axs[3].set_ylabel('O/F ratio', **axis_font) axs[3].grid(b=True, axis='both') axs[3].set_xlim(left=time[0]) # Regression rate plot axs[4].loglog(Go, v_reg, color='black', label='Regression Rate', linewidth=2.0) axs[4].set_title('') axs[4].set_ylabel('Regression Rate', **axis_font) axs[4].grid(True, which='both', ls='-') axs[4].set_ylim(bottom=1e-5, top=1e-2) axs[4].set_xlim(left=nanmin(Go), right=nanmax(Go)) # Go-plot axs[5].plot(Go, time, linestyle='--', label='Go', color='red') axs[5].set_title('') axs[5].set_ylabel('Time (s)', **axis_font) axs[5].set_xlabel('Go [kg/m^2/sec]', **axis_font) axs[5].grid(True, which='both', ls='-') axs[5].set_xlim(left=nanmin(Go), right=nanmax(Go)) # Sonic Speed-plot axs[6].plot(time, chamber_sound_speed, ls='-', label='Sound Speed', color='black') axs[6].set_title('') axs[6].set_ylabel('Chamber c (m/s^2)', **axis_font) axs[6].set_xlabel('time (secs)', **axis_font) axs[6].grid(True, which='both', ls='-') axs[6].set_ylim(bottom=nanmin(chamber_sound_speed), top=nanmax(chamber_sound_speed))
def plot_2d_partial_dependence(oovr, X, col, col_names=None, grid_resolution=100, grid_range=(.05, 0.95), n_jobs=-1, n_samples=1000, progressbar=True): ''' Wrapper function for calling the plot_partial_dependence function from skater, which estimates the partial dependence of a column based on a random sample of 1000 data points. To calculate partial dependencies the following procedure is executed: 1. Pick a range of values (decided by the grid_resolution and grid_range parameters) to calculate partial dependency for. 2. Loop over the values, one at a time, repeating steps 3-5 each time. 3. Replace the entire column corresponding to the variable of interest with the current value that is being cycled over. 4. Use the model to predict the probabilities. 5. The (value, average_probability) becomes an (x, y) pair of the partial dependence plot. Parameters ---------- oovr: OrderedOVRClassifier Trained OrderedOVRClassifier model. X: array-like, shape = [n_samples, n_features] Input data used for training or evaluating the fitted model. col: str Label for the feature to compute partial dependence for. col_names: list, optional Names to call features. grid_resolution: int, optional, default: 100 How many unique values to include in the grid. If the percentile range is 5% to 95%, then that range will be cut into <grid_resolution> equally size bins. grid_range: (float, float) tuple, optional, default: (.05, 0.95) The percentile extrama to consider. 2 element tuple, increasing, bounded between 0 and 1. n_jobs: int, optional, default: -1 The number of CPUs to use to compute the partial dependence. -1 means 'all CPUs' (default). n_samples: int, optional, default: 1000 How many samples to use when computing partial dependence. progressbar: bool, optional, default: True Whether to display progress. This affects which function we use to multipool the function execution, where including the progress bar results in 10-20% slowdowns. ''' if not skater_loaded: raise RuntimeError("Skater is required but not installed. Please " "install skater with 'pip install skater' to use " "this function.") target_names = ['predicted_' + str(x) for x in oovr._le.classes_] interpreter = Interpretation(X, feature_names=col_names) interpreter.logger.handlers = [logging.StreamHandler()] pdep = PartialDependence(interpreter) pyint_model = InMemoryModel(oovr.predict_proba, target_names=target_names, examples=X) fig = pdep.plot_partial_dependence([col], pyint_model, with_variance=False, figsize=(6, 4), grid_resolution=grid_resolution, grid_range=grid_range, n_jobs=n_jobs, n_samples=n_samples, progressbar=progressbar) for i, f in enumerate(fig[0]): if f.__module__ == 'matplotlib.axes._subplots': f.yaxis.set_major_formatter(FormatStrFormatter('%.3f')) f.set_title('Partial Dependence Plot') plt.show()
def plot_cartopy(lons, lats, size, color, labels=None, projection='global', resolution='110m', continent_fill_color='0.8', water_fill_color='1.0', colormap=None, colorbar=None, marker="o", title=None, colorbar_ticklabel_format=None, show=True, proj_kwargs=None, **kwargs): # @UnusedVariable """ Creates a Cartopy plot with a data point scatter plot. :type lons: list/tuple of floats :param lons: Longitudes of the data points. :type lats: list/tuple of floats :param lats: Latitudes of the data points. :type size: float or list/tuple of floats :param size: Size of the individual points in the scatter plot. :type color: list/tuple of floats (or objects that can be converted to floats, like e.g. :class:`~obspy.core.utcdatetime.UTCDateTime`) :param color: Color information of the individual data points to be used in the specified color map (e.g. origin depths, origin times). :type labels: list/tuple of str :param labels: Annotations for the individual data points. :type projection: str, optional :param projection: The map projection. Currently supported are: * ``"global"`` (Will plot the whole world using :class:`~cartopy.crs.Mollweide`.) * ``"ortho"`` (Will center around the mean lat/long using :class:`~cartopy.crs.Orthographic`.) * ``"local"`` (Will plot around local events using :class:`~cartopy.crs.AlbersEqualArea`.) * Any other Cartopy :class:`~cartopy.crs.Projection`. An instance of this class will be created using the supplied ``proj_kwargs``. Defaults to "global" :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be passed directly to the Cartopy module. Possible values are: * ``"110m"`` * ``"50m"`` * ``"10m"`` Defaults to ``"110m"``. For compatibility, you may also specify any of the Basemap resolutions defined in :func:`plot_basemap`. :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type colormap: str, any matplotlib colormap, optional :param colormap: The colormap for color-coding the events as provided in `color` kwarg. The event with the smallest `color` property will have the color of one end of the colormap and the event with the highest `color` property the color of the other end with all other events in between. Defaults to None which will use the default matplotlib colormap. :type colorbar: bool, optional :param colorbar: When left `None`, a colorbar is plotted if more than one object is plotted. Using `True`/`False` the colorbar can be forced on/off. :type title: str :param title: Title above plot. :type colorbar_ticklabel_format: str or function or subclass of :class:`matplotlib.ticker.Formatter` :param colorbar_ticklabel_format: Format string or Formatter used to format colorbar tick labels. :type show: bool :param show: Whether to show the figure after plotting or not. Can be used to do further customization of the plot before showing it. :type proj_kwargs: dict :param proj_kwargs: Keyword arguments to pass to the Cartopy :class:`~cartopy.ccrs.Projection`. In this dictionary, you may specify ``central_longitude='auto'`` or ``central_latitude='auto'`` to have this function calculate the latitude or longitude as it would for other projections. Some arguments may be ignored if you choose one of the built-in ``projection`` choices. """ import matplotlib.pyplot as plt if isinstance(color[0], (datetime.datetime, UTCDateTime)): datetimeplot = True color = [date2num(getattr(t, 'datetime', t)) for t in color] else: datetimeplot = False fig = plt.figure() # The colorbar should only be plotted if more then one event is # present. if colorbar is not None: show_colorbar = colorbar else: if len(lons) > 1 and hasattr(color, "__len__") and \ not isinstance(color, (str, native_str)): show_colorbar = True else: show_colorbar = False if projection == "local": ax_x0, ax_width = 0.10, 0.80 elif projection == "global": ax_x0, ax_width = 0.01, 0.98 else: ax_x0, ax_width = 0.05, 0.90 proj_kwargs = proj_kwargs or {} if projection == 'global': proj_kwargs['central_longitude'] = np.mean(lons) proj = ccrs.Mollweide(**proj_kwargs) elif projection == 'ortho': proj_kwargs['central_latitude'] = np.mean(lats) proj_kwargs['central_longitude'] = mean_longitude(lons) proj = ccrs.Orthographic(**proj_kwargs) elif projection == 'local': if min(lons) < -150 and max(lons) > 150: max_lons = max(np.array(lons) % 360) min_lons = min(np.array(lons) % 360) else: max_lons = max(lons) min_lons = min(lons) lat_0 = max(lats) / 2. + min(lats) / 2. lon_0 = max_lons / 2. + min_lons / 2. if lon_0 > 180: lon_0 -= 360 deg2m_lat = 2 * np.pi * 6371 * 1000 / 360 deg2m_lon = deg2m_lat * np.cos(lat_0 / 180 * np.pi) if len(lats) > 1: height = (max(lats) - min(lats)) * deg2m_lat width = (max_lons - min_lons) * deg2m_lon margin = 0.2 * (width + height) height += margin width += margin else: height = 2.0 * deg2m_lat width = 5.0 * deg2m_lon # Do intelligent aspect calculation for local projection # adjust to figure dimensions w, h = fig.get_size_inches() aspect = w / h if show_colorbar: aspect *= 1.2 if width / height < aspect: width = height * aspect else: height = width / aspect proj_kwargs['central_latitude'] = lat_0 proj_kwargs['central_longitude'] = lon_0 proj = ccrs.AlbersEqualArea(**proj_kwargs) # User-supplied projection. elif isinstance(projection, type): if 'central_longitude' in proj_kwargs: if proj_kwargs['central_longitude'] == 'auto': proj_kwargs['central_longitude'] = mean_longitude(lons) if 'central_latitude' in proj_kwargs: if proj_kwargs['central_latitude'] == 'auto': proj_kwargs['central_latitude'] = np.mean(lats) if 'pole_longitude' in proj_kwargs: if proj_kwargs['pole_longitude'] == 'auto': proj_kwargs['pole_longitude'] = np.mean(lons) if 'pole_latitude' in proj_kwargs: if proj_kwargs['pole_latitude'] == 'auto': proj_kwargs['pole_latitude'] = np.mean(lats) proj = projection(**proj_kwargs) else: msg = "Projection '%s' not supported." % projection raise ValueError(msg) if show_colorbar: map_ax = fig.add_axes([ax_x0, 0.13, ax_width, 0.77], projection=proj) cm_ax = fig.add_axes([ax_x0, 0.05, ax_width, 0.05]) plt.sca(map_ax) else: ax_y0, ax_height = 0.05, 0.85 if projection == "local": ax_y0 += 0.05 ax_height -= 0.05 map_ax = fig.add_axes([ax_x0, ax_y0, ax_width, ax_height], projection=proj) if projection == 'local': x0, y0 = proj.transform_point(lon_0, lat_0, proj.as_geodetic()) map_ax.set_xlim(x0 - width / 2, x0 + width / 2) map_ax.set_ylim(y0 - height / 2, y0 + height / 2) else: map_ax.set_global() # Pick features at specified resolution. resolution = _CARTOPY_RESOLUTIONS[resolution] try: borders, land, ocean = _CARTOPY_FEATURES[resolution] except KeyError: borders = cfeature.NaturalEarthFeature(cfeature.BORDERS.category, cfeature.BORDERS.name, resolution, edgecolor='none', facecolor='none') land = cfeature.NaturalEarthFeature(cfeature.LAND.category, cfeature.LAND.name, resolution, edgecolor='face', facecolor='none') ocean = cfeature.NaturalEarthFeature(cfeature.OCEAN.category, cfeature.OCEAN.name, resolution, edgecolor='face', facecolor='none') _CARTOPY_FEATURES[resolution] = (borders, land, ocean) # Draw coast lines, country boundaries, fill continents. if MATPLOTLIB_VERSION >= [2, 0, 0]: map_ax.set_facecolor(water_fill_color) else: map_ax.set_axis_bgcolor(water_fill_color) map_ax.add_feature(ocean, facecolor=water_fill_color) map_ax.add_feature(land, facecolor=continent_fill_color) map_ax.add_feature(borders, edgecolor='0.75') map_ax.coastlines(resolution=resolution, color='0.4') # Draw grid lines - TODO: draw_labels=True doesn't work yet. if projection == 'local': map_ax.gridlines() else: # Draw lat/lon grid lines every 30 degrees. map_ax.gridlines(xlocs=range(-180, 181, 30), ylocs=range(-90, 91, 30)) # Plot labels if labels and len(lons) > 0: with map_ax.hold_limits(): for name, xpt, ypt, _colorpt in zip(labels, lons, lats, color): map_ax.text(xpt, ypt, name, weight="heavy", color="k", zorder=100, transform=ccrs.Geodetic(), path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white")]) scatter = map_ax.scatter(lons, lats, marker=marker, s=size, c=color, zorder=10, cmap=colormap, transform=ccrs.Geodetic()) if title: plt.suptitle(title) # Only show the colorbar for more than one event. if show_colorbar: if colorbar_ticklabel_format is not None: if isinstance(colorbar_ticklabel_format, (str, native_str)): formatter = FormatStrFormatter(colorbar_ticklabel_format) elif hasattr(colorbar_ticklabel_format, '__call__'): formatter = FuncFormatter(colorbar_ticklabel_format) elif isinstance(colorbar_ticklabel_format, Formatter): formatter = colorbar_ticklabel_format locator = MaxNLocator(5) else: if datetimeplot: locator = AutoDateLocator() formatter = AutoDateFormatter(locator) # Compat with old matplotlib versions. if hasattr(formatter, "scaled"): formatter.scaled[1 / (24. * 60.)] = '%H:%M:%S' else: locator = None formatter = None cb = Colorbar(cm_ax, scatter, cmap=colormap, orientation='horizontal', ticks=locator, format=formatter) # Compat with old matplotlib versions. if hasattr(cb, "update_ticks"): cb.update_ticks() if show: plt.show() return fig
fig, ax = plt.subplots() CS = ax.contour(X, Y, Z) ax.clabel(CS, inline=1, fontsize=10) ax.set_title('Simplest default with labels') plt.show() #3D fig = plt.figure() ax = fig.gca(projection='3d') # Make data. # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. ax.set_zlim(-2, 2) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=10, aspect=5) plt.show()
def plot_basemap(lons, lats, size, color, labels=None, projection='global', resolution='l', continent_fill_color='0.8', water_fill_color='1.0', colormap=None, colorbar=None, marker="o", title=None, colorbar_ticklabel_format=None, show=True, fig=None, **kwargs): # @UnusedVariable """ Creates a basemap plot with a data point scatter plot. :type lons: list/tuple of floats :param lons: Longitudes of the data points. :type lats: list/tuple of floats :param lats: Latitudes of the data points. :type size: float or list/tuple of floats :param size: Size of the individual points in the scatter plot. :type color: list/tuple of floats (or objects that can be converted to floats, like e.g. :class:`~obspy.core.utcdatetime.UTCDateTime`) :param color: Color information of the individual data points to be used in the specified color map (e.g. origin depths, origin times). :type labels: list/tuple of str :param labels: Annotations for the individual data points. :type projection: str, optional :param projection: The map projection. Currently supported are: * ``"global"`` (Will plot the whole world.) * ``"ortho"`` (Will center around the mean lat/long.) * ``"local"`` (Will plot around local events) Defaults to "global". :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be based directly to the basemap module. Possible values are: * ``"c"`` (crude) * ``"l"`` (low) * ``"i"`` (intermediate) * ``"h"`` (high) * ``"f"`` (full) Defaults to ``"l"``. For compatibility, you may also specify any of the Cartopy resolutions defined in :func:`plot_cartopy`. :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type colormap: str, any matplotlib colormap, optional :param colormap: The colormap for color-coding the events as provided in `color` kwarg. The event with the smallest `color` property will have the color of one end of the colormap and the event with the highest `color` property the color of the other end with all other events in between. Defaults to None which will use the default matplotlib colormap. :type colorbar: bool, optional :param colorbar: When left `None`, a colorbar is plotted if more than one object is plotted. Using `True`/`False` the colorbar can be forced on/off. :type title: str :param title: Title above plot. :type colorbar_ticklabel_format: str or function or subclass of :class:`matplotlib.ticker.Formatter` :param colorbar_ticklabel_format: Format string or Formatter used to format colorbar tick labels. :type show: bool :param show: Whether to show the figure after plotting or not. Can be used to do further customization of the plot before showing it. :type fig: :class:`matplotlib.figure.Figure` :param fig: Figure instance to reuse, returned from a previous :func:`plot_basemap` call. If a previous basemap plot is reused, any kwargs regarding the basemap plot setup will be ignored (i.e. `projection`, `resolution`, `continent_fill_color`, `water_fill_color`). Note that multiple plots using colorbars likely are problematic, but e.g. one station plot (without colorbar) and one event plot (with colorbar) together should work well. """ import matplotlib.pyplot as plt if any([isinstance(c, (datetime.datetime, UTCDateTime)) for c in color]): datetimeplot = True color = [ (np.isfinite(float(t)) and date2num(getattr(t, 'datetime', t)) or np.nan) for t in color] else: datetimeplot = False # The colorbar should only be plotted if more then one event is # present. if colorbar is None: if len(lons) > 1 and hasattr(color, "__len__") and \ not isinstance(color, (str, native_str)): colorbar = True else: colorbar = False if fig is None: fig = plt.figure() if projection == "local": ax_x0, ax_width = 0.10, 0.80 elif projection == "global": ax_x0, ax_width = 0.01, 0.98 else: ax_x0, ax_width = 0.05, 0.90 if colorbar: map_ax = fig.add_axes([ax_x0, 0.13, ax_width, 0.77]) cm_ax = fig.add_axes([ax_x0, 0.05, ax_width, 0.05]) else: ax_y0, ax_height = 0.05, 0.85 if projection == "local": ax_y0 += 0.05 ax_height -= 0.05 map_ax = fig.add_axes([ax_x0, ax_y0, ax_width, ax_height]) bmap = None else: error_message_suffix = ( ". Please provide a figure object from a previous call to the " ".plot() method of e.g. an Inventory or Catalog object.") try: map_ax = fig.axes[0] except IndexError as e: e.args = tuple([e.args[0] + error_message_suffix] + list(e.args[1:])) raise try: bmap = fig.bmap except AttributeError as e: e.args = tuple([e.args[0] + error_message_suffix] + list(e.args[1:])) raise # basemap plots will break with basemap 1.1.0 together with matplotlib # >=2.3 (see matplotlib/basemap#382) so only thing we can do is show a # nicer message. # XXX can be removed maybe a year or so after basemap # 1.1.1 or 1.2.0 is released try: from matplotlib.cbook import MatplotlibDeprecationWarning except ImportError: # matplotlib 1.2.0 does not have that warning class yet # XXX can be removed when minimum matplotlib version gets bumped to # XXX 1.3.0 category = {} else: category = {'category': MatplotlibDeprecationWarning} try: with warnings.catch_warnings(): warnings.filterwarnings( 'ignore', message='The axesPatch function was deprecated ' 'in version 2.1. Use Axes.patch instead.', module='.*basemap.*', **category) scatter = _plot_basemap_into_axes( ax=map_ax, lons=lons, lats=lats, size=size, color=color, bmap=bmap, labels=labels, projection=projection, resolution=resolution, continent_fill_color=continent_fill_color, water_fill_color=water_fill_color, colormap=colormap, marker=marker, title="", adjust_aspect_to_colorbar=colorbar, **kwargs) except AttributeError as e: if 'axesPatch' not in str(e): raise msg = ('Encountered a problem doing the basemap plot due to a known ' 'issue of matplotlib >=2.3 together with basemap <=1.1.0 (see ' 'https://github.com/matplotlib/basemap/issues/382). Please ' 'update basemap to a version >1.1.0 if available or downgrade ' 'matplotlib to a version <2.3.') raise Exception(msg) if title: plt.suptitle(title) if colorbar: if colorbar_ticklabel_format is not None: if isinstance(colorbar_ticklabel_format, (str, native_str)): formatter = FormatStrFormatter(colorbar_ticklabel_format) elif hasattr(colorbar_ticklabel_format, '__call__'): formatter = FuncFormatter(colorbar_ticklabel_format) elif isinstance(colorbar_ticklabel_format, Formatter): formatter = colorbar_ticklabel_format locator = MaxNLocator(5) else: if datetimeplot: locator = AutoDateLocator() formatter = AutoDateFormatter(locator) # Compat with old matplotlib versions. if hasattr(formatter, "scaled"): formatter.scaled[1 / (24. * 60.)] = '%H:%M:%S' else: locator = None formatter = None # normal case: axes for colorbar was set up in this routine if "cm_ax" in locals(): cb_kwargs = {"cax": cm_ax} # unusual case: reusing a plot that has no colorbar set up previously else: cb_kwargs = {"ax": map_ax} cb = fig.colorbar( mappable=scatter, cmap=colormap, orientation='horizontal', ticks=locator, format=formatter, **cb_kwargs) # Compat with old matplotlib versions. if hasattr(cb, "update_ticks"): cb.update_ticks() if show: plt.show() return fig
] stations = ['Huaxian', 'Xianyang', 'Zhangjiashan'] fig_idx = ['(a)', '(b)', '(c)', '(d)'] for k in range(len(records_sets)): records_list = records_sets[k] predictions_list = predictions_sets[k] x_s = x_sets[k] y_s = y_sets[k] plt.figure(figsize=(5.5, 5.5)) for j in range(len(records_list)): ax = plt.subplot(2, 2, j + 1, aspect='equal') xx, linear_list, xymin, xymax = compute_multi_linear_fit( records=records_list[j], predictions=predictions_list[j], ) ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) # if j in range(8,12): plt.xlabel('Predictions(' + r'$10^8m^3$' + ')', ) # if j in [0,4,8]: plt.ylabel('Records(' + r'$10^8m^3$' + ')', ) models = models_labels[j] markers = [ 'o', 'v', ] zorders = [1, 0] plt.text(x_s[j], y_s[j], fig_idx[j], fontweight='normal', fontsize=7) for i in range(len(predictions_list[j])): # plt.plot(predictions_list[i], records_list[i],marker=markers[i], markerfacecolor='w',markeredgecolor='blue',markersize=6.5) plt.scatter( predictions_list[j][i],
## #the belief of the previous state ## I=gauss_pbc(3 * pi / 2,sig) ## for t in arange(90): ## u=update(u,I) ## x=0.5*(tanh(0.1*u)+1) ## xall=xall+[x] # # #Wait till it stabilizes for 50 steps # I=zeros(n) # for t in arange(200): # u=update(u,I) # x=0.5*(tanh(0.1*u)+1) # xall=xall+[x] #Create a figure for the 3d plot fig = plt.figure() ax = fig.gca(projection='3d') X, Y = meshgrid(arange(n), arange(350)) surf = ax.plot_surface(X, Y, asarray(xall), cmap=cm.jet, linewidth=0, antialiased=True) ax.w_zaxis.set_major_locator(LinearLocator(10)) ax.w_zaxis.set_major_formatter(FormatStrFormatter('%.1f')) ax.set_zlabel("Excitation") ax.set_xlabel("Node") ax.set_ylabel("Time") fig.colorbar(surf, shrink=0.5, aspect=5)