def data_load(PATH, DATANAME, COLUMNNAME): pb.printProgressBar(0, len(DATANAME), prefix='Loading Data:', suffix='Complete') for i in range(len(DATANAME)): print("Opening Data file: %s%s" % (PATH[i], DATANAME[i])) try: FILE = pyfits.open(PATH[i] + DATANAME[i]) pb.printProgressBar(i, len(DATANAME), prefix='Loading Data:', suffix='Complete') except: print("FILE COULD NOT BE OPENED") TABLE = FILE[1].data for j in COLUMNNAME[i]: print("Loading column %s" % j) VAR = TABLE.field("%s" % j) CleanVAR = [x for x in VAR if str(x) != 'nan'] DATASET.append(CleanVAR) print("Data set loaded ready for plotting") return DATASET
def plot(x,y,x_error=[None],y_error=[None],DATALABELS=[None],COLOURS=[None], SIZES=[None],POINTSTYLES=['none'],EDGECOLOURS=[None]): HANDLES = [] n_var = len(x) x_error = default_lengths(x_error,n_var) y_error = default_lengths(y_error,n_var) #DATALABELS = default_lengths(DATALABELS,n_var) COLOURS = default_lengths(COLOURS,n_var) SIZES = default_lengths(SIZES,n_var) POINTSTYLES = default_lengths(POINTSTYLES,n_var) EDGECOLOURS = default_lengths(EDGECOLOURS,n_var) #colour_cycle(len(DATALABELS),COLOURS) pb.printProgressBar(0,len(x),prefix='BEGINNING PLOTTING',suffix='COMPLETE', length=40) for i in range(len(x)): pb.printProgressBar(i,len(x),prefix='PLOTTING VARIABLE %d'%(i+1), suffix='COMPLETE',length=40) PLOT = plt.errorbar(np.array(x[i]),np.array(y[i]),xerr=x_error[i], yerr=y_error[i],color=COLOURS[i],s=SIZES[i], fmt=POINTSTYLES[i],edgecolor=EDGECOLOURS[i], label=None) HANDLES.append(PLOT[0]) pb.printProgressBar(len(x),len(x),prefix='FINISHED PLOTTING!', suffix='COMPLETE!',length=40) return HANDLES
def plot(DATASET, DATALABEL, COLOURS): PLOTS = [] HANDLES = [] LEGEND = [] all_counts = [] global MIN, MAX, WID, n, LINES, LINW, SHADE MIN = default_lengths(MIN, DATALABEL) MAX = default_lengths(MAX, DATALABEL) WID = default_lengths(WID, DATALABEL) n = default_lengths(n, DATALABEL) #COLOURS = default_lengths(COLOURS,DATALABEL) LINES = default_lengths(LINES, DATALABEL) LINW = default_lengths(LINW, DATALABEL) SHADE = default_lengths(SHADE, DATALABEL) colour_cycle(len(DATALABEL), PLOTS, COLOURS) pb.printProgressBar(0, len(DATASET), prefix='BEGINNING PLOTTING', suffix='COMPLETE', length=40) for i in range(len(DATASET)): #print("Plotting Variable %d"%(i+1)) pb.printProgressBar(i, len(DATASET), prefix='PLOTTING VARIABLE %d' % (i + 1), suffix='COMPLETE', length=40) x, y, NORM, MIN[i], MAX[i] = make_bins(DATASET[i], MIN[i], MAX[i], WID[i], n[i]) all_counts.append(y) LINE = plt.plot(np.array(x), np.array(y), linestyle=LINES[i], color=COLOURS[i], linewidth=int(LINW[i]), label=None) FILL = plt.fill(np.array(x), np.array(y), alpha=SHADE[i], color=COLOURS[i], label=DATALABEL[i]) HANDLES.append(FILL[0]) pb.printProgressBar(len(DATASET), len(DATASET), prefix='FINISHED PLOTTING!', length=40) return HANDLES, all_counts, MIN, MAX
def plot(x,y,x_error=[None],y_error=[None],DATALABELS=[None],COLOURS=[None], FILL_COLOURS=[None],SHADE=[0.5],SIZES=[None],POINTSTYLES=['none'], EDGECOLOURS=[None],EDGEWID=[None],LWID=[2],ERBWID=[2]): """ Method capable of plotting multiple sets of 2D variables Args: x (2D array of floats): All arrays of x-axis data to plot y (2D array of floats): All arrays of y-axis data to plot x_error (2D Array of floats/tuples): Errors for each x value Supports tuples for assymetric errors y_error (2D Array of floats/tuples): Errors for each y value Supports tuples for assymetric errors """ HANDLES = [] x = convert_to_array(x) y = convert_to_array(y) n_var = len(x) # Makes sure all parameters are the same length as number of plots x_error = default_lengths(x_error,n_var) y_error = default_lengths(y_error,n_var) DATALABELS = default_lengths(DATALABELS,n_var) COLOURS = default_lengths(COLOURS,n_var) FILL_COLOURS = default_lengths(FILL_COLOURS,n_var) SIZES = default_lengths(SIZES,n_var) POINTSTYLES = default_lengths(POINTSTYLES,n_var) EDGECOLOURS = default_lengths(EDGECOLOURS,n_var) SHADE = default_lengths(SHADE,n_var) LWID = default_lengths(LWID,n_var) ERBWID = default_lengths(ERBWID,n_var) EDGEWID = default_lengths(EDGEWID,n_var) # Initialise progress bar for plotting if print_on == True: pb.printProgressBar(0,len(x),prefix='BEGINNING PLOTTING', suffix='COMPLETE', length=40) # Run through x and y sets and create plots for i in range(len(x)): # Update progress bar if print_on == True: pb.printProgressBar(i,len(x),prefix='PLOTTING VARIABLE %d'%(i+1), suffix='COMPLETE',length=40) # Plot x and y within parameters PLOT = plt.errorbar(np.array(x[i]),np.array(y[i]),xerr=x_error[i], yerr=y_error[i],color=COLOURS[i],ms=SIZES[i], fmt=POINTSTYLES[i],mec=EDGECOLOURS[i], lw=LWID[i],elinewidth=ERBWID[i],mew=EDGEWID[i]) # Appends the artist label for this plot to HANDLES for legend entry if DATALABELS[i] != None: HANDLES.append(PLOT[0]) # Fills underneath line/scatters # WARNING: THIS IS IN ALPHA DEVELOPMENT! if FILL_COLOURS[i] != None: plt.fill(np.array(x[i]),np.array(y[i]),alpha=SHADE[i], color=FILL_COLOURS[i]) # Finishes progress bar if print_on == True: pb.printProgressBar(len(x),len(x),prefix='FINISHED PLOTTING!', suffix='COMPLETE!',length=40) return HANDLES
def data_load(DATANAME, COLUMNNAME, PATH=['']): """Load data in from columns in a FITS file Args: DATANAME ([str]): Array of strings with names of the FITS file containing the data to be loaded COLUMNNAME ([[str]]): 2D array of strings with first axis being of equal length to DATANAME, and the second axis being the names of the columns to be loaded from each FITS file in DATANAME PATH: Optional variable that is a list of strings for paths to each FITS file. Should be same length as DATANAME Returns: A 2D array of data requested from FITS files """ # Defines the array that will hold all the variables to plot DATASET = [] # Checks that PATH is the same length as DATANAME and corrects if not PATH = laplt.default_lengths(PATH, len(DATANAME)) if laplt.print_on: # Initialises the progress bar for loading the data pb.printProgressBar(0, 2 * len(DATANAME) * sum(len(x) for x in COLUMNNAME), prefix='LOADING DATA:', suffix='COMPLETE', length=40) # Loops through the FITS files for i in range(len(DATANAME)): # Exception handling in case file cannot be opened try: # Opens file into memory FILE = pyfits.open("%s%s" % (PATH[i], DATANAME[i])) if laplt.print_on: # Updates progress bar pb.printProgressBar( i, 2 * len(DATANAME) * sum(len(x) for x in COLUMNNAME), prefix='OPENING DATA FILE %s%s:' % (PATH[i], DATANAME[i]), suffix='COMPLETE', length=40) # Loads Extension 1 of the FITS file into memory TABLE = FILE[1].data # Loops through and loads all the columns in the file to be loaded for j in range(len(COLUMNNAME[i])): if laplt.print_on: # Progress bar updated to reflect this pb.printProgressBar( i + j, 2 * len(DATANAME) * sum(len(x) for x in COLUMNNAME), prefix='LOADING COLUMN %s:' % COLUMNNAME[i][j], suffix='COMPLETE', length=40) # Loads column into memory VAR = TABLE.field("%s" % COLUMNNAME[i][j]) # Removes any 'nan' (Not an Actual Number) strings that are # placeholders if there are blank entries as these would throw # errors CleanVAR = [x for x in VAR if str(x) != 'nan'] # Adds 'cleaned' variable into DATASET DATASET.append(CleanVAR) # If file cannot be opened, throws an exception except: print("FILE COULD NOT BE OPENED") if laplt.print_on: # Completes progress bar once all variables are loaded into DATASET pb.printProgressBar( 2 * len(DATANAME) * sum(len(x) for x in COLUMNNAME), 2 * len(DATANAME) * sum(len(x) for x in COLUMNNAME), prefix='DATASET LOADED READY FOR PLOTTING!', suffix='COMPLETE!', length=40) return DATASET # Returns 2D array of variables
def plot(x, y, x_error=[None], y_error=[None], DATALABELS=[None], COLOURS=[None], FILL_COLOURS=[None], SHADE=[0.5], SIZES=[None], POINTSTYLES=['none'], EDGECOLOURS=[None], EDGEWID=[None], LWID=[2], ERBWID=[2]): """ Method capable of plotting multiple sets of 2D variables Args: x ([[float]]): All arrays of x-axis data to plot y ([[float]]): All arrays of y-axis data to plot x_error ([[float]]/[[tuple]]): Errors for each x value. Supports tuples for asymmetric errors y_error ([[float]]/[[tuple]]): Errors for each y value. Supports tuples for asymmetric errors DATALABELS ([str]): Labels for legend of plots COLOURS ([str]): Colours for each plot FILL_COLOURS ([str]): Colour of fill for plot. If None is entered then no fill is used SHADE ([float]): Alpha value for fill under each plot SIZES ([float]): Size of points for each plot POINTSTYLES ([str]): Style of point/ line for each plot EDGECOLOURS ([str]): Colour for points of each plot EDGEWID ([float]): Width of point edge for each plot LWID ([float]): Width of line for each plot ERBWID ([float]): Width of error bars for each plot Returns: HANDLES: Handles for each plot to be used to construct a legend and final figure """ HANDLES = [] x = convert_to_array(x) y = convert_to_array(y) n_var = len(x) # Makes sure all parameters are the same length as number of plots x_error = default_lengths(x_error, n_var) y_error = default_lengths(y_error, n_var) DATALABELS = default_lengths(DATALABELS, n_var) COLOURS = default_lengths(COLOURS, n_var) FILL_COLOURS = default_lengths(FILL_COLOURS, n_var) SIZES = default_lengths(SIZES, n_var) POINTSTYLES = default_lengths(POINTSTYLES, n_var) EDGECOLOURS = default_lengths(EDGECOLOURS, n_var) SHADE = default_lengths(SHADE, n_var) LWID = default_lengths(LWID, n_var) ERBWID = default_lengths(ERBWID, n_var) EDGEWID = default_lengths(EDGEWID, n_var) # Initialise progress bar for plotting if print_on: pb.printProgressBar(0, len(x), prefix='BEGINNING PLOTTING', suffix='COMPLETE', length=40) # Run through x and y sets and create plots for i in range(len(x)): # Update progress bar if print_on: pb.printProgressBar(i, len(x), prefix='PLOTTING VARIABLE %d' % (i + 1), suffix='COMPLETE', length=40) # Plot x and y within parameters PLOT = plt.errorbar(np.array(x[i]), np.array(y[i]), xerr=x_error[i], yerr=y_error[i], color=COLOURS[i], ms=SIZES[i], fmt=POINTSTYLES[i], mec=EDGECOLOURS[i], lw=LWID[i], elinewidth=ERBWID[i], mew=EDGEWID[i]) # Appends the artist label for this plot to HANDLES for legend entry if DATALABELS[i] is not None: HANDLES.append(PLOT[0]) # Fills underneath line/scatters # WARNING: THIS IS IN ALPHA DEVELOPMENT! if FILL_COLOURS[i] is not None: plt.fill(np.array(x[i]), np.array(y[i]), alpha=SHADE[i], color=FILL_COLOURS[i]) # Finishes progress bar if print_on: pb.printProgressBar(len(x), len(x), prefix='FINISHED PLOTTING!', suffix='COMPLETE!', length=40) return HANDLES
def plot(ax, x, y, z, DATALABELS=[None], COLOURS=[None], SIZES=[2], POINTSTYLES=['none'], CMAP=[None]): """ Method capable of plotting multiple sets of 2D variables Args: x ([[float]]): All arrays of x-axis data to plot y ([[float]]): All arrays of y-axis data to plot DATALABELS ([str]): Labels for legend of plots COLOURS ([str]): Colours for each plot SIZES ([float]): Size of points for each plot POINTSTYLES ([str]): Style of point/ line for each plot CMAP (): Returns: HANDLES: Handles for each plot to be used to construct a legend and final figure """ HANDLES = [] if not isinstance(x[0], (list, np.ndarray)): x = [x] if not isinstance(y[0], (list, np.ndarray)): y = [y] if not isinstance(z[0], (list, np.ndarray)): z = [z] n_var = len(x) # Makes sure all parameters are the same length as number of plots DATALABELS = laplt2D.default_lengths(DATALABELS, n_var) COLOURS = laplt2D.default_lengths(COLOURS, n_var) SIZES = laplt2D.default_lengths(SIZES, n_var) POINTSTYLES = laplt2D.default_lengths(POINTSTYLES, n_var) # Initialise progress bar for plotting if print_on: pb.printProgressBar(0, len(x), prefix='BEGINNING PLOTTING', suffix='COMPLETE', length=40) # Run through x and y sets and create plots for i in range(len(x)): # Update progress bar if print_on: pb.printProgressBar(i, len(x), prefix='PLOTTING VARIABLE %d' % (i + 1), suffix='COMPLETE', length=40) c = None if COLOURS[i] == 'colourbar' and CMAP[i] is not None: c = np.array(z[i]) # Plot x and y within parameters PLOT = ax.scatter(xs=np.array(x[i]), ys=np.array(y[i]), zs=np.array(z[i]), c=c, cmap=CMAP[i], s=SIZES[i], marker=POINTSTYLES[i]) cb = plt.colorbar(PLOT) if not visible_colourbar: cb.remove() # Appends the artist label for this plot to HANDLES for legend entry if DATALABELS[i] is not None: HANDLES.append(PLOT) # Finishes progress bar if print_on: pb.printProgressBar(len(x), len(x), prefix='FINISHED PLOTTING!', suffix='COMPLETE!', length=40) print("\n") return ax, HANDLES
def create_visualisation(x, y, z, DATALABELS=[None], COLOURS=[None], CMAP=[None], SIZES=[2], POINTSTYLES=['none'], x_label=None, y_label=None, z_label=None, figure_name="Plot3D_fig.pdf", figsize=(10., 10.), axis_range=[0.0, 10.0, 0.0, 10.0], label_rot=[20.0, 340.0, 90.0], elev=None, azim=None, no_frames=20, folder='Frames'): """ Creates a figure (or multiple figures) of the plots of data supplied Args: x (2D Array of floats): Data to plot on x-axis y (2D Array of floats): Data to plot on y-axis x_error (2D Array of floats/tuples): Errors for each x value Supports tuples for assymetric errors y_error (2D Array of floats/tuples): Errors for each y value Supports tuples for assymetric errors DATALABELS (Array of strings): Label for each variable for legend COLOURS (Array of strings): Colours """ # WELCOME MESSAGE ======================================================== if print_on == True: print("\nWELCOME TO Plot3D") print("PART OF THE LancAstro PACKAGE \n") # Sets up the figure size from parameters before plotting commences fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='3d') # Sets the x,y-axis scales from parameters ax.set_xscale(x_scale) ax.set_yscale(y_scale) ax.set_zscale(z_scale) # Calls plot method to plot each variable from the dataset ax, HANDLES = plot(ax, x, y, z, DATALABELS=DATALABELS, COLOURS=COLOURS, SIZES=SIZES, POINTSTYLES=POINTSTYLES, CMAP=CMAP) # If set to, automatically sets the min and max of the axis # from the range of all the data if auto_axis == True: axis_range = determine_axis(x, y, z=z, w=w) # Places grid if set to do so ax.grid(grid) ax.axis(visible_axes) # Creates figure axis from defined parameters ax.set_xlim(axis_range[0], axis_range[1]) ax.set_ylim(axis_range[2], axis_range[3]) ax.set_zlim(axis_range[4], axis_range[5]) # Creates x and y axis labels from settings if visible_axes == True: ax.set_xlabel(x_label, color=x_colour, fontsize=x_size, rotation=label_rot[0]) ax.set_ylabel(y_label, color=y_colour, fontsize=y_size, rotation=label_rot[1]) ax.set_zlabel(z_label, color=z_colour, fontsize=z_size, rotation=label_rot[2]) if visible_axes == False: ax.set_xlabel([]) ax.set_ylabel([]) ax.set_zlabel([]) # ax.axes.get_xaxis().set_visible(False) # ax.axes.get_yaxis().set_visible(False) # ax.axes.get_zaxis().set_visible(False) # If true, creates a legend if legend_on == True: if print_on == True: print("Producing legend") leg = fig.legend(handles=HANDLES, labels=DATALABELS) # Sets legend frame to be transparent if set to do so if frame == False: leg.get_frame().set_facecolor('none') # Removes legend border if set to False if frame_border == False: leg.get_frame().set_linewidth(0.0) # Sets frame border to defiend if frame_border == True: leg.get_frame().set_edgecolor(frame_colour) # Sets ticks on the top and right axis if true if both_axis == True: ax.tick_params(which="both", direction="in", top=True, right=True) # Initialise progress bar for plotting if print_on == True: pb.printProgressBar(0, no_frames + 2, prefix='BEGINNING VISUALISATION', suffix='COMPLETE', length=40) for i in np.arange(0, no_frames, 1): cpfig = fig # Sets elevation and azimuthal angle of plot if azim == None: ax.view_init(elev=elev, azim=(float(i) / float(no_frames) * 360.0)) if elev == None: ax.view_init(elev=(float(i) / float(no_frames) * 360.0), azim=azim) if elev == None and azim == None: ax.view_init(elev=(float(i) / float(no_frames) * 360.0), azim=(float(i) / float(no_frames) * 360.0)) cpfig.savefig("%s%d%s" % (folder, i, figure_name), bbox_inches='tight') if print_on == True: pb.printProgressBar(i + 1, no_frames + 2, prefix='FRAME NO.%d SAVED ' % i, suffix='COMPLETE', length=40) plt.close() # Finishes progress bar if print_on == True: pb.printProgressBar(no_frames + 2, no_frames + 2, prefix='VISUALISATION COMPLETE!', suffix='COMPLETE!', length=40) print("\n")