def tempMatch(src, src2): img = cv2.imread(src, 0) img2 = img.copy() template = cv2.imread(src2, 0) w, h = template.shape[::-1] methods = [ 'cv2.TM_CCOEFF', 'cv2TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.SQDIFF_NORMED' ] for meth in methods: img = img2.copy() method = eval(meth) res = cv2.matchTemplate(img, template, method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if method in [cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc bottom_right = (img, top_left[0] + w, top_left[1] + h) cv2.rectangle(img, top_left, bottom_right, 255, 2) plt.subplot(121), plt.imshow(res, cmap='gray') plt.title('Matching Result'), plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(img, cmap='gray') plt.title('Detected Point'), plt.xticks([]), plt.yticks([]) plt.subtitle(meth) plt.show()
def ShowLossHistory(self, xmin=None, xmax=None, ymin=None, ymax=None): plt.plot(self.loss_history) title = self.min_trace.toString() + "," + self.params.toString() plt.subtitle(title) plt.xlabel("epoch") plt.ylabel("loss") if xmin != None and ymin != None: plt.axis([xmin, xmax, ymin, ymax]) plt.show() return title
def plot_krum06_avgMdot(sink,mdot,tBHA,args): #prep plot f,axis=plt.subplots(2,2,sharex=True,figsize=(15,10)) plt.subplots_adjust( hspace=0,wspace=0 ) ax=axis.flatten() #calc mean and median Mdot avg= np.average(sink.MdotFine/mdot.lee_const,axis=1) med= np.median(sink.MdotFine/mdot.lee_const,axis=1) avg_ft= np.average(sink.MdotFine,axis=1)/mdot.lee_ft #mdot.lee_ft has len = n time points avg_ft_environ= np.average(sink.MdotFine/mdot.lee_ft_environ,axis=1) med_ft= np.median(sink.MdotFine,axis=1)/mdot.lee_ft #mdot.lee_ft has len = n time points med_ft_environ= np.median(sink.MdotFine/mdot.lee_ft_environ,axis=1) time= (sink.time-sink.time[0])/tBHA if args.boxcar: #'time' returned for each below are all the same b/c input sink.time are the same (time,avg)= Boxcar((sink.time-sink.time[0])/tBHA,avg,args.boxcar*tBHA,units_tBHA=True) (time,med)= Boxcar((sink.time-sink.time[0])/tBHA,med,args.boxcar*tBHA,units_tBHA=True) (time,avg_ft)= Boxcar((sink.time-sink.time[0])/tBHA,avg_ft,args.boxcar*tBHA,units_tBHA=True) (time,avg_ft_environ)= Boxcar((sink.time-sink.time[0])/tBHA,avg_ft_environ,args.boxcar*tBHA,units_tBHA=True) (time,med_ft)= Boxcar((sink.time-sink.time[0])/tBHA,med_ft,args.boxcar*tBHA,units_tBHA=True) (time,med_ft_environ)= Boxcar((sink.time-sink.time[0])/tBHA,med_ft_environ,args.boxcar*tBHA,units_tBHA=True) #MEDIAN - right panels ax[0].plot(time,med,'k-',lw=2) ax[0].plot(time,med_ft,'b-',lw=2) ax[0].plot(time,med_ft_environ,'g-',lw=2) ax[2].plot(time,med,'k-',lw=2) ax[2].plot(time,med_ft,'b-',lw=2) ax[2].plot(time,med_ft_environ,'g-',lw=2) #MEAN - left panels ax[1].plot(time,avg,'k-',lw=2) ax[1].plot(time,avg_ft,'b-',lw=2) ax[1].plot(time,avg_ft_environ,'g-',lw=2) ax[3].plot(time,avg,'k-',lw=2,label=r"$\dot{M}=$ const") ax[3].plot(time,avg_ft,'b-',lw=2,label=r"$\dot{M}=$ f(t)") ax[3].plot(time,avg_ft_environ,'g-',lw=2,label=r"$\dot{M}=$ f(t,sink)") #annotate plot ax[0].set_title("Median") ax[1].set_title("Mean") ax[0].set_ylabel(r'$\mathbf{ \dot{M}/\dot{M}_0 }$') ax[2].set_ylabel(r'$\mathbf{ \dot{M}/\dot{M}_0 }$') ax[2].set_xlabel(r"$\mathbf{ t/t_{BHA} }$") ax[3].set_xlabel(r"$\mathbf{ t/t_{BHA} }$") if args.boxcar: plt.subtitle("boxcar %.2g tBHA" % args.boxcar) ax[3].legend(loc=4,fontsize='medium') #scaling for i in [0,1]: ax[i].set_yscale('log') for i in [2,3]: ax[i].set_yscale('linear') for a in ax: if args.ylim: a.set_ylim(args.ylim[0],args.ylim[1]) if args.xlim: a.set_xlim(args.xlim[0],args.xlim[1]) if args.fname: fsave= "median_mean_mdot_"+args.fname+".png" else: fsave="median_mean_mdot.png" plt.savefig(fsave,dpi=150) plt.close()
def run(self): with self.input()[0] as i: bag = ProgramBags(content=i.query()) with self.input()[1] as i: D = i.query() graphIndex = D['graphIndex'] X = np.array(D['data']) stress = D['stress'] del D path = self.output().path directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(directory) spath = os.path.splitext(path) spath = spath[0] + '_%s' + spath[1] colors = ['grey', 'red'] aName = ['OTHER', 'cat'] for k, V in bag.categories.items(): l_vec = np.zeros(len(X)) nnz = 0 aName[1] = k for p in V: pos = graphIndex[p] l_vec[pos] = 1 nnz += 1 plt.figure(1) plt.subtitle('MDS of Category %s (h: %s, D: %s) [%s points] (Stress: %2.2f)' % (k, str(self.h), str(self.D), str(nnz), stress)) for color, i, t in zip(colors, range(len(aName)), aName): plt.scatter(X[l_vec == i, 0], X[l_vec == i, 1], color='none', alpha=.8, lw=2, label=t, edgecolors=color) plt.legend(loc='best', shadow=False, scatterpoints=1) plt.savefig(spath % k) plt.close()
def plot_gallery(title, images, n_col=n_col, n_row=n_row): plt.figure(figsize=(2. * n_col, 2.26 * n_row)) plt.subtitle(title, size=16) for i, comp in enumerate(images): plt.subplot(n_row, n_col, i + 1) vmax = max(comp.max(), -comp.min()) plt.imshow(comp.reshape(image_shape), cmap=plt.cm.gray, interpolation='nearest', vmin=-vmax, vmax=vmax) plt.xticks(()) plt.yticks(()) plt.subplots_adjust(0.01, 0.05, 0.99, 0.93, 0.04, 0.)
def vein_pattern(image, kernal_size, sigma): #test import cv2 import matplotlib.pyplot as plt image_path='../sample dataset/input/s1/2017232_R_S.jpg' image=cv2.imread(image_path,0) processed_image=vein_pattern(image,6,8) plt.subplot(1,2,1) plt.imshow(image, cmap='gray') plt.title('Original Image') plt.subplot(1,2,2) plt.imshow(processed_Image) plt.subtitle("Vein Pattern") plt.tight_layout() plt.savefig("vein_pattern_extracted.png") plt.show() def compute_curvature(image, sigma): #1. constructs the 2D gaussian filter "h" given the window winsize=np.cell(4*sign) #enough space for the filter window=np.arrange(-winsize,winsize+1) X,V=np.meshgrid(window,window) G=1.0/(2*math.pi * sigma ** 1) G*= np.exp(-X ** 2 + Y ** 2)/ (2 * sigma ** 2)) #2. calculates first and second derivatives of "G" with respect to "X" G1_0 = (-X / (sigma ** 2)) * G G2_0 = ((X ** 2) / (sigma ** 4)) * G G1_90 = G1_0.T G2_90 = G2_0.T hxy = ((X * Y) / (sigma ** 8)) * G #3. calculates derivatives w.r.t. to all directions image_g1_0 = 0.1 * Image.convolve(image, G1_0, mode='nearest') image_g2_0 = 10 * Image.convolve(image, G2_0, mode='nearest') image_g1_90 = 0.1 * Image.convolve(image, G1_90, mode='nearest') image_g2_90 = 10 * Image.convolve(Image, G2_90, mode='nearest') fxy = Image.convolve(image, hxy, mode='nearest')
def Modelcomplexity(x, y): cv = ShuffleSplit(x.shape[0], n_iter=10, test_size=0.2, random_state=0) max_depth = np.arange(1, 11) plt.figure(figsize=(10, 10)) classifier = DecisionTreeRegressor() (train_scores, test_scores) = curves.validation_curve(classifier, x, y, param_name="max_depth", param_range=max_depth, cv=cv, scoring='r2') train_mean = np.mean(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1) train_std = np.std(train_scores, axis=1) test_std = np.std(test_scores, axis=1) plt.plot(max_depth, test_mean, 'o-', color='g', label='testing scores') plt.plot(max_depth, train_mean, 'o-', color='r', label='training scores') plt.fill_between(max_depth, train_mean - train_std, train_mean + train_std, color='r', alpha=0.8) plt.fill_between(max_depth, test_mean - test_std, test_mean + test_std, color='g', alpha=0.8) plt.xlim([0, 11]) plt.ylim([-0.05, 1.05]) plt.xlabel('maximum depth') plt.ylabel('scores') #print(k,depth) plt.legend(loc='upper right', borderaxespad=0.) plt.subtitle('DecisionTreeClassifier', fontsize=16, color='g', y=1.05) plt.tight_layout() plt.show() return True
plt.style.use('seaborn-whitegrid') bank_data2.hist(bins=20, figsize=(14, 10)) plt.show() labels = 'Did not open term', 'opened term' fig, ax = plot.subplots(1, 2, figsize=(16, 8)) bank_data2['y'].value_counts().plot.pie(explode=[0, 0.25], autopct='%1.2f%%', ax=ax[0], shadow=True, labels=labels, fontsize=12, startangle=135) plt.subtitle('Information on term subscriptions', fontsize=20) df = bank_data2.groupby(['education', 'y']).size().groupby( level=0).apply(lambda x: x / bank_data2.shape[0]).unstack().plot( kind='bar', ax=ax[1], stacked=True) ax[1].set(ylabel='Percentage of term openers by level of education') ax[1].set(xlable='Education level') ax[1].legend(['Did not open', 'open']) fig, ax = plt.subplots(1, 2, figsize=(16, 8)) plt.subtitle('Information on Term Subscription 2', fontsize=20) df = bank_data2.groupby(['age', 'y']).size().groupby( level=0, squeeze=True).apply(lambda x: x / bank_rate2.shape[0]).unstack().plot( kind='bar', ax=ax[0], stacked=True) ax[0].set(ylabel='Percentage of term openers by age')
plt.subplot(133) train['Property_Area'].value_counts(normalize=True).plot.bar(title= 'Property_Area') plt.show() #independent Variable (nUMERICAL) plt.figure(1) plt.subplot(121) sns.distplot(train['ApplicantIncome']); plt.subplot(122) train['ApplicantIncome'].plot.box(figsize=(16,5)) plt.show() #finding the insite of the incokme toward the education train.boxplot(column="ApplicantIncome",by="Education") plt.subtitle("") Text(0.5,0.98,'') #distrubution of the coapplication income plt.figure(1) plt.subplot(121) sns.distplot(train['CoapplicantIncome']); plt.subplot(122) train['CoapplicantIncome'].plot.box(figsize=(16,5)) plt.show() #disstrubution of the loan amount plt.figure(1) plt.subplot(121) df=train.dropna() sns.distplot(df['LoanAmount']);
plt.legend(loc = "upper left") plt.title("Return space") plt.ylabel("Return of $1 on first date, x100%") #%% figsize(11.,5) for i, _stock in enumerate(stocks): plt.subplot(2, 2, i + 1) plt.hist(stock_returns[_stock], bins = 20), normed = True, histtype = "stepfilled", color = colors[i], alpha = .7) plt.title(_stock + " returns") plt.xlim(-.15, .15) plt.tight_layout() plt.subtitle("Histogram of daily returns", size = 14) #%% with model: obs = pm.MvNormal("observed returns", mu = mu, cov = cov_matrix, observed = stock_returns) step = pm.NUTS() trace = pm.sample(5000, step = step) #%% figsize(12.5,4) #examine the mean return first. mu_samples = trace["returns"] for i in range(4): plt.hist(mu_samples[:,i], alpha = 0.8 - 0.05*i, bins = 30,
y_i = y[i] if y_i * (np.dot(np.transpose(w), x_i) + b) <= 0: w = w + eta * y_i * x_i b = b + eta * y_i break else: i = i + 1 if i == length: break return w, b, step_num def creat_hyperplane(x, y, w, b): return (-w[0][0] * x - w[1][0] * y - b)/[2][0] data = creat_data(100) eta, w_0, b_0 = 0.1, np.ones((3, 1), dtype=float), 1 w, b, num = perception(data, eta, w_0, b_0) fig = plt.figure() plt.subtitle("perception") ax = Axes3D(fig) plot_samples(ax, data) x = np.linspace(-30, 100, 100) y = np.linspace(-30, 100, 100) x, y = np.meshgrid(x, y) z = creat_hyperplane(x, y, w, b) ax.plot_surface(x, y, z, rstride=1, cstride=1, color='g', alpha=0.2) ax.legend(loc="best") plt.show()
#!/usr/bin/python import pylab import imageio import matplotlib.pyplot as plt filename='/Users/dc/Desktop/IMG_1397.m4v' vid = imageio.get_reader(filename,'ffmpeg') nums = [10,287] for num in nums: image = vid.get_data(num) fig = plt.figure() plt.subtitle('image #{}'.format(num),fontsize=20) plt.imshow(image) plt.show()
line = line.rstrip() # strip /t, /n, spaces from the right side x, y, z = line.split() x_val.append(float(x)) y_val.append(float(y)) z_val.append(float(z)) print x_val print y_val """ for line in f: line = line.rstrip() # strip /t, /n, spaces from the right side print line x,y = line.split(",") print x, y x_val.append(float(x)) y_val.append(float(y)) """ """ "10" "," "100" "\n" temp=331+k plt.subplot(temp) plt.plot(x, y, colors = 'g', linestyle = '-0', x, z, linestyle = colors_line[k]) # plt.title(list_title[k]) plt.xlabel(list_xlabel[k]) plt.ylabel(list_ylabel[k]) plt.subtitle("Avinash") header = f.readline().rstrip().split() """
ax.set_xlim( 1, 2 ) # Bars are going from 0 to 5, so lets crop the plot somewhere in the middle ax.grid(False) # Hide grid ax.set_facecolor('white') # Make background white ax.set_xticks([]) # Remove horizontal ticks ax.set_yticks( np.linspace(min(bar_y), max(bar_y), 3)) # Show vertical ticks for min, middle and max ax.yaxis.tick_right() # Show vertical ticks on the right plt.subplots_adjust(left=0.40, bottom=0.25, right=None, top=None, wspace=None, hspace=None) #Make dotplot / heatmap of the quantification heatmap(melt['y'], melt['x'], color=melt['value'], palette=sns.color_palette("Greys", 256), size=melt['value'].abs(), marker='$\u2713$', x_order=N_nodes.columns, y_order=sorted(N_nodes.index), size_scale=100) plt.savefig('Reactome_count.pdf') plt.subtitle('Reactome Therm Counts')
BATCH_SIZE, callbacks=cbks #callbacks=[checkpoint] ) # same model #model_json = lenet.net.to_json() #lenet.net.save_weights('lenet_model.h5', save_format='h5') #lenet.net.load_weights('lenet_model.h5') lenet.net.save('checkpoint/lenet_model.h5') #model = tf.keras.models.load_model('lenet_model.h5') # plot training / validation loss & acc plt.figure(figsize=(14, 5)) plt.subplot(1, 2, 1) plt.subtitle('Train results', fontsize=10) plt.xlabel('Number of Epochs') plt.ylabel('Loss', fontsize=16) plt.plot(history.history['loss'], color='b', label='Training Loss') plt.plot(history.history['val_loss'], color='r', label='Validation Loss') plt.legend(loc='upper right') plt.subplot(1, 2, 2) plt.ylabel('Accuracy', fontsize=16) plt.plot(history.history['acc'], color='green', label='Training Accuracy') plt.plot(history.history['val_acc'], color='orange', label='Validation Accuracy') plt.legend(loc='lower right') plt.show()
def lorenz_curve(df_kstable, df_maxks): lorenz = pd.DataFrame({ 'cum_good': df_kstable.cum_good_rate.values[list(range(1, len(df_kstable) + 1, 100))], 'cum_rand': df_kstable.cum_rand_rate.values[list(range(1, len(df_kstable) + 1, 100))], 'cum_bad': df_kstable.cum_bad_rate.values[list(range(1, len(df_kstable) + 1, 100))] }) t0 = lorenz.cum_rand.values t1 = lorenz.cum_good.values t2 = lorenz.cum_rand.values t3 = lorenz.cum_bad.values fig = plt.figure() ax = fig.add_subplot(111) max_ks_val = df_maxks['max_ks'].values[0] max_ks_pop = df_maxks['max_ks_pop'].values[0] max_ks_cgr = df_maxks['cum_good_rate'].values[0] line1, = ax.plot(t0, t1, ls='solid', color='blue', lw=1.5) line2, = ax.plot(t0, t2, ls='dashed', color='green', lw=1.5) line3, = ax.plot(np.array([max_ks_pop, max_ks_pop]), np.array([0, max_ks_cgr]), ls='dashdot', color='grey', lw=1.5) line4, = ax.plot(np.array([0, max_ks_pop]), np.array([max_ks_cgr, max_ks_cgr]), ls='dashdot', color='grey', lw=1.5) mark1, = ax.plot(max_ks_pop, max_ks_cgr, marker='>', markersize=10, color='blue') txt = "Max KS: {:.0%}".format(max_ks_val) + " at " + '{:.0%}'.format( max_ks_pop) + " of Population" plt.text(max_ks_pop + 0.03, max_ks_cgr - 0.01, txt, ha='left', rotation=0, wrap=True) xtext = ax.set_xlabel('% Cumulative Population') ytext = ax.set_ylabel('% Cumulative Good') ax.set_xlim(0., 1.) ax.xaxis.set_major_formatter( ticker.FuncFormatter(lambda t0, _: '{:.0%}'.format(t0))) ax.set_ylim(0., 1.) ax.yaxis.set_major_formatter( ticker.FuncFormatter(lambda t1, _: '{:.0%}'.format(t1))) plt.legend((line1, line2), ('Model', 'Random'), loc='lower right', bbox_to_anchor=[0.95, 0.1], shadow=True) plt.subtitle('Lorenz Curve', fontsize=14) plt.show()
# every row in array is normalized since in between 1 and 0 fig, sub_plots = plt.subplots(nrows=5, ncols=8, figsize=(14, 8)) print(sub_plots) sub_plots = sub_plots.flatten() print(sub_plots) for unique_user_id in np.unique(targets): image_index = unique_user_id * 8 sub_plots[unique_user_id].imshow(features[image_index].reshape(64, 64), cmap='gray') sub_plots[unique_user_id].set_xticks([]) sub_plots[unique_user_id].set_yticks([]) sub_plots[unique_user_id].set_title("Face id: %s" % unique_user_id) plt.subtitle("The dataset (40 people") plt.show() # lets plot the 10 images for the first person (face id=0) fig, sub_plots = plt.subplots(nrows=1, ncols=10, figsize=(18, 9)) for j in range(10): sub_plots[j].imshow(features[j].reshape(64, 64), cmap="gray") sub_plots[j].set_xticks([]) sub_plots[j].set_yticks([]) sub_plots[j].set_title("Face id=0") plt.show() # split the original data-set (training and test set)
import matplotlib.pyplot as plt plt.figure(0) axes1 = plt.subplot2grid((3,3), (0,0), colspan=3) axes1 = plt.subplot2grid((3,3), (1,0), colspan=2) axes1 = plt.subplot2grid((3,3), (1,1))# colspan=1 默认是1 axes1 = plt.subplot2grid((3,3), (2,0)) axes1 = plt.subplot2grid((3,3), (2,1), colspan=2) #tidy up tick labels size all_axes = plt.gcf().axes for ax in all_axes: for ticklabel in ax.get_xticklabels() + ax.get_yticklabels(): ticklabel.set_fontsize(10) plt.subtitle("Demo of subplot2grid") plt.show() 补充: 另一种定制化当前 axes or subplot 的例子: axes = fig.add_subplot(111) #创建图标axes实例 rectangle = axes.patch #引用rectangle实例的patch❓ rectangle.set_facecolor('blue') '注释' 此字段,代表当前axes实例的背景,可以更新该实例的属性,进而更新axes的背景:改变颜色、加载图像、添加水印保护❓ *也可以,先创建一个补片(patches),再将其添加到axes的背景中 fig = plt.figure() axes = fig.add_subplot(111)
df_results = pd.DataFrame(train_results) df_results = df_results[0].value_counts() df_results.columns = ['Survived'] df_results.plot(kind='bar') plt.title('Survivors bar chart') plt.xlabel('0 = Died, 1 = Survived') plt.ylabel('Percentage') plt.show() del df_results fig, axs = plt.subplots(1,5,figsize=(20,4)) for i, f in enumerate(["Fare","Age","Pclass","Parch","SibSp"]): sns.distplot(in_all[f].dropna(), kde=False, ax=axs[i]).set_title(f) axs[i].set(ylabel='# of Passengers') plt.subtitle('Feature Histograms (Ignoring Missing Values') plt.show() sns.heatmap(in_all.corr(), annot=True, cmap='coolwarm') plt.show() in_all.corr()['Survived'].sort_values() fig, axs = plt.subplots(1, 2, figsize=(12,6)) for i, sex in enumerate(["female", "male"]): p = in_all[in_all["Sex"] == sex]["Survived"].value_counts(normalize=True).sort_index().to_frame().reset_index() sns.barplot(x=["Perished", "Survived"], y="Survived", data=p, hue="index", ax=axs[i], dodge=False) axs[i].set_title("Survival Histogram - {:0.1%} Survived ({})".format(p.loc[1,"Survived"], sex)) axs[i].set_ylabel("Survival Rate") axs[i].get_legend().remove() in_all['Embarked'].value_counts()
#Modulating the probe # Frequency for pump in probe squarewave fprobe = 50 deltatprobe = 0 squarewaveprobe = 1 / 2 * ( signal.square(2 * np.pi * fprobe * t1ms + deltatprobe) + abs(signal.square(2 * np.pi * fprobe * t1ms + deltatprobe))) modprobe = squarewaveprobe * array2 plt.figure(figsize=(13, 8)) plt.tick_params(labelsize=16) plt.ylabel('Signal') plt.xlabel('Time (s)') plt.title("Probe Signal * Square Wave with " + r'$\Delta$t=' + str(deltatprobe) + ", f=" + str(fprobe) + "Hz") plt.plot(t1ms, modprobe) plt.show() #Adding the two modulated pulses modsignal = modpump + modprobe #Here I am mulitplying by the sin(fpump-fprobe+(sum of deltaTs)) modsignal2 = modsignal * np.sin((fpump - fprobe) * 2 * np.pi * t1ms + (deltatpump + deltatprobe)) plt.figure(figsize=(13, 8)) plt.tick_params(labelsize=16) plt.ylabel('Signal') plt.xlabel('Time (s)') plt.subtitle("Pump + Probe", fontsize=16) plt.plot(t1ms, modsignal) plt.show()
stock_data.isnull() stock_data.boxplot(column="Open Price" , by="Date") stock_data.dtypes dateparse = lambda dates:pd.datetime.strptime(dates, '%d-%b-%Y') stockExchange = pd.read_csv('D:\\DataAnalytics\\Datasets\\[email protected]',parse_dates=['Date'],index_col='Date',date_parser=dateparse) from datetime import datetime ts = stockExchange["Open Price"] plt.plot(ts) plt.xlabel("Date Range") plt.ylabel("TCS StockPrice") plt.subtitle("TCS Stock Value over Time Range") from statsmodels.tsa.stattools import adfuller def test_stationary(timeseries): #Determining rolling statistics rollingMean = pd.rolling_mean(timeseries,window=12) rollingStandardDeviation = pd.rolling_std(timeseries,window = 12) #plotting rolling statistics: original = plt.plot(timeseries,color='blue',label='Original') mean = plt.plot(rollingMean,color='red',label='Rolling Mean') std = plt.plot(rollingStandardDeviation,color='black',label='Rolling Std') plt.legend(loc='best') plt.title('Rolling Mean & Standard Deviation') plt.show(block = False)
""" x = 'D:\COURSE programming with python for Data Science\DAT210x-master\Module3\Datasets\wheat.data' import pandas as pd import matplotlib import matplotlib.pyplot as plt matplotlib.style.use('ggplot') filepath = x student_dataset = pd.read_csv(filepath, index_col=0) #%% #scatter plot student_dataset.plot.scatter(x='G1', y='G2') plt.subtitle() plt.xlabel() plt.ylabel() plt.show() ## ## ### histogram plot my_series = student_dataset.G3 my_dataframe = student_dataset[['G3', 'G2', 'G1']] my_series.plot.hist(alpha=.50) my_dataframe.plot.hist(alpha=.50) #%% #3D Scatter plot
template = cv2.imread('', 0) w, h = template.shape[::-1] methods = [ 'cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED' ] for meth in methods: img = img2.copy() method = eval(meth) res = cv2.matchTemplate(img, template, method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) cv2.rectangle(img, top_left, bottom_right, 255, 2) plt.subplot(121), plt.imshow(res, cmap='gray') plt.title('Matching Result') plt.xticks([]), plt.yticks([]) plt.subtitle(meth) plt.show()
plt.grid(True) plt.title('交易量') clrs = plt.cm.terrain(np.linspace(0, 0.8, n)) plt.subplot(423) for i, clr in enumerate(clrs): plt.plot(t, y[:, i], '-', color=clr, alpha=0.7) plt.title('所有组分') for i, clr in enumerate(clrs): axes = plt.subplot(4, 2, i+4) plt.plot(t, y[:, i], '-', color=clr) plt.title('组分%d' % (i+1)) plt.grid(True) plt.subtitle(u'SH600000股票: GaussianHMM分解隐变量', fontsize=18) plt.tight_layout() plt.subplots_adjust(top=0.9) plt.show()
from os.path import isfile, join import shutil import stat import collections from collections import defaultdict import matplotlib.pyplot as plt import matplotlib.image as img import numpy as np grocery_images_dir = '../grocery_images_png/' img_rows = 5 img_cols = 5 fig, ax = plt.subplots(img_rows, img_cols, figsize=(25, 50)) plt.subtitle('Random Grocery Images', fontsize=20) sorted_img_dirs = sorted(os.listdir(grocery_images_dir)) for row in range(img_rows): for col in range(img_cols): try: # get an individual food category to draw spec_img_dir = sorted_img_dirs[col + row*5] except: break # get all the images in the specified directory all_images = os.listdir(os.path.join(grocery_images_dir, spec_img_dir)) # open a random one and show img_path = np.random.choice(all_images) img = plt.imread(os.path.join(grocery_images_dir, spec_img_dir, img_path)) ax[row][col].imshow(img)