Python matplotlib.ticker.LinearLocator() Examples

The following are 21 code examples of matplotlib.ticker.LinearLocator(). 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.ticker , or try the search function .
Example #1
Source File: deforme.py    From Image-Restoration with MIT License 6 votes vote down vote up
def plot_surface(x,y,z):
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)

    # Customize the z axis.
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    if save_info:
        fig.tight_layout()
        fig.savefig('./gaussian'+ str(idx) + '.png')
    plt.show() 
Example #2
Source File: lagrange.py    From pyray with MIT License 6 votes vote down vote up
def three_d_grid():
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    # Make data.
    X = np.arange(-5, 5, 0.25)
    Y = np.arange(-5, 5, 0.25)
    X, Y = np.meshgrid(X, Y)
    R = (X**3 + Y**3)
    Z = R

    # Plot the surface.
    surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                        linewidth=0, antialiased=False)

    # Customize the z axis.
    #ax.set_zlim(-1.01, 1.01)
    #ax.zaxis.set_major_locator(LinearLocator(10))
    #ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show() 
Example #3
Source File: mainwindow.py    From Turing with MIT License 5 votes vote down vote up
def plot_window(xmin, xmax, ymin, ymax, xgrad=0, ygrad=0):
    GuiState.plot_axes.set_xlim(xmin, xmax)
    GuiState.plot_axes.set_ylim(ymin, ymax)

    GuiState.plot_axes.get_xaxis().set_major_locator(
        AutoLocator() if xgrad == 0 else LinearLocator(abs(int((xmax - xmin) / xgrad)) + 1))
    GuiState.plot_axes.get_yaxis().set_major_locator(
        AutoLocator() if ygrad == 0 else LinearLocator(abs(int((ymax - ymin) / ygrad)) + 1)) 
Example #4
Source File: test_ticker.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_set_params(self):
        """
        Create linear locator with presets={}, numticks=2 and change it to
        something else. See if change was successful. Should not exception.
        """
        loc = mticker.LinearLocator(numticks=2)
        loc.set_params(numticks=8, presets={(0, 1): []})
        assert loc.numticks == 8
        assert loc.presets == {(0, 1): []} 
Example #5
Source File: test_ticker.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_basic(self):
        loc = mticker.LinearLocator(numticks=3)
        test_value = np.array([-0.8, -0.3, 0.2])
        assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value) 
Example #6
Source File: tools.py    From L2L with GNU General Public License v3.0 5 votes vote down vote up
def plot(fn, random_state):
    """
    Implements plotting of 2D functions generated by FunctionGenerator
    :param fn: Instance of FunctionGenerator
    """
    import numpy as np
    from l2l.matplotlib_ import plt
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter

    fig = plt.figure()
    ax = fig.gca(projection=Axes3D.name)

    # Make data.
    X = np.arange(fn.bound[0], fn.bound[1], 0.05)
    Y = np.arange(fn.bound[0], fn.bound[1], 0.05)
    XX, YY = np.meshgrid(X, Y)
    Z = [fn.cost_function([x, y], random_state=random_state) for x, y in zip(XX.ravel(), YY.ravel())]
    Z = np.array(Z).reshape(XX.shape)

    # Plot the surface.
    surf = ax.plot_surface(XX, YY, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

    # Customize the z axis.
    # ax.set_zlim(-1.01, 1.01)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    W = np.where(Z == np.min(Z))
    ax.set(title='Min value is %.2f at (%.2f, %.2f)' % (np.min(Z), X[W[0]], Y[W[1]]))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.savefig('function.png')
    plt.show() 
Example #7
Source File: plot_results.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def plot_tang(X, Y, Z, title, npts=None):

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    # Plot the surface.
    surf = ax.plot_surface(X, Y, Z, cmap="viridis",
                           linewidth=0, antialiased=False)

    # Customize the z axis.
    ax.set_zlim(-100, 250)
    ax.zaxis.set_tick_params(pad=8)
    ax.zaxis.set_major_locator(LinearLocator(5))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)

    if "teacher" in title:
        plt.suptitle("Teacher model")

    if "student" in title and "sobolev" not in title:
        assert (npts is not None)
        plt.suptitle("Student model %s training pts" % npts)

    if "sobolev" in title:
        assert (npts is not None)
        plt.suptitle("Student model %s training pts + Sobolev" % npts)

    else:
        plt.suptitle("Styblinski Tang function")

    plt.savefig(title) 
Example #8
Source File: test_ticker.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_set_params(self):
        """
        Create linear locator with presets={}, numticks=2 and change it to
        something else. See if change was successful. Should not exception.
        """
        loc = mticker.LinearLocator(numticks=2)
        loc.set_params(numticks=8, presets={(0, 1): []})
        assert loc.numticks == 8
        assert loc.presets == {(0, 1): []} 
Example #9
Source File: test_ticker.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_basic(self):
        loc = mticker.LinearLocator(numticks=3)
        test_value = np.array([-0.8, -0.3, 0.2])
        assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value) 
Example #10
Source File: simulation.py    From hypermax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createContributionChartExample(type=4):
    algo = AlgorithmSimulation()
    param1 = algo.createHyperParameter()
    contribution = algo.createHyperParameterContribution(param1, type=type)

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d, Axes3D
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from matplotlib import cm

    fig, ax = plt.subplots()

    print(contribution['func'])
    funcStore = {}
    exec("import math\nimport scipy.interpolate\nfunc = " + contribution['func'], funcStore)
    func = funcStore['func']

    xVals = numpy.linspace(0, 1, 25)

    yVals = []
    for x in xVals:
        yVals.append(func(x))

    # Plot the surface.
    surf = ax.scatter(numpy.array(xVals), numpy.array(yVals), cmap=cm.coolwarm, linewidth=0, antialiased=False, vmin=0, vmax=1)

    plt.show() 
Example #11
Source File: simulation.py    From hypermax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createInteractionChartExample():
    algo = AlgorithmSimulation()
    param1 = algo.createHyperParameter()
    param2 = algo.createHyperParameter()
    interaction = algo.createHyperParameterInteraction(param1, param2, type=3)

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d, Axes3D
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from matplotlib import cm

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    funcStore = {}
    exec("import math\nimport scipy.interpolate\nfrom scipy.stats import norm\nfunc = " + interaction['func'], funcStore)
    func = funcStore['func']

    xVals = numpy.linspace(0, 1, 25)
    yVals = numpy.linspace(0, 1, 25)

    grid = []
    for x in xVals:
        row = []
        for y in yVals:
            row.append(func(x, y)[0])
        grid.append(row)

    # Plot the surface.
    xVals, yVals = numpy.meshgrid(xVals, yVals)
    surf = ax.plot_surface(xVals, yVals, numpy.array(grid), cmap=cm.coolwarm, linewidth=0, antialiased=False, vmin=0, vmax=1)

    # Customize the z axis.
    ax.set_zlim(0, 1.00)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show() 
Example #12
Source File: simulation.py    From hypermax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createContributionChartExample():
    algo = AlgorithmSimulation()
    param1 = algo.createHyperParameter()
    contribution = algo.createHyperParameterContribution(param1, type=4)

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d, Axes3D
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from matplotlib import cm

    fig, ax = plt.subplots()

    print(contribution['func'])
    funcStore = {}
    exec("import math\nimport scipy.interpolate\nfunc = " + contribution['func'], funcStore)
    func = funcStore['func']

    xVals = numpy.linspace(0, 1, 25)

    yVals = []
    for x in xVals:
        yVals.append(func(x))

    # Plot the surface.
    surf = ax.scatter(numpy.array(xVals), numpy.array(yVals), cmap=cm.coolwarm, linewidth=0, antialiased=False, vmin=0, vmax=1)

    plt.show() 
Example #13
Source File: simulation.py    From hypermax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createInteractionChartExample():
    algo = AlgorithmSimulation()
    param1 = algo.createHyperParameter()
    param2 = algo.createHyperParameter()
    interaction = algo.createHyperParameterInteraction(param1, param2, type=3)

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d, Axes3D
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from matplotlib import cm

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    funcStore = {}
    exec("import math\nimport scipy.interpolate\nfrom scipy.stats import norm\nfunc = " + interaction['func'], funcStore)
    func = funcStore['func']

    xVals = numpy.linspace(0, 1, 25)
    yVals = numpy.linspace(0, 1, 25)

    grid = []
    for x in xVals:
        row = []
        for y in yVals:
            row.append(func(x, y)[0])
        grid.append(row)

    # Plot the surface.
    xVals, yVals = numpy.meshgrid(xVals, yVals)
    surf = ax.plot_surface(xVals, yVals, numpy.array(grid), cmap=cm.coolwarm, linewidth=0, antialiased=False, vmin=0, vmax=1)

    # Customize the z axis.
    ax.set_zlim(0, 1.00)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show() 
Example #14
Source File: test_ticker.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_LinearLocator():
    loc = mticker.LinearLocator(numticks=3)
    test_value = np.array([-0.8, -0.3, 0.2])
    assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value) 
Example #15
Source File: test_ticker.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_LinearLocator():
    loc = mticker.LinearLocator(numticks=3)
    test_value = np.array([-0.8, -0.3, 0.2])
    assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value) 
Example #16
Source File: read_NOM_maps.py    From xrt with MIT License 5 votes vote down vote up
def plot_NOM_3D(fname):
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter

    xL, yL, zL = np.loadtxt(fname+'.dat', unpack=True)
    nX = (yL == yL[0]).sum()
    nY = (xL == xL[0]).sum()
    x = xL.reshape((nY, nX))
    y = yL.reshape((nY, nX))
    z = zL.reshape((nY, nX))
    x1D = xL[:nX]
    y1D = yL[::nX]
#    z += z[::-1, :]
    zmax = abs(z).max()

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False, alpha=0.5)
    ax.set_zlim(-zmax, zmax)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    fig.colorbar(surf, shrink=0.5, aspect=5)

    splineZ = ndimage.spline_filter(z.T)
    nrays = 1e3
    xnew = np.random.uniform(x1D[0], x1D[-1], nrays)
    ynew = np.random.uniform(y1D[0], y1D[-1], nrays)
    coords = np.array([(xnew-x1D[0]) / (x1D[-1]-x1D[0]) * (nX-1),
                       (ynew-y1D[0]) / (y1D[-1]-y1D[0]) * (nY-1)])
    znew = ndimage.map_coordinates(splineZ, coords, prefilter=True)
    ax.scatter(xnew, ynew, znew, c=znew, marker='o', color='gray', s=50,
               cmap=cm.coolwarm)

    fig.savefig(fname+'_3d.png')
    plt.show() 
Example #17
Source File: test_surface.py    From opticspy with MIT License 5 votes vote down vote up
def spherical_surf(l1):
	R = 1.02
	l1 = l1  #surface matrix length
	theta = __np__.linspace(0, 2*__np__.pi, l1)
	rho = __np__.linspace(0, 1, l1)
	[u,r] = __np__.meshgrid(theta,rho)
	X = r*__cos__(u)
	Y = r*__sin__(u)
	Z = __sqrt__(R**2-r**2)-__sqrt__(R**2-1)
	v_1 = max(abs(Z.max()),abs(Z.min()))

	noise = (__np__.random.rand(len(Z),len(Z))*2-1)*0.05*v_1
	Z = Z+noise
	fig = __plt__.figure(figsize=(12, 8), dpi=80)
	ax = fig.gca(projection='3d')
	surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=__cm__.RdYlGn,\
								linewidth=0, antialiased=False, alpha = 0.6)
	v = max(abs(Z.max()),abs(Z.min()))
	ax.set_zlim(-1, 2)
	ax.zaxis.set_major_locator(__LinearLocator__(10))
	ax.zaxis.set_major_formatter(__FormatStrFormatter__('%.02f'))
	cset = ax.contourf(X, Y, Z, zdir='z', offset=-1, cmap=__cm__.RdYlGn)
	fig.colorbar(surf, shrink=1, aspect=30)
	__plt__.title('Test Surface: Spherical surface with some noise',fontsize=16)
	__plt__.show()

	#Generate test surface matrix from a detector
	x = __np__.linspace(-1, 1, l1)
	y = __np__.linspace(-1, 1, l1)
	[X,Y] = __np__.meshgrid(x,y)
	Z = __sqrt__(R**2-(X**2+Y**2))-__sqrt__(R**2-1)+noise
	for i in range(len(Z)):
		for j in range(len(Z)):
			if x[i]**2+y[j]**2>1:
				Z[i][j]=0
	return Z 
Example #18
Source File: zernike_rec.py    From opticspy with MIT License 5 votes vote down vote up
def zernikesurface(self):
		"""
		------------------------------------------------
		zernikesurface(self, label_1 = True):

		Return a 3D Zernike Polynomials surface figure

		label_1: default show label

		------------------------------------------------
		"""
		a = self.__a__
		b = __sqrt__(1-a**2)
		x1 = __np__.linspace(-a, a, 50)
		y1 = __np__.linspace(-b, b, 50)
		[X,Y] = __np__.meshgrid(x1,y1)
		Z = __zernikecartesian__(self.__coefficients__,a,X,Y)
		fig = __plt__.figure(figsize=(12, 8), dpi=80)
		ax = fig.gca(projection='3d')
		surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=__cm__.RdYlGn,
	        linewidth=0, antialiased=False, alpha = 0.6)

		ax.auto_scale_xyz([-1, 1], [-1, 1], [Z.max(), Z.min()])
		# ax.set_xlim(-a, a)
		# ax.set_ylim(-b, b)
		# v = max(abs(Z.max()),abs(Z.min()))
		# ax.set_zlim(-v*5, v*5)
		# cset = ax.contourf(X, Y, Z, zdir='z', offset=-v*5, cmap=__cm__.RdYlGn)

		# ax.zaxis.set_major_locator(__LinearLocator__(10))
		# ax.zaxis.set_major_formatter(__FormatStrFormatter__('%.02f'))
		fig.colorbar(surf, shrink=1, aspect=30)

		# p2v = round(__tools__.peak2valley(Z),5)
		# rms1 = round(__tools__.rms(Z),5)
		__plt__.show() 
Example #19
Source File: test_ticker.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_set_params(self):
        """
        Create linear locator with presets={}, numticks=2 and change it to
        something else. See if change was successful. Should not exception.
        """
        loc = mticker.LinearLocator(numticks=2)
        loc.set_params(numticks=8, presets={(0, 1): []})
        assert loc.numticks == 8
        assert loc.presets == {(0, 1): []} 
Example #20
Source File: test_ticker.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_basic(self):
        loc = mticker.LinearLocator(numticks=3)
        test_value = np.array([-0.8, -0.3, 0.2])
        assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value) 
Example #21
Source File: zernike.py    From opticspy with MIT License 4 votes vote down vote up
def zernikesurface(self, label = True, zlim=[], matrix = False):
		"""
		------------------------------------------------
		zernikesurface(self, label_1 = True):

		Return a 3D Zernike Polynomials surface figure

		label_1: default show label

		------------------------------------------------
		"""
		theta = __np__.linspace(0, 2*__np__.pi, 100)
		rho = __np__.linspace(0, 1, 100)
		[u,r] = __np__.meshgrid(theta,rho)
		X = r*__cos__(u)
		Y = r*__sin__(u)
		Z = __interferometer__.__zernikepolar__(self.__coefficients__,r,u)
		fig = __plt__.figure(figsize=(12, 8), dpi=80)
		ax = fig.gca(projection='3d')
		surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=__cm__.RdYlGn,
	        linewidth=0, antialiased=False, alpha = 0.6)

		if zlim == []:
			v = max(abs(Z.max()),abs(Z.min()))
			ax.set_zlim(-v*5, v*5)
			cset = ax.contourf(X, Y, Z, zdir='z', offset=-v*5, cmap=__cm__.RdYlGn)
		else:
			ax.set_zlim(zlim[0], zlim[1])
			cset = ax.contourf(X, Y, Z, zdir='z', offset=zlim[0], cmap=__cm__.RdYlGn)

		ax.zaxis.set_major_locator(__LinearLocator__(10))
		ax.zaxis.set_major_formatter(__FormatStrFormatter__('%.02f'))
		fig.colorbar(surf, shrink=1, aspect=30)


		p2v = round(__tools__.peak2valley(Z),5)
		rms1 = round(__tools__.rms(Z),5)

		label_1 = self.listcoefficient()[0]+"P-V: "+str(p2v)+"\n"+"RMS: "+str(rms1)
		if label == True:
			__plt__.title('Zernike Polynomials Surface',fontsize=18)
			ax.text2D(0.02, 0.1, label_1, transform=ax.transAxes,fontsize=14)
		else:
			pass
		__plt__.show()

		if matrix == True:
			return Z
		else:
			pass