def gen_bars(data, headers, datasets, methods): """ Description: Inputs: Outputs: """ width = 0.5 x = np.arange(0, 16, 2) labels_x = datasets.copy() labels_x.insert(0,"") fig, ax = plt.subplots() bar1 = ax.bar(x - (0.3 + width/2), data[0,:], width, label = methods[0]) add_labels(ax, bar1) if (len(methods) > 1): bar2 = ax.bar(x , data[1,:], width, label = methods[1]) add_labels(ax, bar2) if (len(methods) > 2): bar3 = ax.bar(x + (0.3 + width/2), data[1,:], width, label = methods[2]) add_labels(ax, bar3) ax.set_ylabel(metric) ax.set_xlabel("Dataset") ax.set_xticklabels(labels_x) ax.set_title(metric + " Across Datasets") ax.legend(bbox_to_anchor=(1, 1.15), fancybox=True, framealpha=0.5)
def plotmeshval(val,ixmin=None,ixmax=None,iymin=None,iymax=None, r_min=None,r_max=None,z_min=None,z_max=None,title=None,units=None, block=True): """ plotmeshval(val,ixmin=<int>,ixmax=<int>,iymin=<int>,iymax=<int> title=<string>,units=<string>,block=<True|False>) Display 2-D quantity using polyfill. where ixmin, ixmax, iymin, and iymax are integer variables or expressions used to plot a portion of the grid. title is used as both the title and the figure name. Units are displayed in the side colorbar. Block default is True. The plot axis limits may be specified with r_rmin,r_max,z_min,z_max. """ if ixmin == None: ixmin = com.nxomit if ixmax == None: ixmax = (com.nxm-1) if iymin == None: iymin = 0 if iymax == None: iymax = (com.ny-1) if r_min == None: r_min = com.rm.min() if r_max == None: r_max = com.rm.max() if z_min == None: z_min = com.zm.min() if z_max == None: z_max = com.zm.max() rcdefaults() if title == None: title='Uedge' fig, ax = plt.subplots() verts = np.array([]) z = np.array([]) for ix in range(ixmax-ixmin+1): for iy in range(iymax-iymin+1): v = [] v.append([com.rm[ix,iy,1],com.zm[ix,iy,1]]) v.append([com.rm[ix,iy,2],com.zm[ix,iy,2]]) v.append([com.rm[ix,iy,4],com.zm[ix,iy,4]]) v.append([com.rm[ix,iy,3],com.zm[ix,iy,3]]) verts = np.append(verts,v) z = np.append(z,val[ix,iy]) verts = verts.reshape(len(z),4,2) ax.set_title(title) ax.set_ylabel('Z (m)') ax.set_xlabel('R (m)') ax.set_aspect('equal') coll = PolyCollection(verts,array=z,cmap=cm.jet,edgecolors='face') ax.add_collection(coll) ax.autoscale_view() cbar = fig.colorbar(coll,ax=ax) #if units != None: cbar.ax.set_ylabel(units,rotation=-90,va='bottom') if units != None: cbar.ax.set_ylabel(units,va='bottom') plt.ylim(z_min,z_max) plt.xlim(r_min,r_max) #plt.show(block=block) plt.ion() plt.show() plt.pause(0.001)
def club_tags(unencoded_clubs_list): """ Creates a bar graph showing of the number of occurrances of each possible club tag. By using a dictionary to count club tag occurrances, the function then creates a matplotlib bar graph using numpy representations of the dictionary information. The graph is formatted and pushed as a Response type for view on the server. Returns: -------- Response The graph """ club_dict = {} for clubs in unencoded_clubs_list: for tag in clubs.get_category(): if tag in club_dict: club_dict[tag] = club_dict[tag] + 1 else: club_dict[tag] = 1 x = np.zeros(len(club_dict)) index_counter = 0 for tag in club_dict: x[index_counter] = club_dict.get(tag) index_counter = index_counter + 1 fig = plt.figure() ax = fig.add_subplot() bar = ax.bar(np.arange(len(club_dict)), x) labels = club_dict.keys() ax.set_xticks(np.arange(len(club_dict))) ax.set_xticklabels(labels, rotation='45', ha='right') ax.set_xlabel('Club Tags') ax.set_ylabel('Number of Occurrances') ax.set_title('Number of Club Tag Occurrances') for rect in bar: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), textcoords="offset points", ha='center', va='bottom') plt.tight_layout() output = io.BytesIO() FigureCanvas(fig).print_png(output) return Response(output.getvalue(), mimetype='image/png')
def clubs_per_user(user_list): """ Creates a bar graph of the number of clubs per user. Using a dictionary to gather each user's name and the number of club each user is in, numpy representations of the data is used to create a matplotlib bar graph. The graph is then formatted and pushed for view on the server. Returns: -------- Response The graph """ user_club_dict = {} for user in user_list: name = user.get_user_name() user_club_dict[name] = len(user.get_user_clubs()) x = np.zeros(len(user_club_dict)) index_counter = 0 for user in user_club_dict: x[index_counter] = user_club_dict.get(user) index_counter = index_counter + 1 fig = plt.figure() ax = fig.add_subplot() bar = ax.bar(np.arange(len(user_club_dict)), x) labels = user_club_dict.keys() ax.set_xticks(np.arange(len(user_club_dict))) ax.set_xticklabels(labels, rotation='45', ha='right') ax.set_xlabel('User Name') ax.set_ylabel('Number of Clubs') ax.set_title('Number of Clubs per User') for rect in bar: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), textcoords="offset points", ha='center', va='bottom') plt.tight_layout() output = io.BytesIO() FigureCanvas(fig).print_png(output) return Response(output.getvalue(), mimetype='image/png')
def plot_graph(train_history, label_col, mode): # Obtain scores from history loss = train_history.history['loss'] #List val_loss = train_history.history['val_loss'] #Check if binary or multiclass problem to obtain correct metrics if mode == 0: acc = train_history.history['binary_accuracy'] val_acc = train_history.history['val_binary_accuracy'] else: acc = train_history.history['categorical_accuracy'] val_acc = train_history.history['val_categorical_accuracy'] # Plot loss scores sns.set_style("whitegrid") fig, ax = plt.subplots(1, 1) ax.plot(loss, label = "Loss") ax.plot(val_loss, label = "Validation Loss") ax.set_title('Model Loss') ax.legend(loc = "upper right") ax.set_xlim([0, 100]) ax.set_ylabel("Loss") ax.set_xlabel("Epochs") ax.minorticks_on() ax.grid(b=True, which='major') ax.grid(b=True, which='minor') plt.savefig(results_dir + '/' + label_col + '_loss.png') plt.show() # Plot accuracy scores fig, ax = plt.subplots(1, 1) ax.plot(acc, label = "Accuracy") ax.plot(val_acc, label = "Validation Accuracy") ax.set_title('Model Accuracy') ax.legend(loc = "lower right") ax.set_xlim([0, 100]) ax.grid(b=True, which='major') ax.grid(b=True, which='minor') ax.set_ylabel("Accuracy") ax.set_xlabel("Epochs") ax.minorticks_on() plt.savefig(results_dir + '/' + label_col + '_acc.png') plt.show() return 0
def draw(self, output_name, x, y_list): plt.autoscale(True, 'both', True) fig = plt.figure(figsize=(100,10), dpi=300) lines = [] ax = fig.add_subplot(111) for y in y_list: ys = y.split(',') l = None if len(ys) > 1: l = ys[1] y = ys[0].replace('.','') line, = ax.plot(self.data[x], self.data[y], '-', label=l) lines.append(line) ax.set_xlabel(x) # handles, labels = ax.get_legend_handles_labels() ax.legend() plt.savefig(output_name, bbox_inches='tight') plt.clf()
def draw(self, output_name, x, y_list): plt.autoscale(True, 'both', True) fig = plt.figure(figsize=(100, 10), dpi=300) lines = [] ax = fig.add_subplot(111) for y in y_list: ys = y.split(',') l = None if len(ys) > 1: l = ys[1] y = ys[0].replace('.', '') line, = ax.plot(self.data[x], self.data[y], '-', label=l) lines.append(line) ax.set_xlabel(x) # handles, labels = ax.get_legend_handles_labels() ax.legend() plt.savefig(output_name, bbox_inches='tight') plt.clf()
if(float(cont[j].split(" ")[-1]) < 0.0): a = 0 else: a = float(cont[j].split(" ")[-1]) yAxis[i-start].append(a*10**(-7)) x = xAxis #y = np.arange(50, 80.001, 0.75) y = np.arange(50+(start)*0.75, 50+(end)*0.75, 0.75) X, Y = np.meshgrid(x, y) if(sys.argv[1] == "reducedElectricField"): levels = [i for i in range(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))] elif(sys.argv[1] == "eDens"): levels = [i/10.0 for i in range(int(sys.argv[2]), int(sys.argv[3]))]#EDENS else: levels = [-1, 0, 1]#CHEMISTRY Z = yAxis fig = plt.figure() ax = fig.add_subplot(111) ax.tick_params(labelsize=40) ax.set_xticks([-4, -3, -2, -1, 0]) CS = ax.contourf(X, Y, Z, levels) ax.set_ylabel("Altitude (km)", fontsize=40) ax.set_xlabel(r"logarithmic Time ($\mathrm{s}$)", fontsize=40) #ax.set_xlabel(r"Time ($\mathrm{ms}$)", fontsize=40) cb = plt.colorbar(CS) cb.ax.tick_params(labelsize=40) #plt.savefig("{}.png".format(sys.argv[1])) plt.show()
total += x * y new[i][j] = total return new elif self.m == other.n: return other * self else: raise ValueError( "Cannot multiply two matrices of incompatable dimensions") if __name__ == "__main__": fig = plt.figure() ax = fig.gca(projection="3d") v3 = AVector("sin(x)", "cos(y)", "tan(z)") v3.quiver(ax) a, b, c = v3.evaluate(1, 1, 1) print(a, b, c) ax.set_xlabel("sin(x)") ax.set_ylabel("cos(y)") ax.set_zlabel("tan(z)") plt.show()
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) r = z**2 + 1 x = r * np.sin(theta) y = r * np.cos(theta) ax.plot(r_ECI[:, 0] / 1000, r_ECI[:, 1] / 1000, r_ECI[:, 2] / 1000, label='Orbital Position', color='k') # Sphere to represent Earth # Make data u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x1 = rEarth / 1000 * np.outer(np.cos(u), np.sin(v)) y1 = rEarth / 1000 * np.outer(np.sin(u), np.sin(v)) z1 = rEarth / 1000 * np.outer(np.ones(np.size(u)), np.cos(v)) # Plot the surface ax.plot_surface(x1, y1, z1, cmap='GnBu') # Legend and labels ax.legend() ax.set_xlabel('X Pos (km)') ax.set_ylabel('Y Pos (km)') ax.set_zlabel('Z Pos (km)') ax.set_aspect('equal') plt.show()
cont = f.readlines() f.close() f = open(filesB[i], "r") cont2 = f.readlines() f.close() xAxis=[] for j in range(0,len(cont)/300,10): #xAxis.append(np.log10(float(cont[j].split(" ")[0]))) xAxis.append(1000*float(cont[j].split(" ")[0])) yAxis[i].append(int(int(cont[j].split(" ")[-1]) == 0 and int(cont2[j].split(" ")[-1]) == 0)) x = xAxis y = np.arange(50+(start)*0.75, 50+(end)*0.75, 0.75) X, Y = np.meshgrid(x, y) levels = [-1,0,1] Z = yAxis fig = plt.figure() ax = fig.add_subplot(111) ax.tick_params(labelsize=40) #ax.set_xticks([-4, -3, -2, -1, 0]) CS = ax.contourf(X, Y, Z, levels) ax.set_ylabel("Altitude (km)", fontsize=40) #ax.set_xlabel(r"logarithmic Time ($\mathrm{s}$)", fontsize=40) ax.set_xlabel(r"Time ($\mathrm{ms}$)", fontsize=40) #cb = plt.colorbar(CS) #cb.ax.tick_params(labelsize=40) #plt.savefig("{}.png".format(sys.argv[1])) plt.show()
import matplotlib.pyplot as plt from matplotlib import rcParams from matplotlib import axes as ax from mpl_toolkits.mplot3d import Axes3D import numpy as np x, y, z, vx, vy, vz = np.loadtxt('./coordAa.dat.txt', unpack=True) print(len(x)) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(x, y, z, c='r', marker='.', s=0.1) #Axes3D.scatter(x,y,z) ax.set_xlabel('X [kpc]') ax.set_ylabel('Y [kpc]') ax.set_zlabel('Z [kpc]') #plt.axis([-1500., 1500., -1500., 1500, -1500, 1500]) ax.set_xlim3d(-1500, 1500) ax.set_ylim3d(-1500, 1500) ax.set_zlim3d(-1500, 1500) plt.show() radius = sorted([ np.sqrt(i**2 + j**2 + k**2) for i, j, k in zip(x, y, z) if np.sqrt(i**2 + j**2 + k**2) <= 300 ]) max_radius = max(radius) min_radius = min(radius)
import numpy as np import matplotlib.pyplot as plt import matplotlib.axes as ax import pylab # change to proper directory os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis') # load file, select proper date range, convert row to numeric dtypes hpc = pd.read_csv('household_power_consumption.txt', sep=';', index_col=['Date'], usecols=['Global_active_power', 'Date']) hpc = hpc['1/2/2007':'2/2/2007'].convert_objects(convert_numeric=True) # create plotting variables y = pd.value_counts(hpc.Global_active_power, bins=np.arange(0, 8, 0.5), sort=False) index = y.index fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.bar(index, y, width=0.5, color='r') ax.set_xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Frequency') ax.set_title('Global Active Power') pylab.show() # hpc[hpc['Global_active_power'] > 4]
def create_bar_graph(data=[[[1, 2], [10, 20]]], semilog=False, add_bar_labels=True, title='Insert Fancy Title', add_legend=False, bar_colors=[], legend_labels=[]): import matplotlib.patches as mpatches from collections import deque if not bar_colors: bar_color_deque = deque([ '#1395ba', '#a2b86c', '#ebc844', '#f16c20', '#c02e1d', '#0d3c55', '#ecaa38', '#117899', '#d94e1f', '#5ca793', '#ef8b2c', '#0f5b78' ]) else: bar_color_deque = deque(bar_colors) width = 0.33 xs = data[0][0] legend_labels_queue = deque(legend_labels) handles = [] if len(data) > 1: width = 0.33 * 2 / len(data) #plot comparison from multiple archives all_unique_x = {} for series in data: for size in series[0]: all_unique_x[size] = True ind = np.arange(len(all_unique_x.keys())) rect_refs = [] fig, ax = plt.subplots() bar_shift = width / 2 #plot individual bars to allow for sparse data plots for series in data: if len(series) > 2: label = series[2] color = bar_color_deque.popleft() if legend_labels: legend_label = legend_labels_queue.popleft() else: legend_label = label handles.append(mpatches.Patch(color=color, label=legend_label)) index = 0 labeled_yet = False for ex in sorted(all_unique_x.keys()): for i in range(0, len(series[0])): if series[0][i] == ex: if 'label' in locals() and not labeled_yet: rects = ax.bar(index + bar_shift, series[1][i], width, color=color, label=label) labeled_yet = True else: rects = ax.bar(index + bar_shift, series[1][i], width, color=color) rect_refs.append(rects[0]) if add_bar_labels: bar_label(ax, rects, semilog) index += 1 bar_shift += width if semilog: ax.set_yscale('log') ax.set_xticks(ind + 0.59 - 0.045 * len(data)) if add_legend: plt.legend(handles=handles, loc=2) else: color = bar_color_deque.popleft() ys = data[0][1] ind = np.arange(len(xs)) fig, ax = plt.subplots() rects = ax.bar(ind + width, ys, color=color) ax.set_xticks(ind + width * 2) if semilog: ax.set_yscale('log') if add_bar_labels: bar_label(ax, rects, semilog) fig.set_size_inches(15, 8) ax.set_xticklabels(xs, rotation=0) ax.set_title(title) ax.set_xlabel("Object Size (Bytes)") ax.set_ylabel('MB/s') plt.show() plt.savefig('foo.png') return
# import needed libraries import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.axes as ax import pylab # change to proper directory os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis') # load file, select proper date range, convert row to numeric dtypes hpc = pd.read_csv('household_power_consumption.txt', sep=';', index_col=['Date'], usecols=['Global_active_power', 'Date']) hpc = hpc['1/2/2007':'2/2/2007'].convert_objects(convert_numeric=True) # create plotting variables y = pd.value_counts(hpc.Global_active_power, bins=np.arange(0, 8, 0.5), sort=False) index = y.index fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.bar(index, y, width=0.5, color='r') ax.set_xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Frequency') ax.set_title('Global Active Power') pylab.show() # hpc[hpc['Global_active_power'] > 4]
# In[49]: t=25 #days def f(x, y): return np.sin(np.sqrt(x ** 2 + y ** 2)) x = np.linspace(-7, 7, 30) y = np.linspace(-5, 5, 30) X, Y = np.meshgrid(x, y) Z = f(X, Y) fig = plt.figure() ax = plt.axes(projection='3d') ax.contour3D(X, Y, Z, 50, cmap='binary') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z'); # ## Models of bumblebee population growth over many seasons # # ### Infinite resources (exponential growth) # Assuming infinite resources in the environment (probably never the case in nature for bees) and nothing systematically killing populations, bumblebee populations will increase at $\frac{dx}{dt}= kx$, which solves to $x(t)= Ce^{kt}$. k is just some growth constant. # # ### Finite resources (logistic growth) # With finite resources, bee populations will grow according to $\frac {dx}{dt}=kx(1-\frac{x}{C})$, where k is a growth constant and C is the carrying capacity of the environment. An analytic solution is $x=\frac{C}{1+Ae^{-kt}}$ where $A=\frac{C-X_{0}}{X_{0}}$. # # ### Finite resources + big bad pesticides. # Now let's introduce neonicotinoid into the equation once the bees have reached carrying capacity. These pesticides both kill bees directly and decrease their reproductive capacity, so here I'll have a lower k as well as some constant d representing a proportion of bee deaths. # This scenario is represented by the differential equation $\frac{dx}{dt}= (k-d)x$, which solves to $x(t)= Ce^{(k-d)t}$
imgh = np.reshape(img, nx*ny) imgh1 = np.reshape(img_mask1, nx1*ny1) df=36*38 dof=chi2_distance(imgh,imgh1) chi2_distance(imgh, imght[0,:]) chi2_distance(imgh, imght[1,:]) chi2_distance(imgh, imght[2,:]) chi2_distance(imgh, imght[3,:]) chi2_distance(imgh, imght[4,:]) chi2_distance(imgh, imght[5,:]) chi2_distance(imgh, imght[6,:]) chi_sfh=np.array([502.5312995308081,580.45729191839803,204.19667370317001,518.27719309677684,1534.8645907539676,1555.9265125639893]) weights = np.ones_like(chi_sfh)/float(len(chi_sfh)) fig, ax = plt.subplots(1, 1) mean, var, skew, kurt = chi2.stats(df, moments='mvsk') x = np.linspace(chi2.ppf(0.01, df), chi2.ppf(0.99, df), 100) xu = np.linspace(chi2.ppf(0.01, dof), chi2.ppf(0.99, dof), 100) ax.axvline(x=dof/df,color='k', linestyle='dashed',lw=4, label='UGC11680NED01 $\chi^2$') ax.hist(chi_sfh/df,bins=10, normed=False,weights=weights, histtype='step', lw=3,label='Mass $10<\log (M/M_{\odot})<11$ , color $2<g-r<3$') ax.legend(loc='best', frameon=False) ax.set_ylabel('Probability density $\chi ^2$') ax.set_xlabel('$x$') plt.show()