def _button_press(self, evt): self._mouse_hit, extra = self.contains(evt) if not self._mouse_hit: return fig_axes = self.figobj # for obj in fig_axes.walk_tree(): # obj.switch_scale('coarse') Axes3D._button_press(self, evt)
def _button_press(self, evt): self._mouse_hit, extra = self.contains(evt) if not self._mouse_hit:return fig_axes = self.figobj # for obj in fig_axes.walk_tree(): # obj.switch_scale('coarse') Axes3D._button_press(self, evt)
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")
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))
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()
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
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()
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
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()
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()
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()
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)
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
def plot_surface(self, *args, **kwargs): ''' If the **mantid3d** projection is chosen, it can be used the same as :py:meth:`matplotlib.axes.Axes3D.plot_surface` for arrays, or it can be used to plot :class:`mantid.api.MatrixWorkspace` or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: import matplotlib.pyplot as plt from mantid import plots ... fig, ax = plt.subplots(subplot_kw={'projection':'mantid3d'}) ax.plot_surface(workspace) #for workspaces ax.plot_surface(x,y,z) #for arrays fig.show() For keywords related to workspaces, see :func:`mantid.plots.plotfunctions3D.plot_surface` ''' if mantid.plots.helperfunctions.validate_args(*args): mantid.kernel.logger.debug('using mantid.plots.plotfunctions3D') return mantid.plots.plotfunctions3D.plot_surface( self, *args, **kwargs) else: return Axes3D.plot_surface(self, *args, **kwargs)
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()
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
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())
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()
def __init__(self): # create a new window window = gtk.Window() window.set_default_size(400, 300) window.set_title("DICOM contour display") # create a figure and plot self.figure = Figure(figsize=(5, 4), dpi=72) self.subplot = self.figure.add_subplot(111, projection='3d') # Create the widget, a FigureCanvas containing our Figure canvas = FigureCanvas(self.figure) Axes3D.mouse_init(self.subplot) vbox = gtk.VBox(homogeneous=False, spacing=0) vbox.pack_start(canvas, expand=True, fill=True, padding=0) self.contourselect = gtk.SpinButton(gtk.Adjustment(value=0, lower=0, upper=13, step_incr=1, page_incr=1), digits=0) hbox = gtk.HBox(homogeneous=True, spacing=0) hbox.pack_start(gtk.Label("Contour to display:")) hbox.pack_start(self.contourselect) self.contourselect.connect("value-changed", lambda x: self.update_contour()) vbox.pack_start(hbox, expand=False, fill=True, padding=0) window.add(vbox) self.subplot.plot([0], [0], '-') self.subplot.grid(True) self.subplot.set_xlabel('x') self.subplot.set_ylabel('y') self.figure.canvas.draw() # show everything window.show_all() window.connect("destroy", lambda x: gtk.main_quit())
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
def fill_betweenx(self, *args, **kwargs): from art3d_gl import polygon_2d_to_gl zs = kwargs.pop('zs', 0) zdir = kwargs.pop('zdir', 'z') a = Axes3D.fill_betweenx(self, *args, **kwargs) convert_to_gl(a, zs, zdir) a.convert_2dpath_to_3dpath(zs, zdir = zdir) return a
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()
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
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()
def fill_betweenx(self, *args, **kwargs): from art3d_gl import polygon_2d_to_gl zs = kwargs.pop('zs', 0) zdir = kwargs.pop('zdir', 'z') a = Axes3D.fill_betweenx(self, *args, **kwargs) convert_to_gl(a, zs, zdir) a.convert_2dpath_to_3dpath(zs, zdir=zdir) return a
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()
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()
def fill(self, *args, **kwargs): from art3d_gl import polygon_2d_to_gl zs = kwargs.pop('zs', 0) zdir = kwargs.pop('zdir', 'z') a = Axes3D.fill(self, *args, **kwargs) for obj in a: convert_to_gl(obj, zs, zdir) return a
def imshow(self, *args, **kwargs): im_center= kwargs.pop('im_center', (0,0)) im_axes = kwargs.pop('im_axes', [(1, 0, 0), (0, 1, 0)]) from art3d_gl import image_to_gl im = Axes3D.imshow(self, *args, **kwargs) image_to_gl(im) im.set_3dpath(im_center, im_axes) return im
def imshow(self, *args, **kwargs): im_center = kwargs.pop('im_center', (0, 0)) im_axes = kwargs.pop('im_axes', [(1, 0, 0), (0, 1, 0)]) from art3d_gl import image_to_gl im = Axes3D.imshow(self, *args, **kwargs) image_to_gl(im) im.set_3dpath(im_center, im_axes) return im
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()
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 __init__(self): # create a new window window = gtk.Window() window.set_default_size(400,300) window.set_title("DICOM contour display") # create a figure and plot self.figure = Figure(figsize=(5,4), dpi=72) self.subplot = self.figure.add_subplot(111, projection='3d') # Create the widget, a FigureCanvas containing our Figure canvas = FigureCanvas(self.figure) Axes3D.mouse_init(self.subplot) vbox = gtk.VBox(homogeneous=False, spacing=0) vbox.pack_start(canvas, expand=True, fill=True, padding=0) self.contourselect = gtk.SpinButton(gtk.Adjustment(value=0, lower=0, upper=13, step_incr=1, page_incr=1), digits=0) hbox = gtk.HBox(homogeneous=True, spacing=0) hbox.pack_start(gtk.Label("Contour to display:")) hbox.pack_start(self.contourselect) self.contourselect.connect("value-changed", lambda x: self.update_contour()) vbox.pack_start(hbox, expand=False, fill=True, padding=0) window.add(vbox) self.subplot.plot([0], [0], '-') self.subplot.grid(True) self.subplot.set_xlabel('x') self.subplot.set_ylabel('y') self.figure.canvas.draw() # show everything window.show_all() window.connect("destroy", lambda x: gtk.main_quit())
def plot(self, *args, **kwargs): from art3d_gl import line_3d_to_gl fc = kwargs.pop('facecolor', None) gl_offset = kwargs.pop('gl_offset', (0,0,0)) array_idx = kwargs.pop('array_idx', None) lines = Axes3D.plot(self, *args, **kwargs) for l in lines: line_3d_to_gl(l) l._facecolor = fc l._gl_offset = gl_offset l._gl_array_idx = array_idx return lines
def contour(self, *args, **kwargs): from art3d_gl import poly_collection_3d_to_gl offset = kwargs['offset'] if 'offset' in kwargs else None zdir = kwargs['zdir'] if 'zdir' in kwargs else 'z' cset = Axes3D.contour(self, *args, **kwargs) for z, linec in zip(np.argsort(cset.levels), cset.collections) : convert_to_gl(linec) linec.convert_2dpath_to_3dpath(z, zdir = 'z') linec.do_stencil_test = True if offset is not None: if zdir == 'x': linec._gl_offset = (z*0.001, 0, 0) elif zdir == 'y': linec._gl_offset = (0, z*0.001, 0) else: linec._gl_offset = (0, 0, z*0.001) return cset
def contourf(self, *args, **kwargs): ''' If the **mantid3d** projection is chosen, it can be used the same as :py:meth:`matplotlib.axes.Axes3D.contourf` for arrays, or it can be used to plot :class:`mantid.api.MatrixWorkspace` or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: import matplotlib.pyplot as plt from mantid import plots ... fig, ax = plt.subplots(subplot_kw={'projection':'mantid3d'}) ax.contourf(workspace) #for workspaces ax.contourf(x,y,z) #for arrays fig.show() For keywords related to workspaces, see :func:`mantid.plots.plotfunctions3D.contourf` ''' if mantid.plots.helperfunctions.validate_args(*args): mantid.kernel.logger.debug('using mantid.plots.plotfunctions3D') return mantid.plots.plotfunctions3D.contourf(self, *args, **kwargs) else: return Axes3D.contourf(self, *args, **kwargs)
def plot_solid(self, *args, **kwargs): ''' plot_solid(v) or plot_solid(v, idx) v [element_index, points_in_element, xyz] or v [vertex_index, xyz] idx = [element_idx, point_in_element] kwargs: normals : normal vectors ''' shade = kwargs.pop('shade', 'linear') if shade == 'flat': args, kwargs = self.prep_flat_shading_data(args, kwargs) if len(args) == 1: v = args[0] vv = v.reshape(-1, v.shape[-1])# vertex nv = len(v[:, :, 2].flatten()) idxset = np.arange(nv, dtype=int).reshape(v.shape[0], v.shape[1]) nverts = v.shape[0]*v.shape[1] ncounts = v.shape[1] nele = v.shape[0] else: v = args[0] # vertex vv = v idxset = np.array(args[1], dtype=int, copy=False) # element index (element_idx, point_in_element) nverts = v.shape[0] ncounts = idxset.shape[1] nele = idxset.shape[0] norms = kwargs.pop('normals', None) w = np.zeros((nverts)) # weight if norms is None: norms = np.zeros((nverts, 3), dtype=np.float32) # weight if idxset.shape[1] > 2: xyz = vv[idxset[:, :3]].astype(float, copy=False) p0 = xyz[:, 0, :] - xyz[:, 1, :] p1 = xyz[:, 0, :] - xyz[:, 2, :] n1a = np.cross(p0, p1) da = np.sqrt(np.sum(n1a**2, 1)) da[da == 0.0] = 1. n1a[:,0] /= -da n1a[:,1] /= -da n1a[:,2] /= -da else: da = np.zeros(idxset.shape[0]) n1a = np.zeros((nverts, 3), dtype=np.float32) # weight n1a[:,2] = 1.0 if len(args) == 1: if da[0] == 0.: norms[:,2] = 1 # all [0. 0. 1] else: for k in range(idxset.shape[1]): norms[idxset[:,k], :] = n1a elif idxset.shape[-1] < 3: norms = n1a else: data = np.ones(idxset.flatten().shape[0]) jj = np.tile(np.arange(idxset.shape[0]), idxset.shape[-1]) ii = idxset.transpose().flatten() table = coo_matrix((data, (ii, jj)), shape = (nverts, idxset.shape[0])) csr = table.tocsr() indptr = csr.indptr; indices = csr.indices data = csr.data for i in range(csr.shape[0]): nn = n1a[indices[indptr[i]:indptr[i+1]]] if len(nn) != 0.0: sign = np.sign(np.sum(nn*nn[0], 1)) data[indices[indptr[i]:indptr[i+1]]] = sign else: pass #norms[i, :] = [1,0,0] norms = table.dot(n1a) ''' for i in range(csr.shape[0]): nn = n1a[indices[indptr[i]:indptr[i+1]]] if len(nn) != 0.0: sign = np.sign(np.sum(nn*nn[0], 1)) nn *= np.tile(sign.reshape(sign.shape[0], 1), nn.shape[-1]) norms[i, :] = np.mean(nn, 0) else: norms[i, :] = [1,0,0] ''' ''' table = table.tocsr() nz = n1a[:,2] nz[nz==0] = 1.0 f = nz/np.abs(nz) n1a = (n1a.transpose()*f).transpose() norms = table.dot(n1a) ''' nn = np.sqrt(np.sum(norms**2, 1)) nn[nn == 0.0] = 1. norms = norms/nn.reshape(-1,1) kwargs['gl_3dpath'] = [v[..., 0].flatten(), v[..., 1].flatten(), v[..., 2].flatten(), norms, idxset] from art3d_gl import Poly3DCollectionGL if len(args) == 1: a = Poly3DCollectionGL(v[:2,...], **kwargs) else: a = Poly3DCollectionGL(v[idxset[:2,...]], **kwargs) #For GL aritsts, it is not necesasry to put in collections?? #Axes3D.add_collection3d(self, a) Axes3D.add_artist(self, a) a.do_stencil_test = False return a
def draw(self, renderer): # if self._use_gl and isSupportedRenderer(renderer): gl_len = 0 if isSupportedRenderer(renderer): self._matrix_cache = self.get_proj2() artists = [] artists.extend(self.images) artists.extend(self.collections) artists.extend(self.patches) artists.extend(self.lines) artists.extend(self.texts) artists.extend(self.artists) gl_obj = [a for a in artists if hasattr(a, 'is_gl')] gl_len = len(gl_obj) if gl_obj > 0: glcanvas = get_glcanvas() if (glcanvas is not None and glcanvas.init): glcanvas.set_lighting(**self._lighting) glcanvas._gl_scale = self._gl_scale else: return renderer._num_globj = gl_len renderer._k_globj = 0 ### axes3D seems to change frameon status.... frameon = self.get_frame_on() self.set_frame_on(False) if self._show_3d_axes: self.draw_3d_axes() for a in self._3d_axes_icon: a().set_zorder(gl_len+1) else: if self._3d_axes_icon is not None: self.lines.remove(self._3d_axes_icon[0]()) self.lines.remove(self._3d_axes_icon[1]()) self.lines.remove(self._3d_axes_icon[2]()) self.texts.remove(self._3d_axes_icon[3]()) self.texts.remove(self._3d_axes_icon[4]()) self.texts.remove(self._3d_axes_icon[5]()) self._3d_axes_icon = None if self._gl_scale != 1.0: print("gl_scale", self._gl_scale) xmin, xmax = self.get_xlim3d() ymin, ymax = self.get_ylim3d() zmin, zmax = self.get_zlim3d() dx = (xmax - xmin)/self._gl_scale/2. dy = (ymax - ymin)/self._gl_scale/2. dz = (zmax - zmin)/self._gl_scale/2. xmid = (xmax + xmin)/2. ymid = (ymax + ymin)/2. zmid = (zmax + zmin)/2. self.set_xlim3d([xmid-dx, xmid+dx]) self.set_ylim3d([ymid-dy, ymid+dy]) self.set_zlim3d([zmid-dz, zmid+dz]) val = Axes3D.draw(self, renderer) if self._gl_scale != 1.0: self.set_xlim3d([xmin, xmax]) self.set_ylim3d([ymin, ymax]) self.set_zlim3d([zmin, zmax]) self.set_frame_on(frameon) return val
def short_proj(): return np.dot(Axes3D.get_proj(ax), scale)
def _button_release(self, evt): if not self._mouse_hit:return fig_axes = self.figobj fig_axes.set_bmp_update(False) Axes3D._button_release(self, evt)