def plot_iris_k_mean(self):
     X          = self._x_iris
     y          = self._y_iris
     estimators = {
           'k_means_iris_3' : cluster.KMeans(n_clusters = 3),
           'k_means_iris_8' : cluster.KMeans(n_clusters = 8),
           'k_means_iris_bad_init' : cluster.KMeans(n_clusters = 3, n_init = 1, init='random')
     }
     fignum     = 1
     for name, est in estimators.items():
         fig = plt.figure(fignum, figsize=(4, 3))
         plt.clf()
         ax  = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
     
         plt.cla()
         est.fit(X)
         labels = est.labels_
     
         ax.scatter(X[:, 3], X[:, 0], X[:, 2], c = labels.astype(np.float))
     
         ax.w_xaxis.set_ticklabels([])
         ax.w_yaxis.set_ticklabels([])
         ax.w_zaxis.set_ticklabels([])
         ax.set_xlabel('Petal width')
         ax.set_ylabel('Sepal length')
         ax.set_zlabel('Petal length')
         plt.savefig("k-means-iris-%s.jpg" % name)
         fignum = fignum + 1
     
     # Plot the ground truth
     fig = plt.figure(fignum, figsize=(4, 3))
     plt.clf()
     ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
     
     plt.cla()
     
     for name, label in [('Setosa', 0),
                         ('Versicolour', 1),
                         ('Virginica', 2)]:
         ax.text3D(X[y == label, 3].mean(),
                   X[y == label, 0].mean() + 1.5,
                   X[y == label, 2].mean(), name,
                   horizontalalignment='center',
                   bbox=dict(alpha = .5, edgecolor = 'w', facecolor = 'w'))
     # Reorder the labels to have colors matching the cluster results
     y = np.choose(y, [1, 2, 0]).astype(np.float)
     ax.scatter(X[:, 3], X[:, 0], X[:, 2], c = y)
     
     ax.w_xaxis.set_ticklabels([])
     ax.w_yaxis.set_ticklabels([])
     ax.w_zaxis.set_ticklabels([])
     ax.set_xlabel('Petal width')
     ax.set_ylabel('Sepal length')
     ax.set_zlabel('Petal length')
     plt.savefig("k-means-iris-truth.jpg")
예제 #2
0
    def plot(self, dataframe: pd.DataFrame, labels: List[int], centroids: List[List[float]], zoom = False):
         # plot dei dati presi dal db
        if self.n_components == 2: # 2D
            ax = plt.subplot(1, 1, 1)
            scat = ax.scatter(dataframe['x'], dataframe['y'], c=labels, cmap=self.cmap, label=labels)
        else: # 3D
            fig = plt.figure()
            ax = Axes3D(fig)
            scat = ax.scatter(dataframe['x'], dataframe['y'], dataframe['z'], c=labels, cmap=self.cmap, label=labels, alpha=0.1)

        # handle = list(scat.legend_elements())
        # handle.append(mpatches.Patch(color='black', label='Selected patient'))

        legend = ax.legend(*scat.legend_elements(), loc='upper right', title='Clusters') # inserimento legenda
        ax.add_artist(legend)

        # arr = np.arange(len(centroids))
        # ax.scatter(centroids[:, 0], centroids[:, 1], c=arr, cmap=self.cmap, marker='*', s=500, lw=1.5, edgecolor=(0, 0, 0, 1))
        # if (self.n_components == 2):

        if zoom is True:
            ax.set_xlim(-100000, 0)
            ax.set_ylim(-50, 150)

        ax.set_xticklabels([])
        ax.set_yticklabels([])
        if (self.n_components == 3):
            ax.set_zticklabels([])

        return ax, plt
예제 #3
0
 def drawplot(self):
     fig = plt.figure(1)
     ax = Axes3D(fig)
     ax.scatter(self.placex, self.placey, self.placez)
     ax.scatter(self.SPplacex, self.SPplacey, self.SPplacez)
     ax.text(
         self.placex, self.placey, self.placez,
         'loc=' + str([self.placex, self.placey, self.placez]) + '\n' +
         'V=' + str(self.v) + '\n' + 'P=' + str(self.P))
     if self.cline != -1:
         ax.plot([self.placex, self.SPplacex[self.cline]],
                 [self.placey, self.SPplacey[self.cline]],
                 [self.placez, self.SPplacez[self.cline]], '--')
         ax.text((self.placex + self.SPplacex[self.cline]) / 2,
                 (self.placey + self.SPplacey[self.cline]) / 2,
                 (self.placez + self.SPplacez[self.cline]) / 2,
                 str(self.rate[self.cline]))
         ax.text(
             self.SPplacex[self.cline], self.SPplacex[self.cline],
             self.SPplacex[self.cline],
             'loc=' + str(self.SPplacex[self.cline]) +
             str(self.SPplacex[self.cline]) +
             str(self.SPplacex[self.cline]) + '\n' + 'G=' +
             str(self.G[self.cline]) + '\n')
     ax.set_xlim(-1000, 1000)
     ax.set_ylim(-1000, 1000)
     ax.set_zlim(0, 150)
     plt.show()
예제 #4
0
 def showCluster(self):
     numSamples, dim = self.dataset.shape
     from mpl_toolkits.mplot3d.axes3d import Axes3D
     from matplotlib import pyplot as plt
     import matplotlib as mpl
     mpl.style.use('default')
     fig = plt.figure()
     ax = Axes3D(fig)
     mark = ['v', '^', '<', '>', '1', '2', '3', '4', '8', 's']
     color = ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C0']
     for i in range(numSamples):
         markIndex = int(self.clusterAssment[i, 0])
         ax.scatter(self.dataset[i, 3],
                    self.dataset[i, 1],
                    self.dataset[i, 0],
                    c=color[markIndex],
                    S=20)
     for i in range(self.kopt):
         ax.scatter(self.centroids[i, 3],
                    self.centroids[i, 1],
                    self.centroids[i, 0],
                    c=color[i],
                    marker=mark[i],
                    s=50)
     return fig
예제 #5
0
    def Plot(self, frame=np.arange(5), axtype='contourf'):
        self.LayerBuild()

        q = np.array([self.predict(x) \
                      for x in self.xyt])

        frame_mask = np.array([self.xyt[:, 2] == f \
                               for f in self.frame])
        x = self.xyt[frame_mask[0], 0]
        y = self.xyt[frame_mask[0], 1]
        Z = sigmoid(self.a * q + self.b)

        xgrid = x.reshape(self.grid[0], self.grid[1])
        ygrid = y.reshape(self.grid[0], self.grid[1])

        sns.set_palette('YlGnBu_r')

        for f in frame:
            fig = plt.figure()
            ax = Axes3D(fig)
            z = Z[frame_mask[f]]
            zgrid = z.reshape(self.grid[0], self.grid[1])
            if (axtype == 'wireframe'): ax.plot_wireframe(x, y, z)
            elif (axtype == 'contour'): ax.contour3D(xgrid, ygrid, zgrid)
            elif (axtype == 'contourf'): ax.contourf3D(xgrid, ygrid, zgrid)
            plt.show()
예제 #6
0
파일: Plot.py 프로젝트: Haiezan/SomeProgram
def plotcurve():
    fig = plt.figure()
    axes3d = Axes3D(fig)
    axes3d.set_xlabel('Mx')
    axes3d.set_ylabel('My')
    axes3d.set_zlabel('N')

    filename = 'D:\Github\TractDll\PMM.dat'
    alldata = read_txt_high(filename)

    Num = int(len(alldata) / 3)

    for i in range(0, Num, 1):
        x = alldata[i * 3]
        y = alldata[i * 3 + 1]
        z = alldata[i * 3 + 2]

        axes3d.plot(x, y, z, '--', color='dimgray')
        axes3d.scatter(x, y, z, '--', color='black')

    #filename='D:\Github\JSTract\JSTract\COL.dat'
    #z000,x000,y000=read_txt_high(filename)
    #axes3d.plot(x000,y000,z000,color='red')
    #axes3d.scatter(x000,y000,z000,color='red')
    #plt.xlim(-1e9,1e9)
    #plt.ylim(-1e9,1e9)
    plt.show()
 def plot_figs(fig_num, elev, azim):
     fig = plt.figure(fig_num, figsize=(4, 3))
     plt.clf()
     ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elev, azim=azim)
 
     ax.scatter(a[::10], b[::10], c[::10], c=density[::10], marker='+', alpha=.4)
     Y = np.c_[a, b, c]
 
     # Using SciPy's SVD, this would be:
     # _, pca_score, V = scipy.linalg.svd(Y, full_matrices=False)
 
     pca = decomposition.PCA(n_components=3)
     pca.fit(Y)
     pca_score = pca.explained_variance_ratio_
     V = pca.components_
 
     x_pca_axis, y_pca_axis, z_pca_axis = V.T * pca_score / pca_score.min()
 
     x_pca_axis, y_pca_axis, z_pca_axis = 3 * V.T
     x_pca_plane = np.r_[x_pca_axis[:2], - x_pca_axis[1::-1]]
     y_pca_plane = np.r_[y_pca_axis[:2], - y_pca_axis[1::-1]]
     z_pca_plane = np.r_[z_pca_axis[:2], - z_pca_axis[1::-1]]
     x_pca_plane.shape = (2, 2)
     y_pca_plane.shape = (2, 2)
     z_pca_plane.shape = (2, 2)
     ax.plot_surface(x_pca_plane, y_pca_plane, z_pca_plane)
     ax.w_xaxis.set_ticklabels([])
     ax.w_yaxis.set_ticklabels([])
     ax.w_zaxis.set_ticklabels([])
     plt.savefig("pca_sample_%d.jpg" % fig_num)
예제 #8
0
파일: helper.py 프로젝트: meiTob/ML
def plot_rosenbrock(x_start: np.ndarray, gradient_steps: list = None) -> None:
    """Plot the gradient steps."""
    fig = plt.figure(figsize=(12, 8))
    ax = Axes3D(fig)

    s = 0.3
    X = np.arange(-2, 2.0 + s, s)
    Y = np.arange(-2, 3.0 + s, s)

    # Create the mesh grid(s) for all X/Y combos.
    X, Y = np.meshgrid(X, Y)
    # Rosenbrock function w/ two parameters using numpy Arrays
    Z = f(X, Y)

    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, linewidth=0, alpha=0.8, cmap=cm.coolwarm)
    # Global minimum
    ax.scatter(1, 1, f(1, 1), color="red", marker="*", s=200)
    # Starting point
    x0, x1 = x_start
    ax.scatter(x0, x1, f(x0, x1), color="green", marker="o", s=200)

    # Eps off set of the z axis, to plot the points above the surface for better visualization
    eps = 50
    if gradient_steps:
        for (x0, x1) in gradient_steps:
            ax.scatter(x0, x1, f(x0, x1) + eps, color="green", marker="o", s=50)

    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.set_zlabel("z")
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter("%.02f"))
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show()
예제 #9
0
def main():
    N = 100000

    x = np.random.uniform(-1.0, 1.0, N)
    y = np.random.uniform(-1.0, 1.0, N)
    z = np.random.uniform(-1.0, 1.0, N)

    l = []

    for i in xrange(N):
        if (x[i]**2 + y[i]**2 + z[i]**2) < 1.0:
            l.append(True)
        else:
            l.append(False)

    ax = Axes3D(plt.figure())
    ax.scatter3D(x, y, z, s=3, c=l, edgecolor='None')
    plt.xlim(-1.0, 1.0)
    plt.ylim(-1.0, 1.0)
    plt.show()

    print('Theoretical Value:',
          math.pi**(3.0 / 2.0) / math.gamma(3.0 / 2.0 + 1.0))
    # => Theoretical Value: 4.18879020479
    print('Monte Carlo:', 2.0**3 * float(l.count(True)) / float(N))
예제 #10
0
def surface(row):
    s1 = row['question1']
    s2 = row['question2']
    t1 = list((basic_cleaning(s1)).split())
    t2 = list((basic_cleaning(s2)).split())
    print("Q1: " + s1)
    print("Q2: " + s2)
    print("Duplicate: " + str(row['is_duplicate']))

    #     img = [[w2v_sim(x, y) for x in t1] for y in t2]

    fig = plt.figure()
    ax = Axes3D(fig)
    X = linspace(0, 10, 10)
    Y = linspace(0, 10, 10)
    X, Y = meshgrid(X, Y)
    Z = [[w2v_sim(x, y) for x in t1] for y in t2]
    a = np.array(Z, order='C')
    Z = np.resize(a, (10, 10))

    ax.plot_surface(Y, X, Z, rstride=1, cstride=1, cmap=cm.jet)
    ax.set_xlabel("X Axis")
    ax.set_ylabel("Y Axis")
    ax.set_zlabel("Z Axis")
    plt.show()
예제 #11
0
 def plotGrid(self, learner, suffix):
     from mpl_toolkits.mplot3d.axes3d import Axes3D
     import matplotlib.pyplot as plt
     #        plt.ioff()
     xs = np.linspace(0, 1, 30)
     ys = np.linspace(0, 1, 30)
     X, Y = np.meshgrid(xs, ys)
     Z = zeros(np.shape(X))
     input = DataMatrix(np.shape(Z)[0] * np.shape(Z)[1], 2)
     r = 0
     for i in range(np.shape(Z)[0]):
         for j in range(np.shape(Z)[1]):
             input.set(r, 0, X[i, j])
             input.set(r, 1, Y[i, j])
             r += 1
     result = learner.applyData(input)
     r = 0
     for i in range(np.shape(Z)[0]):
         for j in range(np.shape(Z)[1]):
             Z[i, j] = result[r]
             r += 1
     fig = plt.figure()
     ax = Axes3D(fig)
     ax.plot_wireframe(X, Y, Z)
     #plt.draw()
     plt.savefig("grid3d_%s_%i.png" % (suffix, learner.iteration))
     fig.clf()
     plt.close(plt.gcf())
예제 #12
0
파일: Surface.py 프로젝트: asanf/PyPCS
    def plot(self, plotcp=False, eps=1, dpi=100):
        '''
            Metodo che effettua il plot della superfice
            INPUT:
            @param dpi dot per inch desiderati per l'immagine del plot
            @param eps spaziatura fra una linea e la successiva della superfice
        
        
        se plotcp == True mostra nel plot anche il poligono di controllo
        che ha generato la superfice
        eps indica quanto preciso si vuole la superfice, più eps si avvicina ad 1
        più strette saranno le mesh
        dpi indica la grandezza che si desidera per il plot, in punti per pollice
        '''

        X = self.points[:, 0].reshape(self.npts, self.mpts)
        Y = self.points[:, 1].reshape(self.npts, self.mpts)
        Z = self.points[:, 2].reshape(self.npts, self.mpts)

        fig = pl.figure(1, dpi=dpi)
        ax = Axes3D(fig)

        ax.plot_surface(X, Y, Z, cstride=eps, rstride=eps)
        if (plotcp):
            ax.plot_wireframe(self.cntrl[:, :, 0],
                              self.cntrl[:, :, 1],
                              self.cntrl[:, :, 2],
                              color="#cc0000")
        ax.set_xlabel("X")
        ax.set_ylabel("Y")
        ax.set_zlabel("Z")
        pl.axis('equal')
        pl.show()
        return
예제 #13
0
def visualize_3d(model, classes, num_of_point):
    from mpl_toolkits.mplot3d.axes3d import Axes3D

    reduce_dim = function([model.layers[0].input],
                          [model.layers[-3].output
                           ])  # refer to the first layer and the last 3 layers
    gen_val = make_data_generator(classes, 'val', num_of_point)
    x, y = gen_val.next()
    x_3d = reduce_dim([x])[0]  # (number fo points, 3)
    print(x_3d.shape)
    x1_east, x2_east, x3_east = [], [], []
    x1_west, x2_west, x3_west = [], [], []
    for score, (x1, x2, x3) in zip(y, x_3d):
        if score < 0.5:
            x1_east.append(x1)
            x2_east.append(x2)
            x3_east.append(x3)
        else:
            x1_west.append(x1)
            x2_west.append(x2)
            x3_west.append(x3)
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.scatter(x1_east, x2_east, x3_east, c='r', marker='^')  # '^'
    ax.scatter(x1_west, x2_west, x3_west, c='b', marker='o')
    ax.set_xlabel('x1')
    ax.set_ylabel('x2')
    ax.set_zlabel('x3')
    ax.set_aspect(1)
    plt.show()
예제 #14
0
파일: plotting.py 프로젝트: brille/brille
def _check_axes(axs=None):
    if axs is None:
        if pp.get_fignums() and isinstance(pp.gca(), Axes3D):
            axs = pp.gca()
        else:
            axs = Axes3D(pp.figure())
    return axs
예제 #15
0
파일: 3D_OAT.py 프로젝트: ajmal017/tradesim
def _main():
    fig = plt.figure()
    ax = Axes3D(fig)

    mmax = 4.0959375
    NN = 25

    T = np.linspace(-512, 512, NN)
    M = np.linspace(0, mmax, NN)
    TT, MM = np.meshgrid(T, M)
    OO = oat(TT, MM)

    ax.plot_wireframe(TT, MM, OO)

    N = 50

    t = np.concatenate(
        (np.linspace(-512, 288.25,
                     N), np.linspace(288.25, 511.75,
                                     N), np.linspace(511.75, 511.75, N)))
    m = np.concatenate(
        (np.linspace(0, mmax, N), np.linspace(mmax, 2.36525,
                                              N), np.linspace(2.36525, 0, N)))
    o = oat(t, m)

    ax.scatter(t, m, o, c='r')

    ax.set_xlabel('TAT')
    ax.set_ylabel('Mach')
    ax.set_zlabel('OAT')

    plt.show()
예제 #16
0
def plot_simulation(kernel_fp, sigma, u0, dim, timesteps, axis):
    """
    Run and plot the simulation results
    :param str kernel_fp: The filepath to the kernel being used.
    :param np.array(dim^2,) sigma: The value of the weight matrix.
    :param np.array(dim^2,) u0: The initial conditions.
    :param int dim: The dimensions of the grid.
    :param int timesteps: The number of timesteps to simulate.
    :param str axis: '2d' or '3d' plot
    :return None:
    """

    res = run_simulation(kernel_fp, sigma, u0, dim, timesteps)
    res = res.reshape((dim, dim))

    if axis == '2d':
        plt.imshow(res, origin='lower', interpolation='none')

    elif axis == '3d':
        fig = plt.figure()
        ax = Axes3D(fig)
        x = np.arange(0, 1, 1 / dim)
        y = np.arange(0, 1, 1 / dim)
        xs, ys = np.meshgrid(x, y)
        ax.plot_surface(xs, ys, res, rstride=1, cstride=1, cmap='rainbow')

    plt.show()
예제 #17
0
def plot(data, fig, fformat, dim, fnum, xlim, ylim):
	if plot.count == 1:
#		input('>>')
		pass
	
	if plot.count > fnum:
		print('plot end.')
		input('')
		return
	
	plt.cla()
	plt.title('num = ' + str(plot.count))
	plt.xlim(-1*xlim, xlim)
	plt.ylim(-1*ylim, ylim)
	
	# file load
	fname = fformat % plot.count
	file = open(fname, 'r')
	time = float(file.readline())
	nP   = int(file.readline())
	
	points = []
	X = []
	Y = []
	Z = []
	j = 0
	for line in file:
#		points.append(Point())
		X.append(float)
		Y.append(float)
		Z.append(float)
		itemlist = line[:-1].split(' ')
#		print(itemlist)
		x = float(itemlist[0])
		y = float(itemlist[1])
		z = float(itemlist[2])
		
#		points[j].x = x
#		points[j].y = y
#		points[j].z = z
		
		X[j] = x
		Y[j] = y
		Z[j] = z
		j += 1
	
	for i in range(0,nP):
		if dim == 2:
#			plt.plot(points[i].x, points[i].y, 'o')
			plt.plot(X, Y, 'o')
		if dim == 3:
#			plt.plot(points[i].x, points[i].y, points[i].z, 'o')
			ax = Axes3D(fig)
			ax.set_xlim(-1000, 1000)
			ax.set_ylim(-1000, 1000)
			ax.set_zlim(-1000, 1000)
			ax.scatter3D(X, Y, Z)
	
	plot.count += 1
예제 #18
0
파일: 10.py 프로젝트: hxzuicool/DailyTest
def imgTo3D(img, cmap='gist_rainbow'):  # 也可为'hot'
    fig = plt.figure(figsize=(15, 10))
    axes3d = Axes3D(fig)
    Y = np.arange(0, np.shape(img)[0], 1)
    X = np.arange(0, np.shape(img)[1], 1)
    X, Y = np.meshgrid(X, Y)
    axes3d.plot_surface(X, Y, cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), cmap=cmap)
    plt.show()
예제 #19
0
 def data_plot_GPS_3D(self, dataList, size=1000):
     """
     画图
     :param dataList:
     :param sie:
     :return:
     """
     line_keyId, list_mileage, list_altitude, list_latitude, list_longitude = dataList
     length = len(list_mileage)
     head = 0
     for i in range(1000):
         tail = head + size
         print(i, head, tail, length)
         if tail <= length:
             # 此处fig是二维
             fig = plt.figure()
             # 将二维转化为三维
             axes3d = Axes3D(fig)
             axes3d.scatter3D(list_latitude[head:tail],
                              list_longitude[head:tail],
                              list_altitude[head:tail],
                              s=0.5)
             plt.title('GPS三维图')
             axes3d.set_title("GPS三维图")
             axes3d.set_xlabel("纬度")
             axes3d.set_ylabel("经度")
             axes3d.set_zlabel("高度")
             axes3d.invert_xaxis()  # x轴反向
             plt.show()
         else:
             # 此处fig是二维
             fig = plt.figure()
             # 将二维转化为三维
             axes3d = Axes3D(fig)
             axes3d.scatter3D(list_latitude[head:],
                              list_longitude[head:],
                              list_altitude[head:],
                              s=0.5)
             axes3d.set_title("GPS三维图")
             axes3d.set_xlabel("纬度")
             axes3d.set_ylabel("经度")
             axes3d.set_zlabel("高度")
             axes3d.invert_xaxis()  # x轴反向
             plt.show()
             break
         head += size
예제 #20
0
def plot_points(x, title=''):
    """Plot points with a title."""
    if hasmpl:
        fig = pp.figure()
        ax = Axes3D(fig)
        ax.scatter(x[:, 0], x[:, 1], x[:, 2], s=10)
        ax.set_title(title)
        pp.show()
예제 #21
0
def plot_points(x, title=''):
    """Plot the 3D points with a given title."""
    if HASMPL:
        fig = pp.figure()
        ax = Axes3D(fig)
        ax.scatter(x[:, 0], x[:, 1], x[:, 2], s=10)
        ax.set_title(title)
        pp.show()
예제 #22
0
def plot3D():
    X = pd.read_table('x.dat',header = None, sep='\s+'); Y = pd.read_table('y.dat',header = None, sep='\s+')
    fig = plt.figure(figsize=plt.figaspect(0.5))
    X,Y,Z = X[0],X[1],Y
    # print(X,Y,Z)
    ax = Axes3D(fig) # 画出一个三维图像
    ax.scatter(X, Y, Z)
    plt.show()
예제 #23
0
def array6x4(zz):
    x = np.arange(0, 6, 1)
    y = np.arange(0, 4, 1)
    xs, ys = np.meshgrid(x, y)
    zs = xs**2 + ys**2
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.plot_surface(xs, ys, zz, rstride=1, cstride=1, cmap=cm.viridis)
    plt.show()
예제 #24
0
 def plot_value_function(self):
     Vm = np.amax(self._value_action_state, axis=0)
     x = np.arange(1, 11)
     y = np.arange(1, 22)
     xs, ys = np.meshgrid(x, y)
     fig = plt.figure()
     ax = Axes3D(fig)
     ax.plot_wireframe(xs, ys, Vm.T, rstride=1, cstride=1)
     plt.show()
예제 #25
0
def plot_points_with_lines(x, y, title=''):
    """Plot 3D points and lines with a given title."""
    if HASMPL:
        fig = pp.figure()
        ax = Axes3D(fig)
        ax.plot(y[:, 0], y[:, 1], y[:, 2])
        ax.scatter(x[:, 0], x[:, 1], x[:, 2], s=10)
        ax.set_title(title)
        pp.show()
예제 #26
0
파일: triangulated.py 프로젝트: afcarl/viz
def triangulated_surface(x, y, z):
    """
    3d surface plot of irregularly space samples. Surface is found by tessulating XY plane.
    """

    # Create a triangulation of our region.
    _, _, tri_points, _ = delaunay(x, y)

    data = np.array([x, y, z]).T

    # Construct the triangles for the surface.
    verts = np.array([[data[i], data[j], data[k]] for (i, j, k) in tri_points])

    # To get a coloured plot, we need to assign a value to each face that
    # dictates the colour.  In this case we'll just use the average z
    # co-ordinate of the three triangle vertices.  One of these values is
    # required for each face (triangle).
    z_color = np.array([(np.sum(v_p[:, 2]) / 3.0) for v_p in verts])

    # Choiced for colour maps are :
    #   autumn bone cool copper flag gray hot hsv jet pink prism spring summer
    #   winter spectral
    cm = pl.cm.get_cmap("jet")

    # Our triangles are now turned into a collection of polygons using the
    # vertex array.  We assign the colour map here, which will figure out its
    # required ranges all by itself.
    triCol = Poly3DCollection(verts, cmap=cm)

    triCol.set_edgecolor('k')
    triCol.set_linewidth(0.1)

    # Set the value array associated with the polygons.
    triCol.set_array(z_color)

    # Create the plotting figure and the 3D axes.
    fig = pl.figure()
    ax = Axes3D(fig)

    # Add our two collections of 3D polygons directly.  The collections have all of
    # the point and color information.  We don't need the add_collection3d method,
    # since that method actually converts 2D polygons to 3D polygons.  We already
    # have 3D polygons.
    ax.add_collection(triCol)

    # Add a label, for interest
    #ax.text3D(0.0, 0.0, 2.1, "Peak/Trough")

    # If we don't bound the axes correctly the display will be off.
    ax.set_xlim3d(x.min(), x.max())
    ax.set_ylim3d(y.min(), y.max())
    ax.set_zlim3d(z.min(), z.max())

    # We could also print to a file here.
    pl.show()

    return ax
예제 #27
0
def surf(matIn, div=(1, 1), SIZE=(8, 6)):
    x = np.arange(0, matIn.shape[0])
    y = np.arange(0, matIn.shape[1])
    x, y = np.meshgrid(y, x)
    fig = plt.figure(figsize=SIZE)
    ax = Axes3D(fig)
    ax.plot_surface(x, y, matIn, rstride=div[0], cstride=div[1], cmap='hot')
    plt.title('fig')
    plt.show()
예제 #28
0
def plot_points_with_lines(x, y, title=''):
    """Plot points with connecting lines and a title."""
    if hasmpl:
        fig = pp.figure()
        ax = Axes3D(fig)
        ax.plot(y[:, 0], y[:, 1], y[:, 2])
        ax.scatter(x[:, 0], x[:, 1], x[:, 2], s=10)
        ax.set_title(title)
        pp.show()
def draw_pic(X, Y, Z, z_max, title, z_min=0):
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)
    # ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot)
    ax.set_zlim(z_min, z_max)
    ax.set_title(title)
    # plt.savefig("./myProject/Algorithm/pic/%s.png" % title) # 保存图片
    plt.show()
예제 #30
0
    def __create_axes(self):
        axes = Axes3D(plt.figure())

        if(global_v.UNIFORM_SCALE):
            axes.set_xlim3d(global_v.CHAR_INTERVAL[0], global_v.CHAR_INTERVAL[1])
            axes.set_ylim3d(global_v.CHAR_INTERVAL[0], global_v.CHAR_INTERVAL[1])
            axes.set_zlim3d(global_v.CHAR_INTERVAL[0], global_v.CHAR_INTERVAL[1])
        print("3D plot scale uniformed:", global_v.UNIFORM_SCALE)
        
        return axes