def plot_3d_scatter(self, fig, ax, x, y, z, title='', xlabel='', ylabel='', zlabel='', title_font={}, axis_font={}, tick_font={}): if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default cmap = plt.cm.jet h = plt.scatter(x, y, c=z, cmap=cmap) ax.set_aspect(1./ax.get_data_ratio()) # make axes square cbar = plt.colorbar(h, orientation='vertical', aspect=30, shrink=0.9) if xlabel: ax.set_xlabel(xlabel.replace("_", " "), labelpad=10, **axis_font) if ylabel: ax.set_ylabel(ylabel.replace("_", " "), labelpad=10, **axis_font) if zlabel: cbar.ax.set_ylabel(zlabel.replace("_", " "), labelpad=10, **axis_font) if tick_font: ax.tick_params(**tick_font) if title: ax.set_title(title.replace("_", " "), **title_font) ax.grid(True) plt.tight_layout()
def plot_stacked_time_series(self, fig, ax, x, y, z, title='', ylabel='', cbar_title='', title_font={}, axis_font={}, tick_font = {}, **kwargs): if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default z = np.ma.array(z, mask=np.isnan(z)) h = plt.pcolormesh(x, y, z, shading='gouraud', **kwargs) # h = plt.pcolormesh(x, y, z, **kwargs) if ylabel: ax.set_ylabel(ylabel.replace("_", " "), **axis_font) if title: ax.set_title(title.replace("_", " "), **title_font) plt.axis([x.min(), x.max(), y.min(), y.max()]) ax.xaxis_date() date_list = mdates.num2date(x) self.get_time_label(ax, date_list) fig.autofmt_xdate() ax.invert_yaxis() cbar = plt.colorbar(h) if cbar_title: cbar.ax.set_ylabel(cbar_title, **axis_font) ax.grid(True) if tick_font: ax.tick_params(**tick_font) plt.tight_layout()
def plot_profile(self, fig, ax, x, y, xlabel='', ylabel='', axis_font={}, tick_font={}, scatter=False, **kwargs): if not axis_font: axis_font = axis_font_default if scatter: ppl.scatter(ax, x, y, **kwargs) else: ppl.plot(ax, x, y, **kwargs) if xlabel: ax.set_xlabel(xlabel.replace("_", " "), labelpad=5, **axis_font) if ylabel: ax.set_ylabel(ylabel.replace("_", " "), labelpad=11, **axis_font) if tick_font: ax.tick_params(**tick_font) ax.xaxis.set_label_position('top') # this moves the label to the top ax.xaxis.set_ticks_position('top') ax.xaxis.get_major_locator()._nbins = 5 ax.grid(True) plt.tight_layout()
def plot_days(days): nplots = len(days) fig, subplots = plt.subplots(nplots, figsize=(10, 50)) for i, day in enumerate(days): subplot = subplots[i] plot_day(day, subplot) plt.tight_layout() plt.savefig('./plots/best.png')
def plot_1d_quiver(self, fig, ax, time, u, v, title='', ylabel='', title_font={}, axis_font={}, tick_font={}, legend_title="Magnitude", start=None, end=None, **kwargs): if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default # Plot quiver magnitude = (u**2 + v**2)**0.5 maxmag = max(magnitude) ax.set_ylim(-maxmag, maxmag) dx = time[-1] - time[0] if start and end: ax.set_xlim(start - 0.05 * dx, end + 0.05 * dx) else: ax.set_xlim(time[0] - 0.05 * dx, time[-1] + 0.05 * dx) # ax.fill_between(time, magnitude, 0, color='k', alpha=0.1) # # Fake 'box' to be able to insert a legend for 'Magnitude' # p = ax.add_patch(plt.Rectangle((1, 1), 1, 1, fc='k', alpha=0.1)) # leg1 = ax.legend([p], [legend_title], loc='lower right') # leg1._drawFrame = False # # 1D Quiver plot q = ax.quiver(time, 0, u, v, **kwargs) plt.quiverkey(q, 0.2, 0.05, 0.2, r'$0.2 \frac{m}{s}$', labelpos='W', fontproperties={'weight': 'bold'}) ax.xaxis_date() date_list = mdates.num2date(time) self.get_time_label(ax, date_list) fig.autofmt_xdate() if ylabel: ax.set_ylabel(ylabel.replace("_", " "), labelpad=20, **axis_font) if tick_font: ax.tick_params(**tick_font) ax.set_title(title.replace("_", " "), **title_font) plt.tight_layout()
def plot_time_series(self, fig, is_timeseries, ax, x, y, fill=False, title='', xlabel='', ylabel='', title_font={}, axis_font={}, tick_font={}, scatter=False, qaqc=[], events={}, **kwargs): if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default if scatter: ppl.scatter(ax, x, y, **kwargs) else: h = ppl.plot(ax, x, y, **kwargs) if is_timeseries: self.get_time_label(ax, x) fig.autofmt_xdate() else: ax.set_xlabel(xlabel.replace("_", " "), **axis_font) if ylabel: ax.set_ylabel(ylabel.replace("_", " "), **axis_font) if title: ax.set_title(title.replace("_", " "), **title_font) ax.grid(True) if fill: miny = min(ax.get_ylim()) if not scatter: ax.fill_between(x, y, miny+1e-7, facecolor = h[0].get_color(), alpha=0.15) else: ax.fill_between(x, y, miny+1e-7, facecolor = axis_font_default['color'], alpha=0.15) if events: ylim = ax.get_ylim() for event in events['events']: time = datestr2num(event['start_date']) x = np.array([time, time]) h = ax.plot(x, ylim, '--', label=event['class']) legend = ax.legend() if legend: for label in legend.get_texts(): label.set_fontsize(10) if len(qaqc) > 0: bad_data = np.where(qaqc > 0) h = ppl.plot(ax, x[bad_data], y[bad_data], marker='o', mfc='none', linestyle='None', markersize=6, markeredgewidth=2, mec='r') # plt.tick_params(axis='both', which='major', labelsize=10) if tick_font: ax.tick_params(**tick_font) plt.tight_layout()
def plot_1d_quiver(self, fig, ax, time, u, v, title='', ylabel='', title_font={}, axis_font={}, tick_font={}, key_units='m/s', legend_title="Magnitude", start=None, end=None, **kwargs): if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default # Plot quiver magnitude = (u**2 + v**2)**0.5 maxmag = max(magnitude) ax.set_ylim(-maxmag, maxmag) dx = time[-1] - time[0] if start and end: ax.set_xlim(start - 0.05 * dx, end + 0.05 * dx) else: ax.set_xlim(time[0] - 0.05 * dx, time[-1] + 0.05 * dx) # ax.fill_between(time, magnitude, 0, color='k', alpha=0.1) # # Fake 'box' to be able to insert a legend for 'Magnitude' # p = ax.add_patch(plt.Rectangle((1, 1), 1, 1, fc='k', alpha=0.1)) # leg1 = ax.legend([p], [legend_title], loc='lower right') # leg1._drawFrame = False mean_val = np.mean(magnitude) # Quick conversion of most popular key_units if key_units == 'm s-1': key_units = 'm/s' key_str = '{0:.2f} {1}'.format(mean_val, key_units) # 1D Quiver plot q = ax.quiver(time, 0, u, v, **kwargs) plt.quiverkey(q, 0.1, 0.05, mean_val, key_str, labelpos='W', fontproperties={'weight': 'light', 'style': 'italic', 'size': 'small', 'stretch': 'condensed'}) ax.xaxis_date() date_list = mdates.num2date(time) self.get_time_label(ax, date_list) fig.autofmt_xdate() if ylabel: ax.set_ylabel(ylabel.replace("_", " "), labelpad=20, **axis_font) if tick_font: ax.tick_params(**tick_font) ax.set_title(title.replace("_", " "), **title_font) plt.tight_layout()
def plot_ts_diagram(self, ax, sal, temp, xlabel='Salinity', ylabel='Temperature', title='', axis_font={}, title_font={}, tick_font={}, **kwargs): if not axis_font: axis_font = axis_font_default if not title_font: title_font = title_font_default sal = np.ma.array(sal, mask=np.isnan(sal)) temp = np.ma.array(temp, mask=np.isnan(temp)) if len(sal) != len(temp): raise Exception('Sal and Temp arrays are not the same size!') # Figure out boudaries (mins and maxs) smin = sal.min() - (0.01 * sal.min()) smax = sal.max() + (0.01 * sal.max()) tmin = temp.min() - (0.1 * temp.max()) tmax = temp.max() + (0.1 * temp.max()) # Calculate how many gridcells we need in the x and y dimensions xdim = round((smax-smin)/0.1+1, 0) ydim = round((tmax-tmin)+1, 0) # Create empty grid of zeros dens = np.zeros((ydim, xdim)) # Create temp and sal vectors of appropiate dimensions ti = np.linspace(1, ydim-1, ydim)+tmin si = np.linspace(1, xdim-1, xdim)*0.1+smin # Loop to fill in grid with densities for j in range(0, int(ydim)): for i in range(0, int(xdim)): dens[j, i] = sw.dens(si[i], ti[j], 0) # Substract 1000 to convert to sigma-t dens = dens - 1000 # Plot data cs = plt.contour(si, ti, dens, linestyles='dashed', colors='k') plt.clabel(cs, fontsize=12, inline=1, fmt='%1.0f') # Label every second level ppl.scatter(ax, sal, temp, **kwargs) ax.set_xlabel(xlabel.replace("_", " "), labelpad=10, **axis_font) ax.set_ylabel(ylabel.replace("_", " "), labelpad=10, **axis_font) ax.set_title(title.replace("_", " "), **title_font) ax.set_aspect(1./ax.get_data_ratio()) # make axes square if tick_font: ax.tick_params(**tick_font) plt.tight_layout()
def layerActivations(model, data, labels): print('Visualizing activations with tSNE...') if not os.path.exists(cc.cfg['plots']['layer_activations_dir']): os.makedirs(cc.cfg['plots']['layer_activations_dir']) numLabels = cc.cfg['plots']['layer_activations_label_cap'] data = data[:cc.cfg['plots']['layer_activations_points_cap']] labels = labels[:numLabels,:cc.cfg['plots']['layer_activations_points_cap']] subplotCols = numLabels subplotRows = len(model.layers)-1 subplotIdx = 1 plt.figure(figsize=(5*subplotCols,5*subplotRows)) for i in range(1,len(model.layers)): print('Running tSNE for layer {}/{}'.format(i+1,len(model.layers))) func = K.function([model.layers[0].input], [model.layers[i].output]) out = func([data])[0] tsneModel = TSNE(n_components = 2, random_state = 0) tsneOut = tsneModel.fit_transform(out).T # labeledTsneOut = np.hstack((tsneOut, labels[0].reshape(-1,1))) for j in range(numLabels): plt.subplot(subplotRows, subplotCols, subplotIdx) plt.title('{} / {}'.format(model.layers[i].name,cc.exp['params']['data']['labels'][j])) plt.scatter(tsneOut[0],tsneOut[1],c=labels[j],cmap = 'plasma') subplotIdx += 1 # tsneDF = pd.DataFrame(labeledTsneOut, columns = ('a', 'b', 'c')) # plot = tsneDF.plot.scatter(x = 'a', y = 'b', c = 'c', cmap = 'plasma') plt.tight_layout() plt.savefig('{}/activations.png'.format(cc.cfg['plots']['layer_activations_dir'])) plt.close() print('...done')
def histograms(modelLogger): if not cc.cfg['plots']['histograms']: return if not os.path.exists(cc.cfg['plots']['histograms_dir']): os.makedirs(cc.cfg['plots']['histograms_dir']) cntEpochs = len(modelLogger.epochLogs) cntLayers = len(modelLogger.epochLogs[-1]['weights']) logVals = [ {'name':'weights','color':'blue'}, {'name':'updates','color':'red'}, {'name':'ratios','color':'green'} ] subplotRows = len(logVals) subplotCols = cntLayers for x in range(cntEpochs): subplotIdx = 1 plt.figure(figsize=(5*subplotCols,5*subplotRows)) plt.suptitle('Histograms per layer, epoch {}/{}'.format(x,cntEpochs-1), fontsize=14) for logVal in logVals: for i,layer in enumerate(modelLogger.epochLogs[x][logVal['name']]): histmin = layer.min() histmax = layer.max() plt.subplot(subplotRows, subplotCols, subplotIdx) plt.title('{}, {}'.format(modelLogger.model.layers[modelLogger.loggedLayers[i]].name,logVal['name'])) plt.hist(layer, range = (histmin, histmax), bins = 30, color = logVal['color']) subplotIdx+=1 plt.tight_layout() plt.subplots_adjust(top=0.9) plt.savefig('{}/hist_{e:03d}.png'.format(cc.cfg['plots']['histograms_dir'], e = x)) plt.close()
def plot_stacked_time_series(self, fig, ax, x, y, z, title='', ylabel='', cbar_title='', title_font={}, axis_font={}, tick_font={}, **kwargs): if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default z = np.ma.array(z, mask=np.isnan(z)) h = plt.pcolormesh(x, y, z, shading='gouraud', **kwargs) # h = plt.pcolormesh(x, y, z, **kwargs) if ylabel: ax.set_ylabel(ylabel.replace("_", " "), **axis_font) if title: ax.set_title(title.replace("_", " "), **title_font) plt.axis([x.min(), x.max(), y.min(), y.max()]) ax.xaxis_date() date_list = mdates.num2date(x) self.get_time_label(ax, date_list) fig.autofmt_xdate() ax.invert_yaxis() cbar = plt.colorbar(h) if cbar_title: cbar.ax.set_ylabel(cbar_title) ax.grid(True) if tick_font: ax.tick_params(**tick_font) plt.tight_layout()
def plot_3d_scatter(self, fig, ax, x, y, z, title='', xlabel='', ylabel='', zlabel='', title_font={}, axis_font={}, tick_font={}): if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default cmap = plt.cm.jet h = plt.scatter(x, y, c=z, cmap=cmap) ax.set_aspect(1. / ax.get_data_ratio()) # make axes square cbar = plt.colorbar(h, orientation='vertical', aspect=30, shrink=0.9) if xlabel: ax.set_xlabel(xlabel.replace("_", " "), labelpad=10, **axis_font) if ylabel: ax.set_ylabel(ylabel.replace("_", " "), labelpad=10, **axis_font) if zlabel: cbar.ax.set_ylabel(zlabel.replace("_", " "), labelpad=10, **axis_font) if tick_font: ax.tick_params(**tick_font) if title: ax.set_title(title.replace("_", " "), **title_font) ax.grid(True) plt.tight_layout()
def plot_ts_diagram(self, ax, sal, temp, xlabel='Salinity', ylabel='Temperature', title='', axis_font={}, title_font={}, tick_font={}, **kwargs): if not axis_font: axis_font = axis_font_default if not title_font: title_font = title_font_default sal = np.ma.array(sal, mask=np.isnan(sal)) temp = np.ma.array(temp, mask=np.isnan(temp)) if len(sal) != len(temp): raise Exception('Sal and Temp arrays are not the same size!') # Figure out boudaries (mins and maxs) smin = sal.min() - (0.01 * sal.min()) smax = sal.max() + (0.01 * sal.max()) tmin = temp.min() - (0.1 * temp.max()) tmax = temp.max() + (0.1 * temp.max()) # Calculate how many gridcells we need in the x and y dimensions xdim = round((smax - smin) / 0.1 + 1, 0) ydim = round((tmax - tmin) + 1, 0) # Create empty grid of zeros dens = np.zeros((ydim, xdim)) # Create temp and sal vectors of appropiate dimensions ti = np.linspace(1, ydim - 1, ydim) + tmin si = np.linspace(1, xdim - 1, xdim) * 0.1 + smin # Loop to fill in grid with densities for j in range(0, int(ydim)): for i in range(0, int(xdim)): dens[j, i] = sw.dens(si[i], ti[j], 0) # Substract 1000 to convert to sigma-t dens = dens - 1000 # Plot data cs = plt.contour(si, ti, dens, linestyles='dashed', colors='k') plt.clabel(cs, fontsize=12, inline=1, fmt='%1.0f') # Label every second level ppl.scatter(ax, sal, temp, **kwargs) ax.set_xlabel(xlabel.replace("_", " "), labelpad=10, **axis_font) ax.set_ylabel(ylabel.replace("_", " "), labelpad=10, **axis_font) ax.set_title(title.replace("_", " "), **title_font) ax.set_aspect(1. / ax.get_data_ratio()) # make axes square if tick_font: ax.tick_params(**tick_font) plt.tight_layout()
def main(): description = """Simple bar plot of table. Input is a table from a file or standard input.""" parser = argparse.ArgumentParser( description=description, formatter_class=RawTextHelpFormatter ) parser.add_argument( '-f', '--filename', action='store', metavar='table.csv', help='''A table of the format: x_title, y_title, Main_title x_label1, value1 x_label2, value2''', required=False, dest='filename', ) args = parser.parse_args() if args.filename: filename = args.filename.strip() else: parser.print_help() sys.exit(1) y = [] x = [] for line in open(filename, "r").readlines(): line = line.strip() res = re.search("[0-9]+", line) if not res: line = line.split(",") x_lab = line[0] y_lab = line[1] main = line[2] else: line = line.split(",") if len(line) < 2: y.append(float(line[0])) else: x.append(line[0]) y.append(float(line[1])) print(line) if len(x) < 1: x = range(1, len(y) + 1) plt.rc('font', **{'family': 'DejaVu Sans'}) fig, ax = plt.subplots(1, figsize=(8, 6)) width = 0.2 ind = np.arange(len(y)) xdata = ind + 0.05 + width ax.bar(ind, y) ax.set_xticks(ind + 0.5) ax.set_xticklabels(x) ax.autoscale() ax.set_title( main, fontdict={'fontsize': 20}, ) plt.ylabel(y_lab, fontdict={'fontsize': 15}) plt.xlabel(x_lab, fontdict={'fontsize': 15}) plt.tick_params(axis="y", which="major", labelsize=10) plt.tick_params(axis="x", which="major", labelsize=10) ppl.bar(ax, np.arange(len(y)), y, grid="y") plt.tight_layout() print("The plot has been saved as ``out.png``") fig.savefig("out.png")
import numpy as np import pandas as pd from datetime import * from prettyplotlib import plt a001=pd.read_csv('A001.txt',index_col=[0],parse_dates=[0]) r001=pd.read_csv('R001.txt',index_col=[0],parse_dates=[0]) df=pd.DataFrame({'TAIEX':a001['cp'],'R001':r001['cp']}) ax=df.plot() plt.tight_layout() plt.show() ret1=pd.DataFrame({'TAIFEX':a001['cp'],'TotRet':r001['cp']}) ret1=(np.log(ret1/ret1.shift(1))*100).dropna() df=ret1.groupby(lambda x:x.year).sum() df['diff']=df['TotRet']-df['TAIFEX'] df r001['r1'] = np.log(r001['cp'] / r001['cp'].shift(1))*100 r001['r5'] = pd.stats.moments.rolling_sum(r001['r1'], 5) r001['r20'] = pd.stats.moments.rolling_sum(r001['r1'], 20) r001.dropna().head() ret = r001[['r1','r5','r20']].dropna()
def plot_multiple_streams(self, fig, ax, datasets, colors, axis_font={}, title_font={}, tick_font={}, width_in=8.3 , plot_qaqc=0, scatter=False, **kwargs): # Plot a timeseries with multiple y-axes using multiple streams from uFrame # # Acknowledgment: This function is based on code written by Jae-Joon Lee, # URL= http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/matplotlib/ # examples/pylab_examples/multiple_yaxis_with_spines.py?revision=7908&view=markup # # http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html if not axis_font: axis_font = axis_font_default if not title_font: title_font = title_font_default n_vars = len(datasets) if n_vars > 6: raise Exception('This code currently handles a maximum of 6 independent variables.') elif n_vars < 2: raise Exception('This code currently handles a minimum of 2 independent variables.') if scatter: kwargs['marker'] = 'o' # Generate the plot. # Use twinx() to create extra axes for all dependent variables except the first # (we get the first as part of the ax axes). y_axis = n_vars * [0] y_axis[0] = ax for i in range(1, n_vars): y_axis[i] = ax.twinx() ax.spines["top"].set_visible(False) self.make_patch_spines_invisible(y_axis[1]) self.set_spine_direction(y_axis[1], "top") # Define the axes position offsets for each 'extra' axis spine_directions = ["left", "right", "left", "right", "left", "right"] # Adjust the axes left/right accordingly if n_vars >= 4: if width_in < 8.3: # set axis location offset = [1.2, -0.2, 1.40, -0.40] # overwrite width l_mod = 0.3 r_mod = 0.8 else: offset = [1.10, -0.10, 1.20, -0.20] l_mod = 0.5 r_mod = 1.2 plt.subplots_adjust(left=l_mod, right=r_mod) elif n_vars == 3: offset = [1.20, -0.20, 1.40, -0.40] plt.subplots_adjust(left=0.0, right=0.7) count = 0 for i in range(2, n_vars): y_axis[i].spines[spine_directions[count+1]].set_position(("axes", offset[count])) self.make_patch_spines_invisible(y_axis[i]) self.set_spine_direction(y_axis[i], spine_directions[count+1]) count += 1 # Plot the data legend_handles = [] legend_labels = [] for ind, data in enumerate(datasets): xlabel = data['x_field'][0] ylabel = data['y_field'][0] xdata = data['x'][xlabel] ydata = data['y'][ylabel] # Handle the QAQC data qaqc = data['qaqc'][ylabel] if plot_qaqc >= 10: # Plot all of the qaqc flags results # qaqc_data = data['qaqc'][ylabel] pass elif plot_qaqc >= 1: # This is a case where the user wants to plot just one of the 9 QAQC tests ind = np.where(qaqc != plot_qaqc) qaqc[ind] = 0 else: qaqc = [] h, = y_axis[ind].plot(xdata, ydata, colors[ind], label=data['title'], **kwargs) if len(qaqc) > 0: bad_data = np.where(qaqc > 0) y_axis[ind].plot(xdata[bad_data], ydata[bad_data], marker='o', mfc='none', linestyle='None', markersize=6, markeredgewidth=2, mec='r') # Label the y-axis and set text color: # Been experimenting with other ways to handle tick labels with spines y_axis[ind].yaxis.get_major_formatter().set_useOffset(False) y_axis[ind].set_ylabel(ylabel.replace("_", " "), labelpad=10, **axis_font) y_axis[ind].yaxis.label.set_color(colors[ind]) y_axis[ind].spines[spine_directions[ind]].set_color(colors[ind]) if tick_font: labelsize = tick_font['labelsize'] y_axis[ind].tick_params(axis='y', labelsize=labelsize, colors=colors[ind]) legend_handles.append(h) legend_labels.append(data['title'][0:20]) self.get_time_label(ax, xdata) fig.autofmt_xdate() ax.legend(legend_handles, legend_labels) # ax.tick_params(axis='x', labelsize=10) # ax.set_title(title.replace("_", " "), y=1.05, **title_font) ax.grid(True) plt.tight_layout()
def plot_multiple_yaxes(self, fig, ax, xdata, ydata, colors, title, units=[], scatter=False, axis_font={}, title_font={}, tick_font={}, width_in=8.3, qaqc={}, **kwargs): # Plot a timeseries with multiple y-axes # # ydata is a python dictionary of all the data to plot. Key values are used as plot labels # # Acknowledgment: This function is based on code written by Jae-Joon Lee, # URL= http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/matplotlib/ # examples/pylab_examples/multiple_yaxis_with_spines.py?revision=7908&view=markup # # http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html if not axis_font: axis_font = axis_font_default if not title_font: title_font = title_font_default n_vars = len(ydata) if n_vars > 6: raise Exception('This code currently handles a maximum of 6 independent variables.') elif n_vars < 2: raise Exception('This code currently handles a minimum of 2 independent variables.') if scatter: kwargs['marker'] = 'o' # Generate the plot. # Use twinx() to create extra axes for all dependent variables except the first # (we get the first as part of the ax axes). y_axis = n_vars * [0] y_axis[0] = ax for i in range(1, n_vars): y_axis[i] = ax.twinx() ax.spines["top"].set_visible(False) self.make_patch_spines_invisible(y_axis[1]) self.set_spine_direction(y_axis[1], "top") # Define the axes position offsets for each 'extra' axis spine_directions = ["left", "right", "left", "right", "left", "right"] # Adjust the axes left/right accordingly if n_vars >= 4: if width_in < 8.3: # set axis location offset = [1.2, -0.2, 1.40, -0.40] # overwrite width l_mod = 0.3 r_mod = 0.8 else: offset = [1.10, -0.10, 1.20, -0.20] l_mod = 0.5 r_mod = 1.2 plt.subplots_adjust(left=l_mod, right=r_mod) elif n_vars == 3: offset = [1.20, -0.20, 1.40, -0.40] plt.subplots_adjust(left=0.0, right=0.7) count = 0 for i in range(2, n_vars): y_axis[i].spines[spine_directions[count+1]].set_position(("axes", offset[count])) self.make_patch_spines_invisible(y_axis[i]) self.set_spine_direction(y_axis[i], spine_directions[count+1]) count += 1 # Plot the data for ind, key in enumerate(ydata): y_axis[ind].plot(xdata[key], ydata[key], colors[ind], **kwargs) if len(qaqc[key]) > 0: bad_data = np.where(qaqc[key] > 0) y_axis[ind].plot(xdata[key][bad_data], ydata[key][bad_data], marker='o', mfc='none', linestyle='None', markersize=6, markeredgewidth=2, mec='r') # Label the y-axis and set text color: # Been experimenting with other ways to handle tick labels with spines y_axis[ind].yaxis.get_major_formatter().set_useOffset(False) y_axis[ind].set_ylabel(key.replace("_", " ") + ' (' + units[ind] + ')', labelpad=10, **axis_font) y_axis[ind].yaxis.label.set_color(colors[ind]) y_axis[ind].spines[spine_directions[ind]].set_color(colors[ind]) if tick_font: labelsize = tick_font['labelsize'] y_axis[ind].tick_params(axis='y', labelsize=labelsize, colors=colors[ind]) self.get_time_label(ax, xdata['time']) fig.autofmt_xdate() # ax.tick_params(axis='x', labelsize=10) ax.set_title(title.replace("_", " "), y=1.05, **title_font) ax.grid(True) plt.tight_layout()
def plot_multiple_xaxes(self, ax, xdata, ydata, colors, ylabel='Depth (m)', title='', title_font={}, axis_font={}, tick_font={}, width_in=8.3, **kwargs): # Acknowledgment: This function is based on code written by Jae-Joon Lee, # URL= http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/matplotlib/ # examples/pylab_examples/multiple_yaxis_with_spines.py?revision=7908&view=markup if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default n_vars = len(xdata) if n_vars > 6: raise Exception('This code currently handles a maximum of 6 independent variables.') elif n_vars < 2: raise Exception('This code currently handles a minimum of 2 independent variables.') # Generate the plot. # Use twiny() to create extra axes for all dependent variables except the first # (we get the first as part of the ax axes). x_axis = n_vars * [0] x_axis[0] = ax for i in range(1, n_vars): x_axis[i] = ax.twiny() ax.spines["top"].set_visible(False) self.make_patch_spines_invisible(x_axis[1]) self.set_spine_direction(x_axis[1], "top") offset = [1.10, -0.1, -0.20, 1.20] spine_directions = ["top", "bottom", "bottom", "top", "top", "bottom"] count = 0 for i in range(2, n_vars): x_axis[i].spines[spine_directions[count]].set_position(("axes", offset[count])) self.make_patch_spines_invisible(x_axis[i]) self.set_spine_direction(x_axis[i], spine_directions[count]) count += 1 # Adjust the axes left/right accordingly if n_vars >= 4: plt.subplots_adjust(bottom=0.2, top=0.8) elif n_vars == 3: plt.subplots_adjust(bottom=0.0, top=0.8) # Label the y-axis: ax.set_ylabel(ylabel, **axis_font) for ind, key in enumerate(xdata): x_axis[ind].plot(xdata[key], ydata, colors[ind], **kwargs) # Label the x-axis and set text color: x_axis[ind].set_xlabel(key.replace("_", " "), **axis_font) x_axis[ind].xaxis.label.set_color(colors[ind]) x_axis[ind].spines[spine_directions[ind]].set_color(colors[ind]) for obj in x_axis[ind].xaxis.get_ticklines(): # `obj` is a matplotlib.lines.Line2D instance obj.set_color(colors[ind]) obj.set_markeredgewidth(2) for obj in x_axis[ind].xaxis.get_ticklabels(): obj.set_color(colors[ind]) ax.invert_yaxis() ax.grid(True) if tick_font: ax.tick_params(**tick_font) ax.set_title(title.replace("_", " "), y=1.23, **title_font) plt.tight_layout()
def plot_multiple_xaxes(self, ax, xdata, ydata, colors, ylabel='Depth (m)', title='', title_font={}, axis_font={}, tick_font={}, width_in=8.3, **kwargs): # Acknowledgment: This function is based on code written by Jae-Joon Lee, # URL= http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/matplotlib/ # examples/pylab_examples/multiple_yaxis_with_spines.py?revision=7908&view=markup if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default n_vars = len(xdata) if n_vars > 6: raise Exception( 'This code currently handles a maximum of 6 independent variables.' ) elif n_vars < 2: raise Exception( 'This code currently handles a minimum of 2 independent variables.' ) # Generate the plot. # Use twiny() to create extra axes for all dependent variables except the first # (we get the first as part of the ax axes). x_axis = n_vars * [0] x_axis[0] = ax for i in range(1, n_vars): x_axis[i] = ax.twiny() ax.spines["top"].set_visible(False) self.make_patch_spines_invisible(x_axis[1]) self.set_spine_direction(x_axis[1], "top") offset = [1.10, -0.1, -0.20, 1.20] spine_directions = ["top", "bottom", "bottom", "top", "top", "bottom"] count = 0 for i in range(2, n_vars): x_axis[i].spines[spine_directions[count]].set_position( ("axes", offset[count])) self.make_patch_spines_invisible(x_axis[i]) self.set_spine_direction(x_axis[i], spine_directions[count]) count += 1 # Adjust the axes left/right accordingly if n_vars >= 4: plt.subplots_adjust(bottom=0.2, top=0.8) elif n_vars == 3: plt.subplots_adjust(bottom=0.0, top=0.8) # Label the y-axis: ax.set_ylabel(ylabel, **axis_font) for ind, key in enumerate(xdata): x_axis[ind].plot(xdata[key], ydata, colors[ind], **kwargs) # Label the x-axis and set text color: x_axis[ind].set_xlabel(key.replace("_", " "), **axis_font) x_axis[ind].xaxis.label.set_color(colors[ind]) x_axis[ind].spines[spine_directions[ind]].set_color(colors[ind]) for obj in x_axis[ind].xaxis.get_ticklines(): # `obj` is a matplotlib.lines.Line2D instance obj.set_color(colors[ind]) obj.set_markeredgewidth(2) for obj in x_axis[ind].xaxis.get_ticklabels(): obj.set_color(colors[ind]) ax.invert_yaxis() ax.grid(True) if tick_font: ax.tick_params(**tick_font) ax.set_title(title.replace("_", " "), y=1.23, **title_font) plt.tight_layout()
def plot_multiple_yaxes(self, fig, ax, xdata, ydata, colors, title, units=[], scatter=False, axis_font={}, title_font={}, tick_font={}, width_in=8.3, qaqc={}, **kwargs): # Plot a timeseries with multiple y-axes # # ydata is a python dictionary of all the data to plot. Key values are used as plot labels # # Acknowledgment: This function is based on code written by Jae-Joon Lee, # URL= http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/matplotlib/ # examples/pylab_examples/multiple_yaxis_with_spines.py?revision=7908&view=markup # # http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html if not axis_font: axis_font = axis_font_default if not title_font: title_font = title_font_default n_vars = len(ydata) if n_vars > 6: raise Exception( 'This code currently handles a maximum of 6 independent variables.' ) elif n_vars < 2: raise Exception( 'This code currently handles a minimum of 2 independent variables.' ) if scatter: kwargs['marker'] = 'o' # Generate the plot. # Use twinx() to create extra axes for all dependent variables except the first # (we get the first as part of the ax axes). y_axis = n_vars * [0] y_axis[0] = ax for i in range(1, n_vars): y_axis[i] = ax.twinx() ax.spines["top"].set_visible(False) self.make_patch_spines_invisible(y_axis[1]) self.set_spine_direction(y_axis[1], "top") # Define the axes position offsets for each 'extra' axis spine_directions = ["left", "right", "left", "right", "left", "right"] # Adjust the axes left/right accordingly if n_vars >= 4: if width_in < 8.3: # set axis location offset = [1.2, -0.2, 1.40, -0.40] # overwrite width l_mod = 0.3 r_mod = 0.8 else: offset = [1.10, -0.10, 1.20, -0.20] l_mod = 0.5 r_mod = 1.2 plt.subplots_adjust(left=l_mod, right=r_mod) elif n_vars == 3: offset = [1.20, -0.20, 1.40, -0.40] plt.subplots_adjust(left=0.0, right=0.7) count = 0 for i in range(2, n_vars): y_axis[i].spines[spine_directions[count + 1]].set_position( ("axes", offset[count])) self.make_patch_spines_invisible(y_axis[i]) self.set_spine_direction(y_axis[i], spine_directions[count + 1]) count += 1 # Plot the data for ind, key in enumerate(ydata): y_axis[ind].plot(xdata[key], ydata[key], colors[ind], **kwargs) if len(qaqc[key]) > 0: bad_data = np.where(qaqc[key] > 0) y_axis[ind].plot(xdata[key][bad_data], ydata[key][bad_data], marker='o', mfc='none', linestyle='None', markersize=6, markeredgewidth=2, mec='r') # Label the y-axis and set text color: # Been experimenting with other ways to handle tick labels with spines y_axis[ind].yaxis.get_major_formatter().set_useOffset(False) y_axis[ind].set_ylabel(key.replace("_", " ") + ' (' + units[ind] + ')', labelpad=10, **axis_font) y_axis[ind].yaxis.label.set_color(colors[ind]) y_axis[ind].spines[spine_directions[ind]].set_color(colors[ind]) if tick_font: labelsize = tick_font['labelsize'] y_axis[ind].tick_params(axis='y', labelsize=labelsize, colors=colors[ind]) self.get_time_label(ax, xdata['time']) fig.autofmt_xdate() # ax.tick_params(axis='x', labelsize=10) ax.set_title(title.replace("_", " "), y=1.05, **title_font) ax.grid(True) plt.tight_layout()
def plot_multiple_streams(self, fig, ax, datasets, colors, axis_font={}, title_font={}, tick_font={}, width_in=8.3, plot_qaqc=0, scatter=False, **kwargs): # Plot a timeseries with multiple y-axes using multiple streams from uFrame # # Acknowledgment: This function is based on code written by Jae-Joon Lee, # URL= http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/matplotlib/ # examples/pylab_examples/multiple_yaxis_with_spines.py?revision=7908&view=markup # # http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html if not axis_font: axis_font = axis_font_default if not title_font: title_font = title_font_default n_vars = len(datasets) if n_vars > 6: raise Exception( 'This code currently handles a maximum of 6 independent variables.' ) elif n_vars < 2: raise Exception( 'This code currently handles a minimum of 2 independent variables.' ) if scatter: kwargs['marker'] = 'o' # Generate the plot. # Use twinx() to create extra axes for all dependent variables except the first # (we get the first as part of the ax axes). y_axis = n_vars * [0] y_axis[0] = ax for i in range(1, n_vars): y_axis[i] = ax.twinx() ax.spines["top"].set_visible(False) self.make_patch_spines_invisible(y_axis[1]) self.set_spine_direction(y_axis[1], "top") # Define the axes position offsets for each 'extra' axis spine_directions = ["left", "right", "left", "right", "left", "right"] # Adjust the axes left/right accordingly if n_vars >= 4: if width_in < 8.3: # set axis location offset = [1.2, -0.2, 1.40, -0.40] # overwrite width l_mod = 0.3 r_mod = 0.8 else: offset = [1.10, -0.10, 1.20, -0.20] l_mod = 0.5 r_mod = 1.2 plt.subplots_adjust(left=l_mod, right=r_mod) elif n_vars == 3: offset = [1.20, -0.20, 1.40, -0.40] plt.subplots_adjust(left=0.0, right=0.7) count = 0 for i in range(2, n_vars): y_axis[i].spines[spine_directions[count + 1]].set_position( ("axes", offset[count])) self.make_patch_spines_invisible(y_axis[i]) self.set_spine_direction(y_axis[i], spine_directions[count + 1]) count += 1 # Plot the data legend_handles = [] legend_labels = [] for ind, data in enumerate(datasets): xlabel = data['x_field'][0] ylabel = data['y_field'][0] xdata = data['x'][xlabel] ydata = data['y'][ylabel] # Handle the QAQC data qaqc = data['qaqc'][ylabel] if plot_qaqc >= 10: # Plot all of the qaqc flags results # qaqc_data = data['qaqc'][ylabel] pass elif plot_qaqc >= 1: # This is a case where the user wants to plot just one of the 9 QAQC tests ind = np.where(qaqc != plot_qaqc) qaqc[ind] = 0 else: qaqc = [] h, = y_axis[ind].plot(xdata, ydata, colors[ind], label=data['title'], **kwargs) if len(qaqc) > 0: bad_data = np.where(qaqc > 0) y_axis[ind].plot(xdata[bad_data], ydata[bad_data], marker='o', mfc='none', linestyle='None', markersize=6, markeredgewidth=2, mec='r') # Label the y-axis and set text color: # Been experimenting with other ways to handle tick labels with spines y_axis[ind].yaxis.get_major_formatter().set_useOffset(False) y_axis[ind].set_ylabel(ylabel.replace("_", " "), labelpad=10, **axis_font) y_axis[ind].yaxis.label.set_color(colors[ind]) y_axis[ind].spines[spine_directions[ind]].set_color(colors[ind]) if tick_font: labelsize = tick_font['labelsize'] y_axis[ind].tick_params(axis='y', labelsize=labelsize, colors=colors[ind]) legend_handles.append(h) legend_labels.append(data['title'][0:20]) self.get_time_label(ax, xdata) fig.autofmt_xdate() ax.legend(legend_handles, legend_labels) # ax.tick_params(axis='x', labelsize=10) # ax.set_title(title.replace("_", " "), y=1.05, **title_font) ax.grid(True) plt.tight_layout()
def plot_time_series(self, fig, is_timeseries, ax, x, y, fill=False, title='', xlabel='', ylabel='', title_font={}, axis_font={}, tick_font={}, scatter=False, qaqc=[], events={}, **kwargs): if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default if scatter: ppl.scatter(ax, x, y, **kwargs) else: h = ppl.plot(ax, x, y, **kwargs) if is_timeseries: self.get_time_label(ax, x) fig.autofmt_xdate() else: ax.set_xlabel(xlabel.replace("_", " "), **axis_font) if ylabel: ax.set_ylabel(ylabel.replace("_", " "), **axis_font) if title: ax.set_title(title.replace("_", " "), **title_font) ax.grid(True) if fill: miny = min(ax.get_ylim()) if not scatter: ax.fill_between(x, y, miny + 1e-7, facecolor=h[0].get_color(), alpha=0.15) else: ax.fill_between(x, y, miny + 1e-7, facecolor=axis_font_default['color'], alpha=0.15) if events: ylim = ax.get_ylim() for event in events['events']: time = datestr2num(event['start_date']) x = np.array([time, time]) h = ax.plot(x, ylim, '--', label=event['class']) legend = ax.legend() if legend: for label in legend.get_texts(): label.set_fontsize(10) if len(qaqc) > 0: bad_data = np.where(qaqc > 0) h = ppl.plot(ax, x[bad_data], y[bad_data], marker='o', mfc='none', linestyle='None', markersize=6, markeredgewidth=2, mec='r') # plt.tick_params(axis='both', which='major', labelsize=10) if tick_font: ax.tick_params(**tick_font) plt.tight_layout()