Python matplotlib.pyplot.tick_params() Examples

The following are 30 code examples of matplotlib.pyplot.tick_params(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: plot_threshold_vs_success_trans.py    From pointnet-registration-framework with MIT License 7 votes vote down vote up
def make_plot(files, labels):
	plt.figure()
	for file_idx in range(len(files)):
		rot_err, trans_err = read_csv(files[file_idx])
		success_dict = count_success(trans_err)

		x_range = success_dict.keys()
		x_range.sort()
		success = []
		for i in x_range:
			success.append(success_dict[i])
		success = np.array(success)/total_cases

		plt.plot(x_range, success, linewidth=3, label=labels[file_idx])
		# plt.scatter(x_range, success, s=50)
	plt.ylabel('Success Ratio', fontsize=40)
	plt.xlabel('Threshold for Translation Error', fontsize=40)
	plt.tick_params(labelsize=40, width=3, length=10)
	plt.grid(True)
	plt.ylim(0,1.005)
	plt.yticks(np.arange(0,1.2,0.2))
	plt.xticks(np.arange(0,2.1,0.2))
	plt.xlim(0,2)
	plt.legend(fontsize=30, loc=4) 
Example #2
Source File: statistics_per_user.py    From wiki-scripts with GNU General Public License v3.0 6 votes vote down vote up
def plot_setup(title="", ylabel="edits"):
    fig = plt.figure(figsize=(12, 9))
    ax = fig.add_subplot(111)
    plt.title(title)
    plt.xlabel("date")
    plt.ylabel(ylabel)

    # x-ticks formatting
    plt.gca().xaxis.set_major_formatter(mpl.dates.DateFormatter('%Y-%m-%d'))
    plt.gca().xaxis.set_major_locator(mpl.dates.MonthLocator(interval=3))
    plt.tick_params(axis="x", which="both", direction="out")

    # y-ticks
    plt.gca().yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=10))

    # show grid
    plt.grid(True, which="both")

    return ax 
Example #3
Source File: validation_plots.py    From TheCannon with MIT License 6 votes vote down vote up
def chisq_dist():
    fig = plt.figure(figsize=(6,4))
    ivar = np.load("%s/val_ivar_norm.npz" %DATA_DIR)['arr_0']
    npix = np.sum(ivar>0, axis=1)
    chisq = np.load("%s/val_chisq.npz" %DATA_DIR)['arr_0']
    redchisq = chisq/npix
    nbins = 25
    plt.hist(redchisq, bins=nbins, color='k', histtype="step",
            lw=2, normed=False, alpha=0.3, range=(0,3))
    plt.legend()
    plt.xlabel("Reduced $\chi^2$", fontsize=16)
    plt.tick_params(axis='both', labelsize=16)
    plt.ylabel("Count", fontsize=16)
    plt.axvline(x=1.0, linestyle='--', c='k')
    fig.tight_layout()
    #plt.show()
    plt.savefig("chisq_dist.png") 
Example #4
Source File: MakeEvolutionFigure.py    From dybm with Apache License 2.0 6 votes vote down vote up
def subplot(N, n, i, title=True):
    ax = fig.add_subplot(N, 1, i)
    image = np.array(x[n]).T
    ax.imshow(image, cmap=plt.cm.gray, interpolation="nearest")
    if title:
        if n == 0:
            ax.set_title('Before training', **title_font)
        else:
            num = str(n)
            if len(num) > 3:
                num = num[:-3] + "," + num[-3:]
            if len(num) > 7:
                num = num[:-7] + "," + num[-7:]
            ax.set_title('After training ' + num + " times", **title_font)
    plt.tick_params(axis='both', which='both', bottom='off', top='off',
                    right="off", left="off", labelleft="off",
                    labelbottom='off')
    if i == N:
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        plt.arrow(xlim[0], ylim[0] + 1, xlim[1] - xlim[0] - 1.5, 0, width=.1,
                  color="k", clip_on=False, head_width=1., head_length=1.5) 
Example #5
Source File: pixel.py    From yatsm with MIT License 6 votes vote down vote up
def plot_DOY(dates, y, mpl_cmap):
    """ Create a DOY plot

    Args:
        dates (iterable): sequence of datetime
        y (np.ndarray): variable to plot
        mpl_cmap (colormap): matplotlib colormap
    """
    doy = np.array([d.timetuple().tm_yday for d in dates])
    year = np.array([d.year for d in dates])

    sp = plt.scatter(doy, y, c=year, cmap=mpl_cmap,
                     marker='o', edgecolors='none', s=35)
    plt.colorbar(sp)

    months = mpl.dates.MonthLocator()  # every month
    months_fmrt = mpl.dates.DateFormatter('%b')

    plt.tick_params(axis='x', which='minor', direction='in', pad=-10)
    plt.axes().xaxis.set_minor_locator(months)
    plt.axes().xaxis.set_minor_formatter(months_fmrt)

    plt.xlim(1, 366)
    plt.xlabel('Day of Year') 
Example #6
Source File: Results.py    From MicroGrids with European Union Public License 1.1 6 votes vote down vote up
def Energy_Flow(Time_Series):


    Energy_Flow = {'Energy_Demand':0, 'Lost Load':0, 'Energy PV':0,'Curtailment':0, 'Energy Diesel':0, 'Discharge energy from the Battery':0, 'Charge energy to the Battery':0}

    for v in Energy_Flow.keys():
        if v == 'Energy PV':
            Energy_Flow[v] = round((Time_Series[v].sum() - Time_Series['Curtailment'].sum()- Time_Series['Charge energy to the Battery'].sum())/1000000, 2)
        else:
            Energy_Flow[v] = round((Time_Series[v].sum())/1000000, 2)
          
    
    c = ['From Generator', 'To Battery', 'Demand', 'From PV', 'From Battery', 'Curtailment', 'Lost Load']       
    plt.figure()    
    plt.bar((1,2,3,4,5,6,7), Energy_Flow.values(), color= 'b', alpha=0.3, align='center')
    
    plt.xticks((1.2,2.2,3.2,4.2,5.2,6.2,7.2), c)
    plt.xlabel('Technology')
    plt.ylabel('Energy Flow (MWh)')
    plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='on')
    plt.xticks(rotation=-30)
    plt.savefig('Results/Energy_Flow.png', bbox_inches='tight')
    plt.show()    
    
    return Energy_Flow 
Example #7
Source File: validation_plots.py    From TheCannon with MIT License 6 votes vote down vote up
def snr_dist():
    fig = plt.figure(figsize=(6,4))
    tr_snr = np.load("../tr_SNR.npz")['arr_0']
    snr = np.load("../val_SNR.npz")['arr_0']
    nbins = 25
    plt.hist(tr_snr, bins=nbins, color='k', histtype="step",
            lw=2, normed=True, alpha=0.3, label="Training Set")
    plt.hist(snr, bins=nbins, color='r', histtype="step",
            lw=2, normed=True, alpha=0.3, label="Validation Set")
    plt.legend()
    plt.xlabel("S/N", fontsize=16)
    plt.tick_params(axis='both', labelsize=16)
    plt.ylabel("Normalized Count", fontsize=16)
    fig.tight_layout()
    plt.show()
    #plt.savefig("snr_dist.png") 
Example #8
Source File: visualize_attention.py    From atis with MIT License 6 votes vote down vote up
def render(self, filename):
        """
        Renders the attention graph over timesteps.

        Args:
          filename (string): filename to save the figure to.
        """
        figure, axes = plt.subplots()
        graph = np.stack(self.attentions)

        axes.imshow(graph, cmap=plt.cm.Blues, interpolation="nearest")
        axes.xaxis.tick_top()
        axes.set_xticks(range(len(self.keys)))
        axes.set_xticklabels(self.keys)
        plt.setp(axes.get_xticklabels(), rotation=90)
        axes.set_yticks(range(len(self.generated_values)))
        axes.set_yticklabels(self.generated_values)
        axes.set_aspect(1, adjustable='box')
        plt.tick_params(axis='x', which='both', bottom='off', top='off')
        plt.tick_params(axis='y', which='both', left='off', right='off')

        figure.savefig(filename) 
Example #9
Source File: plot_threshold_vs_success_trans.py    From pcrnet with MIT License 6 votes vote down vote up
def make_plot(files, labels):
	plt.figure()
	for file_idx in range(len(files)):
		rot_err, trans_err = read_csv(files[file_idx])
		success_dict = count_success(trans_err)

		x_range = success_dict.keys()
		x_range.sort()
		success = []
		for i in x_range:
			success.append(success_dict[i])
		success = np.array(success)/total_cases

		plt.plot(x_range, success, linewidth=3, label=labels[file_idx])
		# plt.scatter(x_range, success, s=50)
	plt.ylabel('Success Ratio', fontsize=40)
	plt.xlabel('Threshold for Translation Error', fontsize=40)
	plt.tick_params(labelsize=40, width=3, length=10)
	plt.grid(True)
	plt.ylim(0,1.005)
	plt.yticks(np.arange(0,1.2,0.2))
	plt.xticks(np.arange(0,2.1,0.2))
	plt.xlim(0,2)
	plt.legend(fontsize=30, loc=4) 
Example #10
Source File: paramagg.py    From autonomio with MIT License 6 votes vote down vote up
def paramagg(data):

    '''
    USE: paramagg(df)

    Provides an overview in one plot for a parameter scan. Useful
    to understand rough distribution of accuracacy and loss for both
    test and train.

    data = a pandas dataframe from hyperscan()
    '''

    plt.figure(num=None, figsize=(8, 8), dpi=80, facecolor='w', edgecolor='k')

    plt.scatter(data.train_loss, data.train_acc, label='train')
    plt.scatter(data.test_loss, data.test_acc, label='test')

    plt.legend(loc='upper right')
    plt.tick_params(axis='both', which='major', pad=15)

    plt.xlabel('loss', fontsize=18, labelpad=15, color="gray")
    plt.ylabel('accuracy', fontsize=18, labelpad=15, color="gray")

    plt.show() 
Example #11
Source File: oraclesplot.py    From actions-for-actions with GNU General Public License v3.0 6 votes vote down vote up
def finalize_plot(allticks,handles):
    plt.locator_params(axis='x', nticks=Noracles,nbins=Noracles)
    plt.yticks([x[0] for x in allticks], [x[1] for x in allticks])
    plt.tick_params(
        axis='y',          # changes apply to the x-axis
        which='both',      # both major and minor ticks are affected
        left='off',      # ticks along the bottom edge are off
        right='off'         # ticks along the top edge are off
    )
    if LEGEND:
        plt.legend([h[0] for h in handles],seriesnames,
                   loc='upper right',borderaxespad=0.,
                   ncol=1,fontsize=10,numpoints=1)
    plt.gcf().tight_layout()


######################################################
# Data processing 
Example #12
Source File: MakeSingleFigure.py    From dybm with Apache License 2.0 6 votes vote down vote up
def subplot(N, n, i, title=True):
    ax = fig.add_subplot(N, 1, i)
    image = np.array(x[n]).T
    ax.imshow(image, cmap=plt.cm.gray, interpolation="nearest")
    if title:
        if n == 0:
            ax.set_title('Before training', **title_font)
        else:
            num = str(n)
            if len(num) > 3:
                num = num[:-3] + "," + num[-3:]
            if len(num) > 7:
                num = num[:-7] + "," + num[-7:]
            ax.set_title('After training ' + num + " times", **title_font)
    plt.tick_params(axis='both', which='both', bottom='off', top='off',
                    right="off", left="off", labelleft="off",
                    labelbottom='off')
    if i == N:
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        plt.arrow(xlim[0], ylim[0] + 1, xlim[1] - xlim[0] - 1.5, 0, width=.1,
                  color="k", clip_on=False, head_width=1., head_length=1.5) 
Example #13
Source File: plot_2D.py    From loss-landscape with MIT License 6 votes vote down vote up
def plot_trajectory(proj_file, dir_file, show=False):
    """ Plot optimization trajectory on the plane spanned by given directions."""

    assert exists(proj_file), 'Projection file does not exist.'
    f = h5py.File(proj_file, 'r')
    fig = plt.figure()
    plt.plot(f['proj_xcoord'], f['proj_ycoord'], marker='.')
    plt.tick_params('y', labelsize='x-large')
    plt.tick_params('x', labelsize='x-large')
    f.close()

    if exists(dir_file):
        f2 = h5py.File(dir_file,'r')
        if 'explained_variance_ratio_' in f2.keys():
            ratio_x = f2['explained_variance_ratio_'][0]
            ratio_y = f2['explained_variance_ratio_'][1]
            plt.xlabel('1st PC: %.2f %%' % (ratio_x*100), fontsize='xx-large')
            plt.ylabel('2nd PC: %.2f %%' % (ratio_y*100), fontsize='xx-large')
        f2.close()

    fig.savefig(proj_file + '.pdf', dpi=300, bbox_inches='tight', format='pdf')
    if show: plt.show() 
Example #14
Source File: agglomerative.py    From atap with Apache License 2.0 6 votes vote down vote up
def plot_dendrogram(self, **kwargs):
        # Distances between each pair of children
        distance = np.arange(self.children.shape[0])
        position = np.arange(self.children.shape[0])

        # Create linkage matrix and then plot the dendrogram
        linkage_matrix = np.column_stack([
            self.children, distance, position]
        ).astype(float)

        # Plot the corresponding dendrogram
        fig, ax = plt.subplots(figsize=(15, 7))  # set size
        ax = dendrogram(linkage_matrix, **kwargs)
        plt.tick_params(axis='x', bottom='off', top='off', labelbottom='off')
        plt.tight_layout()
        plt.show() 
Example #15
Source File: views.py    From API-Manager with GNU Affero General Public License v3.0 6 votes vote down vote up
def plot_topconsumer_bar_chart(self, data):
        x = []
        y = []
        for item in data:
            y.append(item['count'])
            x.append(item['app_name'])
        plt.barh(x, y)
        plt.title("Top consumers", fontsize=10)
        plt.xlabel("Number of API Calls", fontsize=8)
        plt.xticks([])
        plt.ylabel("Consumers", fontsize=8)
        plt.tick_params(axis='y', labelsize=8)
        for i, j in zip(y, x):
            plt.text(i, j, str(i), clip_on=True, ha='center',va='center', fontsize=8)
        plt.tight_layout()
        buf = BytesIO()
        plt.savefig(buf, format='png')
        image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8').replace('\n', '')
        buf.close()
        # Clear the previous plot.
        plt.gcf().clear()
        return image_base64 
Example #16
Source File: views.py    From API-Manager with GNU Affero General Public License v3.0 6 votes vote down vote up
def plot_bar_chart(self, data):
        x = []
        y = []
        for item in data:
            y.append(item['count'])
            x.append(item['Implemented_by_partial_function'])
        plt.barh(x, y)
        plt.title("Top apis", fontsize=10)
        plt.xlabel("Number of API Calls", fontsize=8)
        plt.xticks([])
        plt.ylabel("Partial function", fontsize=8)
        plt.tick_params(axis='y', labelsize=8)
        for i, j in zip(y, x):
            plt.text(i, j, str(i), clip_on=True, ha='center',va='center', fontsize=8)
        plt.tight_layout()
        buf = BytesIO()
        plt.savefig(buf, format='png')
        image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8').replace('\n', '')
        buf.close()
        # Clear the previous plot.
        plt.gcf().clear()
        return image_base64 
Example #17
Source File: source.py    From devito with MIT License 6 votes vote down vote up
def show(self, idx=0, wavelet=None):
        """
        Plot the wavelet of the specified source.

        Parameters
        ----------
        idx : int
            Index of the source point for which to plot wavelet.
        wavelet : ndarray or callable
            Prescribed wavelet instead of one from this symbol.
        """
        wavelet = wavelet or self.data[:, idx]
        plt.figure()
        plt.plot(self.time_values, wavelet)
        plt.xlabel('Time (ms)')
        plt.ylabel('Amplitude')
        plt.tick_params()
        plt.show()

    # Pickling support 
Example #18
Source File: fix_shot_times.py    From nba-movement-data with MIT License 6 votes vote down vote up
def plot(t, plots, shot_ind):
    n = len(plots)

    for i in range(0,n):
        label, data = plots[i]

        plt = py.subplot(n, 1, i+1)
        plt.tick_params(labelsize=8)
        py.grid()
        py.xlim([t[0], t[-1]])
        py.ylabel(label)

        py.plot(t, data, 'k-')
        py.scatter(t[shot_ind], data[shot_ind], marker='*', c='g')

    py.xlabel("Time")
    py.show()
    py.close() 
Example #19
Source File: snns_cnn_cifar10.py    From AmusingPythonCodes with MIT License 5 votes vote down vote up
def plot_metric(title, ylabel, metric):
    # Training Accuracy
    plt.figure()
    plt.title(title, size="xx-large")
    plt.ylabel(ylabel, size="x-large")
    plt.tick_params(axis="x", bottom="off", labelbottom="off")
    # select manually for consistent colors
    plt.plot(metric["selu"], label="SELU", linewidth=2)
    plt.plot(metric["elu"], label="ELU", linewidth=2)
    plt.plot(metric["relu"], label="RELU", linewidth=2)
    plt.legend()
    plt.show() 
Example #20
Source File: backup_weather.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def __example_plot__(self,f_name,region_id,row_index,column_index):
        self.image = load(f_name)
        cursor = self.conn.cursor()

        cursor.execute("select template_id from subject_info where fname = \"" + f_name +"\"")
        template_id = cursor.fetchone()[0]

        cursor.execute("select boundary from cell_boundaries where template_id = " + str(template_id) + " and region_id = " + str(region_id) + " and column_id = " + str(column_index) + " and row_id = " + str(row_index))

        boundary_box = json.loads(cursor.fetchone()[0])

        x,y = zip(*boundary_box)
        x_max = int(max(x))
        y_max = int(max(y))
        x_min = int(min(x))
        y_min = int(min(y))


        sub_image = self.image[np.ix_(range(y_min,y_max+1), range(x_min,x_max+1))]
        fig, ax = plt.subplots()
        im = ax.imshow(sub_image)

        plt.tick_params(
                    axis='x',          # changes apply to the x-axis
                    which='both',      # both major and minor ticks are affected
                    bottom='off',      # ticks along the bottom edge are off
                    top='off',         # ticks along the top edge are off
                    labelbottom='off')

        plt.tick_params(
            axis='y',          # changes apply to the x-axis
            which='both',      # both major and minor ticks are affected
            bottom='off',      # ticks along the bottom edge are off
            top='off',         # ticks along the top edge are off
            labelleft='off')

        plt.show()
        pixels = self.__pixel_generator__(boundary_box)
        self.__pixels_to_clusters__(pixels,True,y_min,y_max) 
Example #21
Source File: couple.py    From scat with MIT License 5 votes vote down vote up
def draw_var(self, data, name):
        plt.figure(figsize=(12, 9)) 
        ax = plt.subplot(111)    
        bar_width = 0.5
        bar_l = [i + 1 for i in range(len(data))]
        tick_pos = [ i + (bar_width/2) for i in bar_l ]

        couples = map(lambda a: a.n, data)
        f = map(lambda a: a.f, data)
        g = map(lambda a: a.g, data)

        ax.bar(bar_l, couples, width=bar_width, label="number of couples", 
                alpha=1, color=Chart.colors["couples"])
        ax.bar(bar_l, f, width=bar_width, label="number of left operands", 
                alpha=1, bottom=couples, color=Chart.colors["left"])
        ax.bar(bar_l, g, width=bar_width, label="number of right operands", 
                alpha=1, bottom=map(lambda a: a[0] + a[1], zip(couples, f)), color=Chart.colors["right"])
                
        # Limit the range of the plot to only where the data is.    
        # Avoid unnecessary whitespace.    
        # plt.ylim(0.9, 1.01)    
        plt.xlim(0, len(data) * 1.05)

        ax.spines["top"].set_visible(False)    
        ax.spines["bottom"].set_visible(False)
        ax.spines["right"].set_visible(False)    
        ax.spines["left"].set_visible(False)

        # Ensure that the axis ticks only show up on the bottom and left of the plot.    
        # Ticks on the right and top of the plot are generally unnecessary chartjunk.    
        ax.get_xaxis().tick_bottom()    
        ax.get_yaxis().tick_left()    

        # plt.xticks(tick_pos, map(lambda a: a.tot_in + a.tot_out, data), rotation="vertical")
        plt.tick_params(axis="both", which="both", bottom="off", top="off",    
                labelbottom="off", left="off", right="off", labelleft="on") 
        plt.legend()

        plt.savefig("test/chart/{}_{}.png".format(self._analysis, name), bbox_inches="tight") 
Example #22
Source File: chart.py    From scat with MIT License 5 votes vote down vote up
def draw(self, data, name):
        plt.figure(figsize=(12, 9)) 
        ax = plt.subplot(111)    
        ax.spines["top"].set_visible(False)    
        ax.spines["bottom"].set_visible(False)
        ax.spines["right"].set_visible(False)    
        ax.spines["left"].set_visible(False)
        plt.plot([0, max(data.keys())*1.05], [1, 1], "-", lw=0.5, color="black")
        plt.plot([0, max(data.keys())*1.05], [0, 0], "-", lw=0.5, color="black")
        # Ensure that the axis ticks only show up on the bottom and left of the plot.    
        # Ticks on the right and top of the plot are generally unnecessary chartjunk.    
        ax.get_xaxis().tick_bottom()    
        ax.get_yaxis().tick_left()    

        # Limit the range of the plot to only where the data is.    
        # Avoid unnecessary whitespace.    
        plt.ylim(-0.1, 1.1)    
        plt.xlim(0, max(data.keys()) * 1.05)

        plt.tick_params(axis="both", which="both", bottom="off", top="off",    
                labelbottom="on", left="off", right="off", labelleft="on") 
        acc = [v[0] for v in data.values()]
        fp = [v[1]/float(v[3]) for v in data.values()]
        fn = [v[2]/float(v[3]) for v in data.values()]
        tot = [v[3] for v in data.values()]
        norm = colors.Normalize(0, max(tot))
        tot = map(lambda a: norm(a), tot)
        plt.plot(data.keys(), acc, 'o', lw=1, color=Chart.colors["acc"], label="accuracy")
        if "min_calls" in name or "min_vals" in name:
            plt.plot(data.keys(), tot, 'o', lw=1, color=Chart.colors["tot"], label="number of functions (normalized)")
        plt.plot(data.keys(), fn, 'o', lw=1, color=Chart.colors["fn"], label="false negatives (% of total)")
        plt.plot(data.keys(), fp, 'o', lw=1, color=Chart.colors["fp"], label="false positives (% of total)")
        plt.legend()

        plt.savefig("test/chart/{}_{}.png".format(self._analysis, name), bbox_inches="tight") 
Example #23
Source File: helper_analysis.py    From pointnet-registration-framework with MIT License 5 votes vote down vote up
def generate_loss_3Dplots(self, axis, x_axis_param):
		# Parameters to deal with:
		# axis					This will decide the rotation or translation of point cloud about a particular axis. 'x' or 'y' or 'z'
		# x_axis_param			This will decide either to rotate or translate the point cloud 'rotation' or 'translation'.

		template_data = self.templates[self.template_idx,:,:].reshape((1,MAX_NUM_POINT,3))		# Extract the template and reshape it.
		template_data = template_data[:,0:self.NUM_POINT,:]

		loss = []
		angles_x = []
		angles_y = []														# Store the losses.
		if x_axis_param == 'rotation':
			# Loop to find loss for various angles from -90 to 90.
			for i in range(-90,91):
				print('I: {}'.format(i))
				for j in range(-90,91):
					if axis == 'XY':
						gt_pose = np.array([[0.0, 0.0, 0.0, i*(np.pi/180), j*(np.pi/180), 0.0]])			# New poses as per each index.
					if axis == 'YZ':
						gt_pose = np.array([[0.0, 0.0, 0.0, 0.0, i*(np.pi/180), j*(np.pi/180)]])			# New poses as per each index.
					if axis == 'XZ':
						gt_pose = np.array([[0.0, 0.0, 0.0, i*(np.pi/180), 0.0, j*(np.pi/180)]])			# New poses as per each index.

					source_data = helper.apply_transformation(template_data,gt_pose)		# Generate Source Data.
					final_pose, TRANSFORMATIONS, loss_i, predicted_data, transformed_source_data, _, _ = self.test_one_case(template_data, source_data)	# Find final transformation by network.
					loss.append(loss_i)
					angles_x.append(i)
					angles_y.append(j)
					# helper.display_three_clouds(template_data[0],source_data[0],transformed_source_data,"Results")

			fig = plt.figure()

			ax = fig.add_subplot(111,projection='3d')
			ax.scatter(angles_x,angles_y,loss)
			ax.set_xlabel('Rotation Angle about '+axis[0]+'-axis', fontsize=25, labelpad=25)
			ax.set_ylabel('Rotation Angle about '+axis[1]+'-axis', fontsize=25, labelpad=25)
			ax.set_zlabel('Error in Poses (L2 Norm)', fontsize=25, labelpad=25)
			ax.tick_params(labelsize=25)
			plt.show() 
Example #24
Source File: timit.py    From pyroomacoustics with MIT License 5 votes vote down vote up
def plot(self, L=512, hop=128, zpb=0, phonems=False, **kwargs):

        try:
            import matplotlib.pyplot as plt
            import seaborn as sns
        except ImportError:
            return

        sns.set_style('white')
        X = stft(self.data, L=L, hop=hop, zp_back=zpb, transform=np.fft.rfft, win=np.hanning(L+zpb))
        X = 10*np.log10(np.abs(X)**2).T

        plt.imshow(X, origin='lower', aspect='auto')

        ticks = []
        ticklabels = []

        if phonems:
            for phonem in self.phonems:
                plt.axvline(x=phonem['bnd'][0]/hop)
                plt.axvline(x=phonem['bnd'][1]/hop)
                ticks.append((phonem['bnd'][1]+phonem['bnd'][0])/2/hop)
                ticklabels.append(phonem['name'])

        else:
            for word in self.words:
                plt.axvline(x=word.boundaries[0]/hop)
                plt.axvline(x=word.boundaries[1]/hop)
                ticks.append((word.boundaries[1]+word.boundaries[0])/2/hop)
                ticklabels.append(word.word)

        plt.xticks(ticks, ticklabels, rotation=-45)
        plt.yticks([],[])
        plt.tick_params(axis='both', which='major', labelsize=14) 
Example #25
Source File: tools.py    From DMDpack with GNU General Public License v3.0 5 votes vote down vote up
def plot_modes( omega, color='r', color2='blue', name=None, maker='o', alpha = 0.3, labelon=True, xytx=-20, xyty=20):
    
    m = len(omega)
    
    labels = ['mode{0}'.format(i) for i in range(m)]
    plt.subplots_adjust(bottom = 0.1)
    #vert line
    plt.axvline(x=0,color='k',ls='dashed', lw=2)
    #horiz line
    plt.axhline(y=0,color='k',ls='dashed', lw=2)

    #plot omega    
    plt.scatter( omega.real, omega.imag, marker = maker, c = color, s=20*9, label = name )

    #plot labels
    if labelon==True: 
        for label, x, y in zip(labels, omega.real, omega.imag):
            xytx2, xyty2 =  xytx,   xyty
            color2=np.array([0.4,  0.4,  1.])
            plt.annotate(
                    label, 
                    xy = (x, y), xytext = (xytx2, xyty2),
                    textcoords = 'offset points', ha = 'right', va = 'bottom', fontsize=12, color='white',
                    bbox = dict(boxstyle = 'round,pad=0.5', fc = color2, alpha = alpha),
                    arrowprops = dict(facecolor='black', shrink=0.11))
            
    
    plt.grid(True)
    plt.tight_layout()
    plt.xlabel('Real', fontsize=25)
    plt.ylabel('Imaginary', fontsize=25)
    plt.tick_params(axis='y', labelsize=18) 
    plt.tick_params(axis='x', labelsize=18) 
    #if name != None: plt.legend(loc="lower right", fontsize=25)

    plt.show() 
Example #26
Source File: layout.py    From floris with Apache License 2.0 5 votes vote down vote up
def plot_layout_opt_results(self, sol):
        """
        Method to plot the old and new locations of the layout opitimization.
        """
        locsx = sol.getDVs()["x"]
        locsy = sol.getDVs()["y"]

        plt.figure(figsize=(9, 6))
        fontsize = 16
        plt.plot(self.x0, self.y0, "ob")
        plt.plot(locsx, locsy, "or")
        # plt.title('Layout Optimization Results', fontsize=fontsize)
        plt.xlabel("x (m)", fontsize=fontsize)
        plt.ylabel("y (m)", fontsize=fontsize)
        plt.axis("equal")
        plt.grid()
        plt.tick_params(which="both", labelsize=fontsize)
        plt.legend(
            ["Old locations", "New locations"],
            loc="lower center",
            bbox_to_anchor=(0.5, 1.01),
            ncol=2,
            fontsize=fontsize,
        )

        verts = self.boundaries
        for i in range(len(verts)):
            if i == len(verts) - 1:
                plt.plot([verts[i][0], verts[0][0]], [verts[i][1], verts[0][1]], "b")
            else:
                plt.plot(
                    [verts[i][0], verts[i + 1][0]], [verts[i][1], verts[i + 1][1]], "b"
                )

        plt.show()

    ###########################################################################
    # Properties
    ########################################################################### 
Example #27
Source File: plotter.py    From rl-reliability-metrics with Apache License 2.0 5 votes vote down vote up
def _configure_axes(self, y_label, y_ticks=None, y_tick_labels=None):
    """Configure axis limits and labels."""
    algo_abbreviations = [
        plot_utils.ALGO_ABBREVIATIONS[algo] for algo in self.algorithms
    ]
    plt.xticks(range(1, self.n_algo + 1), algo_abbreviations)
    plt.xlim(0, len(self.algorithms) + 1)
    if y_ticks:
      plt.yticks(y_ticks)
    if y_tick_labels:
      plt.gca().set_yticklabels(y_tick_labels)
    if self.subplot_axis_labels:
      plt.xlabel('algorithm', fontsize=16)
      plt.ylabel(y_label, fontsize=16)
    plt.tick_params(top='off') 
Example #28
Source File: helper_analysis.py    From pcrnet with MIT License 5 votes vote down vote up
def generate_loss_vs_itr(self, axis, x_axis_param):
		# axis					This will decide the rotation or translation of point cloud about a particular axis. 'x' or 'y' or 'z'
		# x_axis_param			This will decide either to rotate or translate the point cloud 'rotation' or 'translation'.

		template_data = self.templates[self.template_idx,:,:].reshape((1,MAX_NUM_POINT,3))		# Extract the template and reshape it.
		template_data = template_data[:,0:self.NUM_POINT,:]

		loss = []
		angles_x = []
		angles_y = []														# Store the losses.
		if x_axis_param == 'rotation':
			# Loop to find loss for various angles from -90 to 90.
			for i in [4,8,12,16,20,24,28,32]:
				self.set_MAX_LOOPS(i)
				print('I: {}'.format(i))
				for j in range(-90,91):
					if axis == 'X':
						gt_pose = np.array([[0.0, 0.0, 0.0, j*(np.pi/180), 0.0, 0.0]])			# New poses as per each index.
					if axis == 'Y':
						gt_pose = np.array([[0.0, 0.0, 0.0, 0.0, j*(np.pi/180), 0.0]])			# New poses as per each index.
					if axis == 'Z':
						gt_pose = np.array([[0.0, 0.0, 0.0, 0.0, 0.0, j*(np.pi/180)]])			# New poses as per each index.

					source_data = helper.apply_transformation(template_data,gt_pose)		# Generate Source Data.
					final_pose, TRANSFORMATIONS, loss_i, predicted_data, transformed_source_data, _ = self.test_one_case(template_data,source_data)	# Find final transformation by network.
					loss.append(np.sum(np.square(final_pose[0]-gt_pose[0]))/6)
					angles_x.append(i)
					angles_y.append(j)

			fig = plt.figure()

			ax = fig.add_subplot(111,projection='3d')
			ax.scatter(angles_x,angles_y,loss)
			ax.set_xlabel('No of Iterations', fontsize=25, labelpad=25)
			ax.set_ylabel('Rotation Angle about '+axis[0]+'-axis', fontsize=25, labelpad=25)
			ax.set_zlabel('Error in Poses (L2 Norm)', fontsize=25, labelpad=25)
			ax.tick_params(labelsize=25)
			plt.show()

	# Generates & Stores Time, Rotation Error, Translation Error & No. of iterations to a .csv file.
	# Also stores mean and variance of all parameters in a .txt file. 
Example #29
Source File: document_clustering.py    From text-analytics-with-python with Apache License 2.0 5 votes vote down vote up
def plot_hierarchical_clusters(linkage_matrix, movie_data, figure_size=(8,12)):
    # set size
    fig, ax = plt.subplots(figsize=figure_size) 
    movie_titles = movie_data['Title'].values.tolist()
    # plot dendrogram
    ax = dendrogram(linkage_matrix, orientation="left", labels=movie_titles)
    plt.tick_params(axis= 'x',   
                    which='both',  
                    bottom='off',
                    top='off',
                    labelbottom='off')
    plt.tight_layout()
    plt.savefig('ward_hierachical_clusters.png', dpi=200)

# build ward's linkage matrix 
Example #30
Source File: helper_analysis.py    From pcrnet with MIT License 5 votes vote down vote up
def generate_loss_3Dplots(self, axis, x_axis_param):
		# Parameters to deal with:
		# axis					This will decide the rotation or translation of point cloud about a particular axis. 'x' or 'y' or 'z'
		# x_axis_param			This will decide either to rotate or translate the point cloud 'rotation' or 'translation'.

		template_data = self.templates[self.template_idx,:,:].reshape((1,MAX_NUM_POINT,3))		# Extract the template and reshape it.
		template_data = template_data[:,0:self.NUM_POINT,:]

		loss = []
		angles_x = []
		angles_y = []														# Store the losses.
		if x_axis_param == 'rotation':
			# Loop to find loss for various angles from -90 to 90.
			for i in range(-90,91):
				print('I: {}'.format(i))
				for j in range(-90,91):
					if axis == 'XY':
						gt_pose = np.array([[0.0, 0.0, 0.0, i*(np.pi/180), j*(np.pi/180), 0.0]])			# New poses as per each index.
					if axis == 'YZ':
						gt_pose = np.array([[0.0, 0.0, 0.0, 0.0, i*(np.pi/180), j*(np.pi/180)]])			# New poses as per each index.
					if axis == 'XZ':
						gt_pose = np.array([[0.0, 0.0, 0.0, i*(np.pi/180), 0.0, j*(np.pi/180)]])			# New poses as per each index.

					source_data = helper.apply_transformation(template_data,gt_pose)		# Generate Source Data.
					final_pose, TRANSFORMATIONS, loss_i, predicted_data, transformed_source_data, _, _ = self.test_one_case(template_data, source_data)	# Find final transformation by network.
					loss.append(loss_i)
					angles_x.append(i)
					angles_y.append(j)
					# helper.display_three_clouds(template_data[0],source_data[0],transformed_source_data,"Results")

			fig = plt.figure()

			ax = fig.add_subplot(111,projection='3d')
			ax.scatter(angles_x,angles_y,loss)
			ax.set_xlabel('Rotation Angle about '+axis[0]+'-axis', fontsize=25, labelpad=25)
			ax.set_ylabel('Rotation Angle about '+axis[1]+'-axis', fontsize=25, labelpad=25)
			ax.set_zlabel('Error in Poses (L2 Norm)', fontsize=25, labelpad=25)
			ax.tick_params(labelsize=25)
			plt.show()