def visualize_with_jupyter_notebook(obj, mode="element", transformation=None): """View a grid or grid function in an IPython Notebook""" import plotly import plotly.figure_factory as ff import plotly.graph_objs as go from bempp.api import GridFunction from bempp.api.grid.grid import Grid import numpy as np if transformation is None: transformation = np.real plotly.offline.init_notebook_mode() if isinstance(obj, Grid): vertices = obj.vertices elements = obj.elements fig = ff.create_trisurf( x=vertices[0, :], y=vertices[1, :], z=vertices[2, :], simplices=elements.T, color_func=elements.shape[1] * ["rgb(255, 222, 173)"], ) fig['layout']['scene'].update(go.layout.Scene(aspectmode='data')) plotly.offline.iplot(fig) elif isinstance(obj, GridFunction): import matplotlib as mpl from matplotlib import pyplot as plt cmap = plt.get_cmap("jet") grid = obj.space.grid vertices = grid.vertices elements = grid.elements local_coordinates = _np.array([[1.0 / 3], [1.0 / 3]]) values = _np.zeros(grid.entity_count(0), dtype="float64") for element in grid.entity_iterator(0): index = element.index local_values = np.real( transformation(obj.evaluate(index, local_coordinates))) values[index] = local_values.flatten() norm = mpl.colors.Normalize(vmin=_np.min(values), vmax=_np.max(values)) colorfun = lambda x: _np.rint(_np.array(cmap(norm(x))) * 255) color_codes = [ "rgb({0}, {1}, {2})".format(*colorfun(x)) for x in values ] fig = ff.create_trisurf( x=vertices[0, :], y=vertices[1, :], z=vertices[2, :], simplices=elements.T, color_func=color_codes, ) fig['layout']['scene'].update(go.layout.Scene(aspectmode='data')) plotly.offline.iplot(fig)
def visualize_with_ipython_notebook(obj, mode='element', transformation=None): """View a grid or grid function in an IPython Notebook""" import plotly import plotly.figure_factory as ff from bempp.api import GridFunction from bempp.api.grid.grid import Grid import numpy as np if transformation is None: transformation = np.real plotly.offline.init_notebook_mode() if isinstance(obj, Grid): vertices = obj.leaf_view.vertices elements = obj.leaf_view.elements fig = ff.create_trisurf(x=vertices[0, :], y=vertices[1, :], z=vertices[2, :], simplices=elements.T, color_func=elements.shape[1] * ['rgb(255, 222, 173)']) plotly.offline.iplot(fig) elif isinstance(obj, GridFunction): import matplotlib as mpl from matplotlib import pyplot as plt cmap = plt.get_cmap('jet') grid = obj.space.grid vertices = grid.leaf_view.vertices elements = grid.leaf_view.elements index_set = grid.leaf_view.index_set() local_coordinates = _np.array([[1. / 3], [1. / 3]]) values = _np.zeros(grid.leaf_view.entity_count(0), dtype='float64') for element in grid.leaf_view.entity_iterator(0): index = index_set.entity_index(element) local_values = np.real( transformation(obj.evaluate(element, local_coordinates))) values[index] = local_values.flatten() norm = mpl.colors.Normalize(vmin=_np.min(values), vmax=_np.max(values)) colorfun = lambda x: _np.rint(_np.array(cmap(norm(x))) * 255) color_codes = [ 'rgb({0}, {1}, {2})'.format(*colorfun(x)) for x in values ] fig = ff.create_trisurf(x=vertices[0, :], y=vertices[1, :], z=vertices[2, :], simplices=elements.T, color_func=color_codes) plotly.offline.iplot(fig)
def plot_coeff(elements, coords, coeff): fig_lin_CO2 = FF.create_trisurf(x=coords[:, 0], y=coords[:, 1], z=coeff[coeff.shape[0] // 2:], simplices=elements.astype(int), title="Linearized CO2") fig_lin_O2 = FF.create_trisurf(x=coords[:, 0], y=coords[:, 1], z=coeff[:coeff.shape[0] // 2], simplices=elements.astype(int), title="Linearized O2") fig_lin_CO2.show() fig_lin_O2.show()
def iap3d(cfg,z_evaled): u = np.linspace(*cfg['tls']) v = np.linspace(*cfg['vls']) print("ushape pre meshgrid : {}".format(u.shape)) print("vshape pre meshgrid : {}".format(v.shape)) u,v = np.meshgrid(u,v) print("ushape post meshgrid : {}".format(u.shape)) print("vshape post meshgrid : {}".format(v.shape)) u = u.flatten() v = v.flatten() x=u y=v z = z_evaled # already evaluated... print("x : {}".format(x.shape)) print("y : {}".format(y.shape)) print("z : {}".format(z.shape)) points2D = np.vstack([u,v]).T print("points2D : {}".format(points2D.shape)) tri = Delaunay(points2D) # https://en.wikipedia.org/wiki/Delaunay_triangulation simplices = tri.simplices simplices.shape print("points2D : {}".format(points2D.shape)) # fig = ff.create_trisurf(x=x, y=y, z=z, simplices=simplices, title="Iap3D", aspectratio=dict(x=1, y=1, z=0.3),) return fig
def plotly_3d_to_html(verts, faces, filename="tmp.html", title="3d visualization", zyx_range=None): """ use plotly offline to plot 3d scan """ x, y, z = zip(*verts) # print("Drawing") # Make the colormap single color since the axes are positional not intensity. colormap = ['rgb(255,105,180)', 'rgb(255,255,51)', 'rgb(0,191,255)'] # colormap = ['rgb(236, 236, 212)', 'rgb(236, 236, 212)'] # fig = FF.create_trisurf(x=x, fig = create_trisurf( x=x, y=y, z=z, showbackground=False, plot_edges=False, colormap=colormap, simplices=faces, # backgroundcolor='rgb(240, 240, 240)', title=title, show_colorbar=False) if zyx_range is not None: hidden_axis(fig.layout.scene.zaxis, zyx_range[0]) hidden_axis(fig.layout.scene.yaxis, zyx_range[1]) hidden_axis(fig.layout.scene.xaxis, zyx_range[2]) # fig.layout.scene.zaxis.range = zyx_range[0] # fig.layout.scene.yaxis.range = zyx_range[1] # fig.layout.scene.xaxis.range = zyx_range[2] plot(fig, filename=filename) return fig
def __update__(self, P, T, color='rgb(255,0,0)'): """ Updates the figure content Parameters ---------- P : Tensor the (N,3,) points set tensor T : LongTensor the (3,M,) topology tensor color : str (optional) the mesh color Returns ------- None """ p = torch2numpy(P) t = torch2numpy(T.t()) fig = FF.create_trisurf(x=p[:, 0], y=p[:, 1], z=p[:, 2], simplices=t, show_colorbar=False, colormap=color) fig.data[0].flatshading = True fig.layout = {'title': {'text': self.__title}} self.__fig__ = fig
def sphere_data(xyz0, color, radius=2000, npts=10): """ Generate the Mesh3d data for a sphere of a specific color, radius, and center. """ phis = np.linspace(-np.pi / 2, np.pi / 2, npts) thetas = np.linspace(0, 2 * np.pi, npts) pp, tt = np.meshgrid(phis, thetas) pp = pp.flatten() tt = tt.flatten() xs = radius * np.cos(pp) * np.cos(tt) + xyz0[0] ys = radius * np.cos(pp) * np.sin(tt) + xyz0[1] zs = radius * np.sin(pp) + xyz0[2] points2D = np.vstack([pp, tt]).T tri = sp.spatial.Delaunay(points2D) simplices = tri.simplices fig_prop = ff.create_trisurf(x=xs, y=ys, z=zs, simplices=simplices, colormap=[cl.to_hex(color), cl.to_hex(color)]) return fig_prop['data'][0]
def draw_deluanay_surf(X, Y, Z, title): u = np.linspace(0, 2 * np.pi, 21) v = np.linspace(0, 2 * np.pi, CARD_VALUE_MAX) u, v = np.meshgrid(u, v) u = u.flatten() v = v.flatten() points2D = np.vstack([u, v]).T tri = Delaunay(points2D) simplices = tri.simplices fig = FF.create_trisurf(z=Z, x=X, y=Y, simplices=simplices) scene = dict( xaxis=dict(nticks=10, range=[CARD_VALUE_MIN, CARD_VALUE_MAX], tick0=1), yaxis=dict(nticks=21, range=[1, 21], ticks='outside', tick0=1), zaxis=dict( nticks=10, range=[np.min(Z) - 0.5, np.max(Z) + 0.5], ), xaxis_title='Dealer', yaxis_title='Player', zaxis_title='Value', ) fig.update_layout(scene=scene, title=title, autosize=True, width=700, height=500, margin=dict(l=65, r=50, b=65, t=90)) fig.show()
def index(request): u = np.linspace(0, 2 * np.pi, 24) v = np.linspace(-1, 1, 8) u, v = np.meshgrid(u, v) u = u.flatten() v = v.flatten() tp = 1 + 0.5 * v * np.cos(u / 2.) x = tp * np.cos(u) y = tp * np.sin(u) z = 0.5 * v * np.sin(u / 2.) points2D = np.vstack([u, v]).T tri = Delaunay(points2D) simplices = tri.simplices fig1 = FF.create_trisurf(x=x, y=y, z=z, colormap="Portland", simplices=simplices, title="Mobius Band") div = py.plot(fig1, auto_open=False, output_type='div') context = { 'page': 'astro', 'cpp_out': astrocpp.bindfunction(4), 'graph': div, } return render(request, 'astro/index.html', context)
def showMesh(verts, faces, aspect=dict(x=1, y=1, z=1), plot_it=True, title=''): fig = FF.create_trisurf(x=verts[:, 0], y=verts[:, 1], z=verts[:, 2], simplices=faces, title=title, aspectratio=aspect) fig.update_layout(scene=dict( xaxis=dict(nticks=1, range=[0, cf_vox_size + 1], backgroundcolor='white', gridcolor='white'), yaxis=dict(nticks=1, range=[0, cf_vox_size + 1], backgroundcolor='white', gridcolor='white'), zaxis=dict(nticks=1, range=[0, cf_vox_size + 1], backgroundcolor='white', gridcolor='white'), ), width=900, height=700, margin=dict(r=20, l=10, b=10, t=10)) return fig
def plot_trimesh(self, mesh, paint_clusters, plot_edges=False, opacity=0.8): """ Plots a triangulated mesh in color. Parameters ---------- mesh : `compas.datastructures.Mesh` A COMPAS mesh with 3D vertices. paint_clusters : `bool` Flag to add colors to mesh faces. Defaults to `True`. plot_edges : `bool`, optional Flag to plot edges of the mesh. Defaults to `False`. opacity : `float` A value between 0.0 and 1.0 to control opacity of the mesh. Defautls to 0.8. Notes ----- The colors of the mesh faces are based on their the cluster labels. """ # color up the faces of the COMPAS mesh according to their cluster # make a dictionary with all labels if paint_clusters: labels_to_color = {} for fkey in mesh.faces(): labels_to_color[fkey] = mesh.face_attribute(key=fkey, name="cluster") # convert labels to rgb colors face_colors = rgb_colors(labels_to_color, invert=False) face_colors = list(face_colors.values()) else: face_colors = [(255, 255, 255) for i in range(mesh.number_of_faces())] # "v" is shorthand for vertices v_x, v_y, v_z = mesh_to_vertices_xyz(mesh) _, mesh_faces = mesh.to_vertices_and_faces() # we must go for another type of plot if we want to have the option of # ploting mesh edges down the line figure_mesh = ff.create_trisurf(x=v_x, y=v_y, z=v_z, simplices=asarray(mesh_faces), color_func=face_colors) self.add_trace(figure_mesh.data[0]) # adds mesh faces if plot_edges: self.add_trace(figure_mesh.data[1]) # adds mesh lines self.update_traces(opacity=opacity)
def create_trisurf_with_parameters(self, u, v, x, y, z, name): points2D = np.vstack([u, v]).T tri = Delaunay(points2D) simplices = tri.simplices return FF.create_trisurf( x=x, y=y, z=z, colormap=['rgb(50, 0, 75)', 'rgb(200, 0, 200)', '#c8dcc8'], show_colorbar=True, simplices=simplices, title=name)
def draw_sphere(shift, colormap): x, y, z, simplices = create_pulse(shift) fig = ff.create_trisurf( x=x, y=y, z=z, simplices=simplices, aspectratio=aspectratio, plot_edges=False, colormap=colormap, show_colorbar=False, ) if shift == D: fig.data[0].update(opacity=0.4) fig_arr.append(fig)
def vol_render(vol, level=0, color='r', opacity=0.5, save=False, zoom_factor=False, name="Isosurface"): '''modified from #https://stackoverflow.com/questions/6030098/how-to-display-a-3d-plot-of-a-3d-array-isosurface-in-matplotlib-mplot3d-or-simil Inputs ------ vol == level : float (from measure.marching_cubes) Contour value to search for isosurfaces in `volume`. If not given or None, the average of the min and max of vol is used. colormap=['rgb(255,105,180)','rgb(255,255,51)','rgb(0,191,255)'] ''' if zoom_factor: vol = zoom(vol, zoom_factor, order=1) if color == 'r': colormap = ((.8, .1, .1), (.8, .1, .1)) #if color=='g': colormap=((.1,.8,.1),(.1,.8,.1)) if color == 'b': colormap = ((.1, .1, .8), (.1, .1, .8)) if color == 'bb': colormap = ((.6, .3, .8), (.5, .25, .8)) if color == 'o': colormap = [(0.4, 0.15, 0), (1, 0.65, 0.12)] if color == 'g': colormap = [(0.15, 0.4, 0), (0.65, 1, 0.12)] if color == 'p': colormap = [(0.15, 0, 0.4), (0.65, 0.12, 1)] vertices, faces, normals, values = measure.marching_cubes(vol, 0) x, y, z = zip(*vertices) fig = ff.create_trisurf(x=x, y=y, z=z, plot_edges=False, colormap=colormap, simplices=faces, title=name) #opacity fig['data'][0].update(opacity=opacity) #orientation #fig['layout'].update(dict(scene=dict(camera=dict(eye=dict(x=1.25, y=1.25, z=1.25))))) fig['layout'].update( dict(scene=dict(camera=dict(eye=dict(x=1.25, y=.25, z=.25))))) plotly.offline.plot(fig)
def plotly_3d(verts, faces): x, y, z = zip(*verts) # Make the colormap single color since the axes are positional not intensity. #colormap=['rgb(255,105,180)','rgb(255,255,51)','rgb(0,191,255)'] colormap = ['rgb(236, 236, 212)', 'rgb(236, 236, 212)'] fig = create_trisurf(x=x, y=y, z=z, plot_edges=False, colormap=colormap, simplices=faces, backgroundcolor='rgb(64, 64, 64)', title="Interactive Visualization") iplot(fig)
def plotly_3d(verts, faces): x, y, z = zip(*verts) print("Drawing") colormap = ['rgb(236, 236, 212)', 'rgb(236, 236, 212)'] fig = create_trisurf(x=x, y=y, z=z, plot_edges=False, colormap=colormap, simplices=faces, backgroundcolor='rgb(64, 64, 64)', title="Interactive Visualization") iplot(fig)
def visualize(thickness): """ 3D interpolation of the thickness profile. """ site['SITE_Z'] = thickness points2D = np.vstack([site['SITE_X'], site['SITE_Y']]).T tri = Delaunay(points2D) simplices = tri.simplices fig = ff.create_trisurf(site['SITE_X'], site['SITE_Y'], site['SITE_Z'], simplices=simplices, title="wafare", aspectratio=dict(x=1, y=1, z=0.5)) fig.show()
def _plotly3d(verts, faces): from plotly.offline import init_notebook_mode, iplot from plotly.figure_factory import create_trisurf init_notebook_mode() x, y, z = zip(*verts) cmap = ["rgb(236, 236, 212)", "rgb(236, 236, 212)"] fig = create_trisurf(x=x, y=y, z=z, plot_edges=False, simplices=faces, backgroundcolor="rgb(64, 64, 64)", colormap=cmap, title="Interactive Visualization") iplot(fig)
def draw_section(shift, colormap): x, y, z, simplices = create_section(shift) fig = ff.create_trisurf( x=x, y=y, z=z, simplices=simplices, aspectratio=aspectratio, plot_edges=False, colormap=colormap, show_colorbar=False, color_func=lambda x, y, z: np.abs(spherical_pulse.mask( x - shift, y, z)), ) if shift == D: fig.data[0].update(opacity=0.4) fig_arr.append(fig)
def plotly_3d(vertices, faces): """Creates fast, but not so high quality plot with plotly as html embedded javascript.""" x, y, z = zip(*vertices) # Make the colormap single color since the axes are positional not intensity. # colormap=['rgb(255,105,180)','rgb(255,255,51)','rgb(0,191,255)'] colormap = ['rgb(236, 236, 212)', 'rgb(236, 236, 212)'] fig = ff.create_trisurf(x=x, y=y, z=z, plot_edges=False, colormap=colormap, simplices=faces, backgroundcolor='rgb(64, 64, 64)', title="Interactive Visualization") plot(fig)
def showsolution(node,elem,u,**kwargs): ''' show 2D solution either of a scalar function or a vector field ''' markersize = 3000/len(node) if u.ndim == 1: uplot = ff.create_trisurf(x=node[:,0], y=node[:,1], z=u, simplices=elem, colormap="Viridis", # similar to matlab's default colormap showbackground=False, aspectratio=dict(x=1, y=1, z=1), ) fig = go.Figure(data=uplot) elif u.ndim == 2 and u.shape[-1] == 2: assert u.shape[0] == elem.shape[0] u /= (np.abs(u)).max() center = node[elem].mean(axis=1) uplot = ff.create_quiver(x=center[:,0], y=center[:,1], u=u[:,0], v=u[:,1], scale=.05, arrow_scale=.5, name='gradient of u', line_width=1, ) # uplot.add_trace(go.Scatter(x=center[:,0], y=center[:,1], # mode='markers', # marker=dict( # color='LightSkyBlue', # size=markersize, # # line=dict( # # color='MediumPurple', # # width=12 # # ) # ), # name='nodes in mesh')) fig = go.Figure(data=uplot) fig.update_layout(template='plotly_dark', margin=dict(l=5, r=5, t=5, b=5), **kwargs) fig.show()
def plot_iso_surface(fcn_grid, iso_level, n_samples, grid_max, title, color, display_plot): spacing = 2 * grid_max / n_samples vertices, simplices, _, _ = measure.marching_cubes_lewiner( fcn_grid, iso_level, spacing=(spacing, spacing, spacing)) x, y, z = zip(*vertices) x = np.array(x) - grid_max y = np.array(y) - grid_max z = np.array(z) - grid_max hover_text = generate_hover_text(x, y, z, 'Weight on Stock A', 'Weight on Stock B', 'Weight on Stock C') fig = ff.create_trisurf(x=x, y=y, z=z, plot_edges=False, show_colorbar=False, colormap=color, simplices=simplices) fig['data'][0].update(opacity=0.3, hoverinfo='none') trace = go.Scatter3d(x=x, y=y, z=z, mode='markers', marker=dict( size=6, opacity=0.0001, color='#BFB1A8', ), text=hover_text.flatten(), hoverinfo='text', showlegend=False) layout = create_standard_layout(title, 'Weight on') data = [fig.data[0], trace] fig = go.Figure(data=data, layout=layout) if display_plot: py.offline.iplot(fig) return data
def plotly_3d(verts, faces): x, y, z = zip(*verts) print("Drawing") # Make the colormap single color since the axes are positional not intensity. # colormap=['rgb(255,105,180)','rgb(255,255,51)','rgb(0,191,255)'] colormap = ['rgb(183, 110, 121)', 'rgb(183, 110, 121)'] fig = FF.create_trisurf(x=x, y=y, z=z, plot_edges=False, show_colorbar=False, colormap=colormap, simplices=faces, backgroundcolor='rgb(204, 204, 204)', title="Visualización Interactiva del Pulmón") iplot(fig)
def plotInteractive(self, image, threshold=300, step_size=1): ''' Method to visualize interactive plot using plotly Might crash, try at own risk ''' verts, faces, p = self.__build_mesh(image, threshold, step_size) print("Drawing") x, y, z = zip(*verts) colormap = ['rgb(236,236,212)', 'rgb(236,236,212)'] fig = figure_factory.create_trisurf(x=x, y=y, z=z, plot_edges = False, colormap = colormap, simplices = faces, backgroundcolor = 'rgb(64, 64, 64)', title = "Interactive Visualization") print('Plotting') plotly.plotly.plot(fig)
def renderFace(points, faces, name='face'): mesh = np.reshape(points, (-1, 3)) fig = FF.create_trisurf(x=mesh[:, 0], y=mesh[:, 1], z=mesh[:, 2], colormap=['rgb(200, 200, 200)'], simplices=faces, title="Some face", plot_edges=False, show_colorbar=False, showbackground=False, aspectratio=dict(x=1, y=1, z=1)) fig['layout'].update(title=name, scene=dict(camera=dict(up=dict(x=1, y=0, z=1), center=dict(x=0, y=0, z=0), eye=dict(x=0.0, y=0.0, z=1.5)), xaxis=dict(autorange=True, showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False), yaxis=dict(autorange=True, showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False), zaxis=dict(autorange=True, showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False))) fig['data'][0].update(opacity=1.0, lighting=dict(ambient=0.3, diffuse=0.8, roughness=0.7, specular=0.05, fresnel=0.01), lightposition=dict(x=100000, y=100000, z=10000)) plot(fig, filename=name + '.html')
def plot_problem(self, renderer='notebook'): import plotly.figure_factory as ff import plotly.graph_objs as go vertices = self.nos.T #[np.unique(self.elem_surf)].T elements = self.elem_surf.T fig = ff.create_trisurf( x=vertices[0, :], y=vertices[1, :], z=vertices[2, :], simplices=elements.T, color_func=elements.shape[1] * ["rgb(255, 222, 173)"], ) fig['data'][0].update(opacity=0.3) fig['layout']['scene'].update(go.layout.Scene(aspectmode='data')) try: if self.R != None: fig.add_trace( go.Scatter3d(x=self.R.coord[:, 0], y=self.R.coord[:, 1], z=self.R.coord[:, 2], name="Receivers", mode='markers')) except: pass if self.S != None: if self.S.wavetype == "spherical": fig.add_trace( go.Scatter3d(x=self.S.coord[:, 0], y=self.S.coord[:, 1], z=self.S.coord[:, 2], name="Sources", mode='markers')) import plotly.io as pio pio.renderers.default = renderer fig.show()
def _trisulf_data(image, threshold, color, opacity): image = image.copy().transpose(2, 1, 0) try: verts, faces, normals, values = measure.marching_cubes( image, threshold) x, y, z = verts.T except ValueError: x, y, z = [0], [0], [0] faces = [-1] return None fig = ff.create_trisurf(x=x, y=y, z=z, simplices=faces, plot_edges=False, show_colorbar=False, colormap=color, # color_func=[color] * len(faces) ) data = fig['data'][0] data.update(opacity=opacity) return data
def plotly_3d(verts, faces, mask, aspectratio=dict(x=1, y=1, z=1)): # plot using trisurf x, y, z = zip(*verts) colormap = ['rgb(236, 236, 212)', (1, 0.65, 0.12)] def mask_code(x, y, z): x, y, z = int(x), int(y), int(z) return mask[z, y, x] fig = FF.create_trisurf( x=x, y=y, z=z, color_func=mask_code if mask is not None else None, plot_edges=False, show_colorbar=True, aspectratio=aspectratio, colormap=colormap, simplices=faces, backgroundcolor='rgb(64, 64, 64)', title="Interactive Visualization", ) iplot(fig)
def plot_volume(fig_, volume_): # Resize volume if too big volume_ = resize_3d(volume_, new_size=100) # Here one could adjust the volume threshold if want to by adding level=level_value to marching_cubes verts, faces, normals, values = measure.marching_cubes(volume_) # Set the color of the surface based on the faces order. Here you can provide your own colouring color = np.zeros(len(faces)) color[0] = 1 # because there has to be a colour range, 1st element is 1 # create a plotly trisurf figure fig_volume = ff.create_trisurf(x=verts[:, 2], y=verts[:, 1], z=verts[:, 0], plot_edges=False, colormap=['rgb(170,170,170)'], simplices=faces, showbackground=False, show_colorbar=False ) fig_.add_trace(fig_volume['data'][0], col=2, row=1) return fig_
def draw_torus(total_radius, outer_radius, kind=GraphType.MPL, z_ratio=1, iterations=50): R = round(float(total_radius - outer_radius), 2) r = round(float(outer_radius), 2) if z_ratio == 0 or z_ratio is None: z_ratio = (r / R) u = np.linspace(0, 2 * np.pi, iterations) v = np.linspace(0 * np.pi, 2 * np.pi, iterations) u, v = np.meshgrid(u, v) if kind == GraphType.PLOTLY: plotly.offline.init_notebook_mode(connected=True) u = u.flatten() v = v.flatten() x = (R + r * np.cos(u)) * np.cos(v) y = (R + r * np.cos(u)) * np.sin(v) z = r * np.sin(u) points2d = np.vstack([u, v]).T tri = Delaunay(points2d) simplices = tri.simplices fig1 = FF.create_trisurf(x=x, y=y, z=z, simplices=simplices, title="Torus", aspectratio=dict(x=1, y=1, z=z_ratio)) plotly.offline.plot(fig1) elif kind == GraphType.MPL: x = (R + r * np.cos(u)) * np.cos(v) y = (R + r * np.cos(u)) * np.sin(v) z = r * np.sin(u) fig = plt.figure() ax = fig.gca(projection='3d') ax.set_xlabel('x axis') ax.set_ylabel('y axis') ax.set_zlabel('z axis') ax.set_xlim(-R, R) ax.set_ylim(-R, R) ax.set_zlim(-r, r) z = z * z_ratio # ax.plot_surface(x, y, z, alpha=0.8, cmap=cm.Wistia) ax.plot_surface(x, y, z, color='yellow', alpha=opacity, rstride=3, cstride=3, cmap=cm.Wistia) plt.show()
def create_trisurf(*args, **kwargs): FigureFactory._deprecated('create_trisurf') from plotly.figure_factory import create_trisurf return create_trisurf(*args, **kwargs)