def PlotTemperature(filename, size=20, tSpace=np.linspace(0, 240 * 10, 11)): #Get the data back from file Data = pickle.load(open(filename, "rb")) #Zeit in seconds time = np.array(Data, dtype=float)[:, 0] / 1000 #print(time) #Temperatur in Celsius temperature = np.array(Data, dtype=float)[:, 1] #print(temperature) plt.figure(figsize=(12, 8)) plt.plot(time, temperature, '.', label='Temperature') plt.xlabel('Time [s]', fontsize=size) plt.ylabel(r"Temperature [$^\circ C$]", fontsize=size) #Set tick fontsize plt.xticks(fontsize=size) plt.yticks(fontsize=size) plt.label(fontsize='xx-large') ySpace = np.linspace( np.amin(temperature) - 0.5, np.amax(temperature) + 0.5, 500) for t in tSpace: plt.plot(t * np.ones_like(ySpace), ySpace, ',g') plt.savefig(filename.split('.')[0] + '.PNG') plt.show()
def plot_result(self, y_true, y_pred): y_true.plot() plt.label("Actual") y_red.plot() plt.label("Predict") plt.title("Forecaste ARIMA Model") plt.show()
def plot_learning_curve(x, scores, figure_file): running_avg = np.zeros(len(scores)) for i in range(len(scores)): running_avg[i] = np.mean(scores[max(0, i - 100):i + 1]) plt.plot(x, running_avg) plt.label('Running average of previous 100 scores') plt.savefig(figure_file)
def MakePlot(self): X = self.topics_list Y = self.avg_cosine_similarity_list plt.plot(X, Y) plt.xlabel("The number of clusters") plt.ylabel("The Avg cosine similarity score") plt.label( "The number of culsters with the Avg cosine similarity score list") plt.show()
def plot_test_error(test_x,test_y,w_r,w_ml,best_lambda): error_r = compute_error_r(test_x,test_y,w_ml,best_lambda) error_ml = compute_error_ml(test_x,test_y,w_ml) plt.plot(error_r,'r') plt.label("Test Error W_r") plt.plot(error_ml,'b') plt.label("Test Error W_ml") plt.title("Test Error") plt.xlabel("Timestem") plt.ylabel("Prediction Cost") plt.show()
def plot_cv_hours(cv, x): plt.clf() plt.xlabel("Hours") plt.ylabel("CV of Hours") axes = plt.gca() my_xticks = [ "00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00" ] plt.xticks(x, my_xticks) axes.set_xlim([0, 23]) index = np.arange(24) bar_width = 0.25 plt.label("CV of Hours and Hours") plt.bar(index, cv, bar_width, align='edge') plt.legend(['CV'])
def main(): inception_res = load_inception_results() resnet_res = load_resnet_results() vgg16_res = load_vgg16_results() vgg19_res = load_vgg19_results() results = [inception_res, resnet_res, vgg16_res, vgg19_res] colors = cm.rainbow(np.linspace(0, 1, len(results))) for result, c in zip(results, colors): result = [random.uniform(0.5, 0.6)] + result y = range(len(result)) custom_plot(y, np.asarray(result), color=c, lw=3) plt.title("Accuracies") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.label(label = "yp") plt.show()
def f(x): temp = [x] c=0 while x != 1: if x%2==0: x = x//2 else: x = (x*3)+1 c+=1 temp.append(c) return temp xcords = [] ycords = [] count = 1 big = [] while count <=100000: big.append(f(count)) xcords.append(f(count)[0]) ycords.append(f(count)[1]) count+=1 plt.scatter(xcords,ycords, s=0.0005) plt.ylabel('Number of Steps') plt.xlabel('Input Number') plt.label('Colatz Algorithm Steps') plt.show()
# Scatter plots of data for visual inspection of sensitivity N_plot=100 N_prms = len(jpdf) N_terms = N_prms//2 Xs=jpdf.sample(N_plot,sample_method='R').transpose() Zs = Xs[:, :N_terms] # Split X in two vectors for X and W Ws = Xs[:, N_terms:] Ys = linear_model(Ws, Zs) scatter = plt.figure('Scatter plots') for k in range(N_terms): plt.subplot(2, N_terms, k + 1) _=plt.plot(Zs[:, k], Ys[:], '.') if k==0 : plt.label('Y') plt.xlabel('Z{}'.format(k+1)) plt.ylim([-150, 150]) plt.subplot(2, N_terms, k + 1 + N_terms) _=plt.plot(Ws[:, k], Ys[:], '.') if k==0 : plt.label('Y') plt.xlabel('W{}'.format(k+1)) plt.ylim([-150, 150]) scatter.tight_layout() # end scatter plots of data for visual inspection of sensitivity # sensitivity analytical values Sa, Szw, Sta = analytic_sensitivity_coefficients(zm, wm)
import matplotlib.pyplot as plt import numpy as np import pandas as pd # read the data into a dataframe class stock_df = pd.read_csv("../../data/stocks.csv") print(stock_df) # multiple graphs in one single line graph stock_df.plot(x='Date', y=['AAPL', 'sp500'], linewidth=3) plt.label('Price') plt.title('Stock Prices') plt.grid()
import matplotlib.pyplot as plt # imports pyplot as plt # part 1 - creating simple plots plt.plot(range(10)) # inputs the values, 0-9 #plt.pause(20) # shows the plot - normally use plt.show but terminal needs pause # part 2 - creating a plot of CO2 vs time times = (0, 1, 2, 3, 4, 5, 6, 7, 8) # the data for the time input co2 = [250, 485, 123, 156, 12, 849, 24, 458, 154] # co2 data input plt.plot(times, co2, 'b--') # plot the data using a blue dashed line plt.xlabel('Time (minutes)') # adds axis label plt.ylabel('CO2 Concentration (ppm)') # adds axis label plt.title('Concentration of CO2 in Leeds') # adds title plt.pause(10) # plt.plot() # part 3 - additional data times = (0, 1, 2, 3, 4, 5, 6, 7, 8) # the data for the time input co2 = (50, 58, 23, 56, 12, 49, 24, 58, 54) # co2 data input temp = (35, 32, 34, 36, 29, 24, 31, 36, 28) plt.plot(times, co2, 'b--', times, temp, 'r') # plot the two data sets plt.xlabel('Time (minutes)') # adds axis label plt.ylabel('CO2 Concentration (ppm)') # adds axis label plt.title('Concentration of CO2 in Leeds') # adds title plt.label() # need to look this up... plt.pause(10) # plt.plot() print
plt.xlabel('Density') plt.ylim(0, ymax) fig7_sp2 = fig7.add_subplot(gs7[0, 9:17]) plt.ylim(0, ymax) plt.plot(x, np.median(demand, axis=1), label='Median of experiments') plt.fill_between(x, np.quantile(demand, 0.75, axis=1), np.quantile(demand, 0.25, axis=1), alpha=0.4, label='Middle 50% of experiments') plt.fill_between(x, demand[(np.argmin(demand.loc[2050]))], demand[(np.argmax(demand.loc[2050]))], alpha=0.3, label='100% of experiments') plt.label() plt.xlabel('Time') # Plot the SUPPLY DISTRIBUTIONS over all experiments fig7 = plt.figure(constrained_layout=True, figsize=(20, 8)) gs7 = fig7.add_gridspec(nrows=1, ncols=20) ymax = 17 for key in supplydemand_composition_dict: fig7_sp1 = fig7.add_subplot(gs7[0, :6]) plt.plot(x, np.median(supplydemand_composition_dict[key], axis=1), label=key, color=supplydemand_color_dict[key]) plt.legend() plt.xlabel('Time') plt.ylabel('Total capacity (PJ)', size=16)
# Display the plot plt.show() # Making a bar chart ------------------------------------------------ plt.bar(df.percinct, df.pets_abducted) plt.ylabel('Pet Abductoins') plt.show() # Horizontal barcharts plt.barh(df.precinct, df.pets_abducted) plt.ylabel('Pet Abductions') plt.show() # Adding error bars plt.bar(df.precinctm df.pet_abductions, yerr = df.error) plt.label('Pet Abductions') plt.show() # Stacked bar charts plt.bar(df.precinct, df.dog, label = 'Dog') plt.bar(df.precinct, df.cat, bottom = df.dog, label = 'Cat') plt.legend() plt.show() # Built a simple bar chart ------------------------------------------------ hours = pd.read_csv('Datasets/hours.csv', sep = ';') # Display the DataFrame hours using print print(hours) # Create a bar plot from the DataFrame hours and add error boars
# frekans sıklıgı plt.hist(setosa.PetalLengthCm, bins=40) plt.xlabel("PetalLengthCm degerleri") plt.ylabel("frekans") plt.title("histogram") plt.show() # %% bar plot import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7]) y = x * 2 + 5 plt.bar(x, y) plt.title("bar plot") plt.xlabel("x") plt.label("y") plt.show() # %% subplot # aynı framede farklı plotları çizdirmesi demek. df1.plot(grid=True, alpha=0.5, subplots=True) plt.subplot(3, 1, 1) plt.plot(setosa.Id, setosa.PetalLengthCm, color="red", label="setosa") plt.subplot(3, 1, 2) plt.plot(versicolor.Id, versicolor.PetalLengthCm, color="green", label="versicolor") plt.subplot(3, 1, 3) plt.plot(virginica.Id, virginica.PetalLengthCm,
ax1.set_xticklabels([]) ax2.plot(x, dd_vec, color='black', linewidth=2.0) ax2.axhline(y=eps, color='r') ax2.set_title('Final dd: ' + str(dd_vec[-1]), loc='right', fontsize=10) ax2.set_title('DD', loc='left', fontweight='bold') ax2.set_xticklabels([]) ax3.plot(x, rmse_vec, color='m', linewidth=2.0) ax3.set_title('Final RMSE: ' + str(rmse_vec[-1]), loc='right', fontsize=10) ax3.set_title('RMSE', loc='left', fontweight='bold') ax3.set_xlabel('Number of Iterations', fontweight='bold') if save: file_name = file_name.replace('.tif', '') plt.savefig('time_plot_' + file_name + '.png') # # Display the Reconstruction. fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7, 3)) ax1.imshow(img0, cmap='gray') ax1.axis('off') ax1.set_title('Original Image') ax2.imshow(recon, cmap='gray') ax2.axis('off') ax2.set_title('Reconstruction') plt.figure() plt.plot(x, cos_alph_vec) plt.xlabel('Number of Iterations') plt.label('Cosine-Alpha', loc='left', fontweight='bold') plt.show()
import matplotlib.pyplot as plt n = int(input("How many term?" ))#this is the input that you put in x2 = 1#numbers that start the fibonacci sequence x1 = 0 a = 0 xaxis = [] yaxis = [] n= n - 1#to account for the number printing of the first term. print(x1)# prints the first number of the fibonacci sequence while n > 0: #this is the loop x = x2 + x1 x2=x1#remebers two numbers before. x1=x#remebers the number before. a = 1 + a xaxis.append(a) yaxis.append(x) n = n - 1#makes it so the cobe will only put out the terms that you asked for. plt.scatter(xaxis,yaxis) plt.label("Fibonacci Graph") plt.xlabel("Number of The Term") plt.ylabel("Value of The Term") plt.show()
# Data Preprocessing Template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('insurance.csv') # Taking Age and Price only for the prediction X = dataset.iloc[:, [0, 6]].values # Using the Dendogram to find optimal number of cluster import scipy.cluster.hierarchy as sch dendogram = sch.dendrogram(sch.linkage(X, method = 'ward')) plt.label('Dendogram') plt.xlabel('Customer') plt.ylabel('Eculiance Distance') #5 Clusture # Fitting Hierarchical Clusturing to the dataset from sklearn.cluster import AgglomerativeClustering hc = AgglomerativeClustering(n_clusters=5,affinity = 'euclidean', linkage='ward') y_hc=hc.fit_predict(X) #Visualising the clusters # If u are using more then 2 dimension don't execute this portion of code as it is valid in 2d only plt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, c = 'red', label = 'Age') plt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, c = 'blue', label = 'Price') plt.title('Clusters of customers') plt.xlabel('Age')
print("##Generate Interarrival times for each ###") df4=df2[['System', 'Item', 'Failure observation']] print(df4.head()) print(df4.groupby('System')) print('Analysis: "Component 10 and 2 appear to be the lesser bottlenecks per system. Component 4 and 9 appear to be the primary bottlenecks per system. Each system itself falls within the same average parameters. With one system breaking everyday, and with it taking approximately three days to repair a system, investigation as to how to potentially ' 'phase out Component 10 and 2 should prove worthwhile."') #dfSyst1 = df2.loc['System 01'] #5 Create a histogram import matplotlib.pyplot as plt itemFailTimeline = df2[['Item', 'Failure observation', 'Repair time']] item4FailTimeline = itemFailTimeline.query('Item =="Component 4"') fig = plt.plot_date(item4FailTimeline['Failure observation'], item4FailTimeline['Repair time'], color='red') plt.ylabel("Hours to repair") plt.title("Item 4 Failures") plt.show() item10FailTimeline = itemFailTimeline.query('Item =="Component 10"') fig =plt.plot_date(item10FailTimeline['Failure observation'], item10FailTimeline['Repair time'], color='red') plt.label("Hours to repair") plt.title("Item 10 Failures") print(item10FailTimeline) plt.show() #print(df4.groupby('System'))
import matplotlib.pyplot as plt import numpy as np x = np.random.randint(1,100,25) y = np.random.randint(10,20,25) # Line graph Example plt.plot(x,y) plt.xlabel("X Random") plt.label("Y Random ") plt.title("LINE GRAPH") plt.show() # Scatter Plot Example actual = np.round(np.random.uniform(10,100,25),decimals = 2) predicted = np.round(np.random.uniform(10,100,25),decimals = 2) plt.scatter(actual,predicted,color = ['red','blue']) plt.show() # Bar Chart Example names = ['a','b','c','d','e'] avg_1 = np.round(np.random.uniform(1,100,5),decimals = 2) avg_2 = np.round(np.random.uniform(1,100,5),decimals = 2) plt.bar(names,avg_1,label="Average 1",color="r") plt.bar(names,avg_2,label="Average 2",color="y")
plt.plot(x, y) plt.plot(x, prediction, color='r') plt.legend(['UNH price', 'Regression line']) plt.xlabel('Time') plt.ylabel('Price') plt.show() print model.summary() ''' # testing for autocorrelation in both prices and residuals _, prices_qstats, prices_qstat_pvalues = statsmodels.tsa.stattools.acf(y, qstat=True) print 'prices autocorrelation pvalue', prices_qstat_pvalues _, prices_qstats, prices_qstat_pvalues = statsmodels.tsa.stattools.acf(y-prediction, qstat=True) print 'residuals autocorrelation pvalue', prices_qstat_pvalues _,jb_pvalue, _, _ = statsmodels.stats.stattools.jarque_bera(y-prediction) print 'jarque bera that residuals are normally distributed', jb_pvalue ''' mlr = regression.linear_model.OLS(y, sm.add_constant(np.column_stack((b1, b2)))).fit() mlr_prediction = mlr.params[0] + mlr.params[1]*b1 + mlr.params[2]*b2 print 'R squared:', mlr.rsquared_adj print 't-statistics of coefficient:', mlr.tvalues y.plot() mlr_prediction.plot() plt.show() plt.legend(['asset', 'model']) plt.label('price')
lin_reg = LinearRegression() lin_reg.fit(X, y) #Fitting polynomial linear regression from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree=4) X_poly = poly_reg.fit_transform(X) poly_reg.fit(X_poly, y) lin_reg_2 = LinearRegression() lin_reg_2.fit(X_poly, y) #plot linear regression plt.scatter(X, y, color='red') plt.plot(X, lin_reg.predict(X), color='blue') plt.title('Truth or Bluff (linear regression)') plt.label('Positionlevel') plt.ylabel('salary') plt.show() #visualize polynomial regresssion plt.scatter(X, y, color='red') plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color='blue') plt.title('Truth or Bluff (polynomial regression)') plt.label('Positionlevel') plt.ylabel('salary') plt.show() #visualising at 0.1 resolution X_grid = np.arange(min(X), max(X), 0.1) X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(X, y, color='red')
#seeing all the power hitters for i in players: power_hitters(i) df2=df2.sort_values("Total_runs",ascending=False) from sklearn.preprocessing import LabelEncoder df3=df2.copy() na_enc=LabelEncoder() df3.Players=na_enc.fit_transform(df3.Players) print(na_enc.classes_) #plots plt.bar(x=df3.Players,height=df3.Runs,color="blue",alpha=1) plt.bar(x=df3.Players,height=df3.B_runs,color="red",alpha=0.6) plt.label("Normal runs and boundary runs") plt.xlabel("Players") plt.ylabel("Runs") plt.show() #orange shows the players gets most of his runs from boundaries than he takes runs #best players on the team according to runs for i in na_enc.inverse_transform([3,4,5,6]): print("{} is one of the best players".format(i)) #to run predictive analysis df_pred=df.copy() df_pred=df_pred.rename(columns={"Balls_without_boundaries":"bwb","Boundary_runs":"b_runs"}) df_pred=df_pred.drop(["b_runs","Runs_ran","bwb","Strike_Rate","Sixes","Fours"],axis=1) #encoding results
##define act model outs = [ layer.output for layer in model.layers[:168]] act_model= Model (inputs= model.inputs, outputs= outs) ## compute activations for all gimages data for the network model stim_acts = act_model.predict( stim) dis_acts = act_model.predict(dis) # loop through layers and filters and compute auc for the data at each filter. for layer_index in range(model.layers[:168]): auc_filters = np.zeros((stim_acts[layer_index].shape(3))) for filter_index in range(stim_acts[layer_index].shape(3)) stim_sample = np.around(stim_acts[layer_index][:,:,:,filter_index].astype('float'), decimals=2) dis_sample = np.around(dis_acts[layer_index][:,:,:,filter_index].astype('float'), decimals=2) auc= aucROC(stim_sample, dis_sample) auc_filters[filter_index] = auc plt.plot(auc_filters, '-') plt.xlabel('Filters Index') plt.label('auRoC') plt.title('ResNet50'+str(model.layers[layer_index].name)+': layer '+str(layer_index) ) plt.savefig('/osg_container_resnet_plots/resnetlayer_'+str(layer_index)+'.png') #write the time taken to file. t_taken= time.time()- start fh = open("time_taken.txt","w") write(t_taken) fh.close()
import numpy as np import matplotlib.pyplot as plt import pandas as pd #import dataset dataset=pd.read_csv('Mall_Customers.Csv') X=dataset.iloc[:,[3,4]].values #using dendagram import scipy.cluster.hierarchy as sch dendrogram=sch.dendrogram(sch.linkage(X,method='ward')) plt.title('Dendrogram') plt.xlabel('Customers') plt.ylabel('Euclidean distances') #HCA (with 5 cluster) from sklearn.cluster import AgglomerativeClustering hc=AgglomerativeClustering(n_clusters=5,affinity='euclidean',linkage='ward') y_hc=hc.fit_predict(X) #visualizing hc plt.scatter(X[y_hc==0,0],X[y_hc==0,1],s=100,c='red',label='Cluster 1') plt.scatter(X[y_hc==1,0],X[y_hc==1,1],s=100,c='blue',label='Cluster 2') plt.scatter(X[y_hc==2,0],X[y_hc==2,1],s=100,c='green',label='Cluster 3') plt.scatter(X[y_hc==3,0],X[y_hc==3,1],s=100,c='cyan',label='Cluster 4') plt.scatter(X[y_hc==4,0],X[y_hc==4,1],s=100,c='magenta',label='Cluster 5') plt.xlabel('Annual Income') plt.ylabel('Spending Scores') plt.label('Clusters of clients') plt.show()
# Regresión con Arboles de DEcision # Importar Librerias import numpy as np import matplotlib.pyplot as plt import pandas as pd #Cargar Dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values #Modelo de Arboles de Decision from sklearn.tree import DecisionTreeRegressor regression = DecisionTreeRegressor(random_state=0) regression.fit(X, y) #Prediccion y_pred = regression.predict([[6.5]]) #Visualizacion de resultados X_grid = np.arange(min(X), max(X), 0.1) X_grid = X_grid.reshape(len(X_grid), 1) plt.scatter(X, y, color="red") plt.plot(X, regression.predict(X), color="blue") plt.title("Arbol de Desicion") plt.label("Posicion del Empleado") plt.ylabel("Sueldo") plt.show()
plt.show() x = [10,12,14] y = [6,12,15] x1 = [11,13,15] y1 = [8,9,19] plt.bar(x,y,align='center') plt.bar(x1,y1,align='center') plt.title('Bar chart') plt.xlabel('X axis') plt.label('Y axis') plt.show()
def plot(self): plt.plot(self.total_frames, self.distances) plt.label("Scores per frame") plt.show()
##################################################################### ## Get the ML estimate of the exponent parameter. alpha_ml, alpha_ml_se = mle_alpha( deg, min( deg ) ) print "The Maximum likelihood estimate of the exponent of the node degree distribution is %.3f (%.4f)\n" % ( alpha_ml, alpha_ml_se ) ##################################################################### ## Run the KS threshold selection routine thresholds = np.unique( deg ) ## The ks_dist() function returns a tuple of the following parameters: ## * ( KS-distance, PV of the KS-test ), ( MLE of alpha, the standard error of the MLE ) ks_min = np.array( [ ks_dist( deg, u ) for u in thresholds ] ) ## Produce the hill plot: the correspondence between the threshold ## and the estimated exponent. plt.figure( 1, figsize = ( 5, 5 ) ) plt.label( 'The hill plot of the degree distribution' ) plt.plot( thresholds, ks_min[:,1,0], "r-") ## In fact the KS-metric is the $L^\infty$ norm on the set of distribution ## functions. plt.figure( 2, figsize = ( 5, 5 ) ) plt.label( 'The KS metric of the estimated and the empirical distributions' ) plt.plot( thresholds, ks_min[:,0,0], "r-") plt.show( ) ## Select the x_min that brings the KS metric to its minimum on the given ## degree data. Note the first threshold is removed, since it is likely ## to yield very biased estimate. i_min = np.argmin( ks_min[10:,0,0] ) x_min = thresholds[ i_min ] alpha_ml, alpha_ml_se = ks_min[ i_min, 1, : ]
def transportplot_mechanisms(self, **kwargs): """ Plots the advective transport based on the physical mechanisms that force it. kwargs: sublevel: string displays underlying levels of the associated mechanisms: 'sublevel', 'subsublevel' or False plotno: integer plot number display: integer or list of strings displays the underlying mechanisms indicated. An integer plots the largest contributions up to that integer and a list of strings plots the mechanisms in that list scale: boolean scales the transport contributions to the maximum value of all contributions concentration: boolean plots the depth-mean, sub-tidal concentration in the background """ ################################################################################################################ # Extract args and/or kwargs ################################################################################################################ sublevel = kwargs.get('sublevel') or kwargs.get('subsublevel') or False # show sub-level data: True/False plotno = kwargs.get('plotno') or 1 # set plot number (default 1) display = kwargs.get('display') or 5 # display number of mechanisms (sorted in descending order) or specific mechanisms scale = kwargs.get('scale') or False # scale the transport contributions to the maximum: True/False concentration = kwargs.get('concentration') or False legend = kwargs.get('legend') if legend !='in': legend = 'out' ################################################################################################################ # Construct list of mechanisms to display and calculate these mechanisms ################################################################################################################ # get keys of the transport mechanisms to display entered by the user or all mechanism if isinstance(display, list): if set(display).issubset(self.input.getKeysOf('T')): keyList = display else: raise KnownError('Not all transport mechanisms passed with display are available.') else: keyList = self.input.getKeysOf('T') # get availability and its derivative w.r.t. x x = self.input.v('grid', 'axis', 'x') if self.input.v('f') is not None: a = self.input.v('f', x=x).reshape(len(x),) a_x = self.input.d('f', x=x, dim='x').reshape(len(x),) else: a = self.input.v('a').reshape(len(x),) a_x = -self.input.v('T') * a / self.input.v('F') # construct list with values to plot loopvalues = [[]] if sublevel: tmp_max = [] for key in keyList: if not 'diffusion' in key: T = self.input.v('T', key) if key in self.input.getKeysOf('F'): trans = T * a + self.input.v('F', key) * a_x loopvalues[0].append([trans, np.sqrt(np.mean(np.square(trans))), key]) else: trans = T * a loopvalues[0].append([trans, np.sqrt(np.mean(np.square(trans))), key]) tmp_max.append(abs(trans).max()) if sublevel == 'subsublevel' and len(self.input.slice('T', key).getAllKeys()[0]) > 2: loopvalues.append([]) tmpkeys = sorted(self.input.slice('T', key).getAllKeys(), key=itemgetter(2)) subkeys = [tmpkeys[i*3:3+i*3] for i in range(len(tmpkeys)/3)] for subkey in subkeys: tmp = np.zeros(a.shape) for subsubkey in subkey: tmp += self.input.v('T', *subsubkey) * a loopvalues[len(loopvalues)-1].append([tmp, np.sqrt(np.mean(np.square(trans))), subsubkey[-1]]) loopvalues[len(loopvalues)-1].append([trans, np.sqrt(np.mean(np.square(trans))), key]) maxT = max(tmp_max) # Sort transport mechanisms based on the value of their root-mean-square value loopvalues[0] = sorted(loopvalues[0], key=itemgetter(1), reverse=True) # Only take the largest transport contributions indicated by the display integer. If the display integer is # larger than the length of the keyList, then all contributions are taken into account if isinstance(display, int): loopvalues[0] = loopvalues[0][:min(display, len(keyList))] # Sort alphetically so that mechanisms receive the same line color for plotting loopvalues[0] = sorted(loopvalues[0], key=itemgetter(2)) else: Ttotal = ((self.input.v('T') - self.input.v('T', 'diffusion_tide') - self.input.v('T', 'diffusion_river')) * a + (self.input.v('F') - self.input.v('F', 'diffusion_tide') - self.input.v('F', 'diffusion_river') ) * a_x) loopvalues[0].append([Ttotal, np.sqrt(np.mean(np.square(Ttotal))), 'total']) maxT = abs(Ttotal).max() ################################################################################################################ # determine number and shape of subplots ################################################################################################################ numberOfSubplots = len(loopvalues) subplotShape = (numberOfSubplots, 2) ################################################################################################################ # plot ################################################################################################################ ## load grid data xdim = ny.dimensionalAxis(self.input.slice('grid'), 'x')[:, 0, 0] conv_grid = cf.conversion.get('x') or 1. # convert size of axis depending on conversion factor in config xdim = xdim * conv_grid ## plot plt.figure(plotno, dpi=cf.dpi, figsize=subplotShape) # plt.hold(True) if not sublevel: sp = plt.subplot() plt.axhline(0, color='k', linewidth=0.5) if scale: loopvalues[0][0][0] = loopvalues[0][0][0] / maxT ln = [] ln += sp.plot(xdim, loopvalues[0][0][0], label='adv. transport') if concentration: conv = cf.conversion.get('c') or 1. c = np.real(np.mean(self.input.v('c0')[:, :, 0] + self.input.v('c1')[:, :, 0] + self.input.v('c2')[:, :, 0], axis=1))*conv if scale: c = c / c.max() ln += sp.plot(xdim, c, '--', color='grey', label=r'$\langle\bar{c}\rangle$') labels = [l.get_label() for l in ln] if legend is 'out': plt.legend(ln, labels, bbox_to_anchor=(1.02, 0), loc=3, borderaxespad=0., fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4) elif legend is 'in': plt.legend(ln, labels, loc='upper left', borderaxespad=0.2, fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4, frameon=False) plt.title('Advective Transport') else: sp2 = sp.twinx() ln += sp2.plot(xdim, c, '--', color='grey', label=r'$\langle\bar{c}\rangle$') labels = [l.get_label() for l in ln] if legend is 'out': plt.legend(ln, labels, bbox_to_anchor=(1.3, 0), loc=3, borderaxespad=0., fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4) elif legend is 'in': plt.legend(ln, labels, loc='upper left', borderaxespad=0.2, fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4, frameon=False) plt.title('Advective Transport', y=1.09) else: plt.title('Advective Transport') ## Axis labels try: xname = cf.names['x'] xunit = cf.units['x'] except KeyError: xname = 'x' xunit = '' plt.xlabel(xname + ' (' + xunit + ')', fontsize = cf.fontsize) try: yunitT = cf.units['T'] if concentration: if scale: sp.set_ylabel(r'$\mathcal{T}$ / $\mathcal{T}_{max}$, $c$ / $c_{max}$ (-)', fontsize = cf.fontsize) if legend is 'in': sp.set_ylim([-1.1, 1.1]) else: sp.set_ylim([-1.1, 1.1]) else: yunitc = cf.units['c'] sp.set_ylabel(r'$\mathcal{T}$ (' + yunitT + ')', fontsize = cf.fontsize) sp2.set_ylabel(r'$c$ (' + yunitc + ')', fontsize = cf.fontsize) else: if scale: sp.set_ylabel(r'$\mathcal{T}$ / $\mathcal{T}_{max}$ (' + yunitT + ')', fontsize = cf.fontsize) if legend is 'in': sp.set_ylim([-1.1, 1.1]) else: sp.set_ylim([-1.1, 1.1]) else: sp.set_ylabel(r'$\mathcal{T}$ (' + yunitT + ')', fontsize = cf.fontsize) except KeyError: yname = [r'$\mathcal{T}$'] yunit = '' plt.ylabel(yname + ' (' + yunit + ')', fontsize = cf.fontsize) else: for subplot_number, subplot_values in enumerate(loopvalues): pos = np.unravel_index(subplot_number, subplotShape) sp = plt.subplot2grid(subplotShape, (pos[0], pos[1])) plt.axhline(0, color='k', linewidth=0.5) # loop over all combinations of the data ln = [] for i, value in enumerate(subplot_values): try: label = cf.transportlabels[value[2]] except KeyError: label = value[2] if scale: value[0] = value[0] / maxT if i == len(subplot_values)-1 and subplot_number >= 1: ln += sp.plot(xdim, value[0], 'k', label=label) else: ln += sp.plot(xdim, value[0], label=label) if concentration and subplot_number == 0: conv = cf.conversion.get('c') or 1. c = np.real(np.mean(self.input.v('c0')[:, :, 0] + self.input.v('c1')[:, :, 0] + self.input.v('c2')[:, :, 0], axis=1)) * conv if scale: c = c / c.max() ln += sp.plot(xdim, c, '--', color='grey', label=r'$\langle\bar{c}\rangle$') labels = [l.get_label() for l in ln] if legend is 'out': plt.legend(ln, labels, bbox_to_anchor=(1.02, 0), loc=3, borderaxespad=0., fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4) elif legend is 'in': plt.legend(ln, labels, loc='upper left', borderaxespad=0.2, fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4, frameon=False) if subplot_number == 0: plt.title('Advective Transport') else: title = keyList[subplot_number-1] try: title = cf.names[title] except: pass plt.title(title, fontsize=cf.fontsize) else: sp2 = sp.twinx() ln += sp2.plot(xdim, c, '--', color='grey', label=r'$\langle\bar{c}\rangle$') labels = [l.get_label() for l in ln] if legend is 'out': plt.legend(ln, labels, bbox_to_anchor=(1.3, 0), loc=3, borderaxespad=0., fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4) elif legend is 'in': plt.legend(ln, labels, loc='upper left', borderaxespad=0.2, fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4, frameon=False) if subplot_number == 0: plt.title(r'Advective Transport ', y=1.09, fontsize=cf.fontsize) else: title = keyList[subplot_number-1] try: title = cf.names[title] except: pass plt.title(title, y=1.09, fontsize=cf.fontsize) else: if legend is 'out': plt.legend(bbox_to_anchor=(1.02, 0), loc=3, borderaxespad=0., fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4) elif legend is 'in': plt.legend(ln, labels, loc='upper left', borderaxespad=0.2, fontsize=cf.fontsize2, labelspacing=0.1, handlelength=0.1, handletextpad=0.4, frameon=False) if subplot_number == 0: plt.title('Advective Transport', fontsize=cf.fontsize) else: title = keyList[subplot_number-1] try: title = cf.names[title] except: pass if concentration and subplot_number > 0: plt.title(title, y=1.09, fontsize=cf.fontsize) else: plt.title(title, fontsize=cf.fontsize) # axis labels and limits. Try to get from config file, else take plain name try: xname = cf.names['x'] xunit = cf.units['x'] except KeyError: xname = 'x' xunit = '' plt.xlabel(xname + ' (' + xunit + ')', fontsize=cf.fontsize) try: yunitT = cf.units['T'] if concentration: if scale: if subplot_number == 0: sp.set_ylabel(r'$\mathcal{T}$ / $\mathcal{T}_{max}$, $c$ / $c_{max}$ (-)', fontsize=cf.fontsize) else: sp.set_ylabel(r'$\mathcal{T}$ / $\mathcal{T}_{max}$ (-)', fontsize=cf.fontsize) if legend is 'in': sp.set_ylim([-1.1, 1.1]) else: sp.set_ylim([-1.1, 1.1]) else: yunitc = cf.units['c'] sp.set_ylabel(r'$\mathcal{T}$ (' + yunitT + ')', fontsize=cf.fontsize) sp2.set_ylabel(r'$c$ (' + yunitc + ')', fontsize=cf.fontsize) else: if scale: sp.set_ylabel(r'$\mathcal{T}$ / $\mathcal{T}_{max}$ (' + yunitT + ')', fontsize=cf.fontsize) if legend is 'in': sp.set_ylim([-1.1, 1.1]) else: sp.set_ylim([-1.1, 1.1]) else: sp.set_ylabel(r'$\mathcal{T}$ (' + yunitT + ')', fontsize=cf.fontsize) except KeyError: yname = [r'$\mathcal{T}$'] yunit = '' plt.label(yname + ' (' + yunit + ')', fontsize=cf.fontsize) plt.xlim(0, max(xdim)) plt.draw() return
[-10, 10, -10, 10] >>> plt.show() >>> plt.plot([-8,-6,-2,1,2,3],[1,3,9,4,5,6],'r--',label='Line1',linewidth=1.5) [<matplotlib.lines.Line2D object at 0x7f2d04680b70>] >>> plt.axis([-10,10,-10,10]) [-10, 10, -10, 10] >>> plt.show() >>> plt.plot([-8,-6,-2,1,2,3],[1,3,-9,4,5,6],'r^',label='Line1',linewidth=1.5) [<matplotlib.lines.Line2D object at 0x7f2d045f36a0>] >>> plt.axis([-10,10,-10,10]) [-10, 10, -10, 10] >>> plt.xlabel("X-Axis") Text(0.5, 0, 'X-Axis') >>> plt.ylabel("Y-Axis") Text(0, 0.5, 'Y-Axis') >>> plt.label("My Plot") Traceback (most recent call last): File "<pyshell#64>", line 1, in <module> plt.label("My Plot") AttributeError: module 'matplotlib.pyplot' has no attribute 'label' >>> plt.title("My Plot") Text(0.5, 1.0, 'My Plot') >>> plt.show() >>> == RESTART: /home/anuranjan/Summer Training/Practice_matplotlib(class)2.py == Traceback (most recent call last): File "/home/anuranjan/Summer Training/Practice_matplotlib(class)2.py", line 4, in <module> plt.sublplot(211) AttributeError: module 'matplotlib.pyplot' has no attribute 'sublplot' >>> == RESTART: /home/anuranjan/Summer Training/Practice_matplotlib(class)2.py ==
5].values # Writing '1:2' instead of '1' because weant X to be a matrix and not an array # Using the elbow method to find the optimal number of clusters from sklearn.cluster import KMeans wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters=i, init='k-means++', n_init=110, max_iter=300, random_state=0) kmeans.fit(X) wcss.append(kmeans.inertia_) plt.plot(range(1, 11), wcss) plt.title('The Elbow Method') plt.label('Number of clusters') plt.ylabel('WCSS') plt.show() # Applying K-Means to the mall dataset kmeans = KMeans(n_clusters=5, init='k-means++', n_init=110, max_iter=300, random_state=0) y_kmeans = kmeans.fit_predict(X) # Visualising the dataset plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s=100,