def test_append_scatter3d(): expected = Figure( data=Data([ Scatter3d( x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene='scene2' ), Scatter3d( x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene='scene2' ) ]), layout=Layout( scene1=Scene( domain={'y': [0.575, 1.0], 'x': [0.0, 1.0]} ), scene2=Scene( domain={'y': [0.0, 0.425], 'x': [0.0, 1.0]} ) ) ) fig = tls.make_subplots(rows=2, cols=1, specs=[[{'is_3d': True}], [{'is_3d': True}]]) trace = Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3]) fig.append_trace(trace, 1, 1) fig.append_trace(trace, 2, 1) assert fig == expected
def test_append_scatter3d(): expected = Figure(data=Data([ Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene='scene1'), Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene='scene2') ]), layout=Layout(scene1=Scene(domain={ 'y': [0.575, 1.0], 'x': [0.0, 1.0] }), scene2=Scene(domain={ 'y': [0.0, 0.425], 'x': [0.0, 1.0] }))) fig = tls.make_subplots(rows=2, cols=1, specs=[[{ 'is_3d': True }], [{ 'is_3d': True }]]) trace = Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3]) fig.append_trace(trace, 1, 1) fig.append_trace(trace, 2, 1) d1, d2 = strip_dict_params(fig['data'][0], expected['data'][0]) assert d1 == d2 d1, d2 = strip_dict_params(fig['data'][1], expected['data'][1]) assert d1 == d2 d1, d2 = strip_dict_params(fig['layout'], expected['layout']) assert d1 == d2
def main(): x, y, z = [0], [0], [f(0, 0)] h, i = 0.1, 0 while len(z) == 1 or abs(z[-2] - z[-1]) >= 0.0001: xi = x[-1] + (f(x[-1] + h, y[-1]) - z[-1]) / h yi = y[-1] + (f(x[-1], y[-1] + h) - z[-1]) / h x, y, z = x + [xi], y + [yi], z + [f(xi, yi)] if z[-2] >= z[-1]: h *= 0.5 i += 1 figure = make_subplots( cols=3, specs=[[{'type': 'xy'}, {'type': 'scene'}, {'type': 'scene'}]] ) xg, yg = meshgrid(linspace(-2, 2, 100), linspace(-0.2, 1, 100)) figure.add_trace(Scatter(x=x, y=y, name=''), row=1, col=1) figure.add_trace(Surface(x=xg, y=yg, z=f(xg, yg)), row=1, col=2) figure.add_trace(Scatter3d(x=x, y=y, z=z, name=''), row=1, col=2) xg, yg = meshgrid(linspace(-5, 5, 200), linspace(-5, 5, 200)) figure.add_trace(Surface(x=xg, y=yg, z=f(xg, yg)), row=1, col=3) figure.add_trace(Scatter3d(x=x, y=y, z=z, name=''), row=1, col=3) figure.update_layout( title=f'x = {x[-1]:.4f}, y = {y[-1]:.4f}, z = {z[-1]:.4f}, h = {h}, i = {i}', showlegend=False ) figure.show()
def PlotGeom(GRS, ID): edge_trace = Scatter3d( x=[], y=[], z=[], # hoverinfo='none', mode='lines') for i in range(GRS.nbElAll): sID = GRS.lsAll.sID[i] eID = GRS.lsAll.eID[i] x0 = GRS.nsAll.x[sID] y0 = GRS.nsAll.y[sID] z0 = GRS.nsAll.z[sID] x1 = GRS.nsAll.x[eID] y1 = GRS.nsAll.y[eID] z1 = GRS.nsAll.z[eID] edge_trace['x'] += [x0, x1, None] edge_trace['y'] += [y0, y1, None] edge_trace['z'] += [z0, z1, None] node_trace = Scatter3d( x=[], y=[], z=[], text=[], mode='markers', hoverinfo='text', marker=Marker( color=['red'], size=5, ), line=dict(width=2)) node_trace['x'].append(GRS.nsAll.x[ID]) node_trace['y'].append(GRS.nsAll.y[ID]) node_trace['z'].append(GRS.nsAll.z[ID]) fig = Figure(data=Data([edge_trace, node_trace]), layout=Layout( showlegend=False, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), height=500, width=1000, scene=dict( aspectmode='data', xaxis=dict( showgrid=False, zeroline=False), yaxis=dict( showgrid=False, zeroline=False), zaxis=dict( showgrid=False, zeroline=False), ), )) return fig
def main(f: Callable[[Any, ndarray], ndarray]): """ Ключова функція візуалізації вирішень ЗДУ. В якості методів присутні 3 вбудовані механізми - метод Рунге-Кутта порядку 3(2), порядку 5(4) і порядку 8 - й 1 самописний спосіб через метод Ейлера. P.S. початкова точка була дещо змінена відносно початкового завдання, це необхідно для деяких адекватних графіків. """ spec = {'type': 'scene'} figure = make_subplots(2, 2, specs=[[spec, spec], [spec, spec]], horizontal_spacing=0.02, vertical_spacing=0.02) span, y0 = (0.0, 150.0), array([-0.8, 0.8, 0.8]) rk23 = solve_ivp(f, span, y0, 'RK23') figure.add_trace( Scatter3d( name='RK23', x=rk23.y[0], # noqa y=rk23.y[1], # noqa z=rk23.y[2], # noqa mode='lines', line={'color': 'red'}), row=1, col=1) rk45 = solve_ivp(f, span, y0) figure.add_trace( Scatter3d( name='RK45', x=rk45.y[0], # noqa y=rk45.y[1], # noqa z=rk45.y[2], # noqa mode='lines', line={'color': 'magenta'}), row=1, col=2) dop853 = solve_ivp(f, span, y0, 'DOP853') figure.add_trace( Scatter3d( name='DOP853', x=dop853.y[0], # noqa y=dop853.y[1], # noqa z=dop853.y[2], # noqa mode='lines', line={'color': 'purple'}), row=2, col=1) euler = solve_ivp_euler(f, span, y0) figure.add_trace(Scatter3d(name='Euler', x=euler[0], y=euler[1], z=euler[2], mode='lines', line={'color': 'blue'}), row=2, col=2) figure.update_layout(margin={'t': 30, 'r': 30, 'b': 30, 'l': 30}) figure.show()
def plotKMeansCluster(data, dimensions): """Plots the kmeans output and displays it on web browser""" axisList = [] for i, c in enumerate(data): cluster_data = [] for point in c.points: cluster_data.append(point.coords) axis = {} centroid = {} if dimensions == 2: print("Displaying graph with 2 dimensions....") axis['x'], axis['y'] = zip(*cluster_data) axis['mode'] = 'markers' axis['marker'] = {} axis['marker']['symbol'] = i axis['marker']['size'] = 12 axis['name'] = "Cluster " + str(i) axisList.append(Scatter(**axis)) centroid['x'] = [c.centroid.coords[0]] centroid['y'] = [c.centroid.coords[1]] centroid['mode'] = 'markers' centroid['marker'] = {} centroid['marker']['symbol'] = i centroid['marker']['color'] = 'rgb(200,10,10)' centroid['name'] = "Centroid " + str(i) axisList.append(Scatter(**centroid)) else: print("Displaying graph with 3 dimensions....") symbols = [ "circle", "square", "diamond", "circle-open", "square-open", "diamond-open", "cross", "x" ] axis['x'], axis['y'], axis['z'] = zip(*cluster_data) axis['mode'] = 'markers' axis['marker'] = {} axis['marker']['symbol'] = symbols[i] axis['marker']['size'] = 12 axis['name'] = "Cluster " + str(i) axisList.append(Scatter3d(**axis)) centroid['x'] = [c.centroid.coords[0]] centroid['y'] = [c.centroid.coords[1]] centroid['z'] = [c.centroid.coords[2]] centroid['mode'] = 'markers' centroid['marker'] = {} centroid['marker']['symbol'] = symbols[i] centroid['marker']['color'] = 'rgb(200,10,10)' centroid['name'] = "Centroid " + str(i) axisList.append(Scatter3d(**centroid)) ##Plot the Kmeans output on web browser page #title = "K-means clustering" % str(len(data)) title = "K-means clustering with %s clusters" % str(len(data)) plotly.offline.plot({"data": axisList, "layout": Layout(title=title)})
def _plotly_cube_objects(x, y, z, style='line', color='#1f77b4', opacity=1.0): objs = list() for f in _plotly_cube_faces(): xp = [pt[0] + x for pt in f] yp = [pt[1] + y for pt in f] zp = [pt[2] + z for pt in f] # print(x, y, x) surf = Scatter3d(x=xp, y=yp, z=zp, marker=dict( size=4, color='#1f77b4', ), line=dict(color='#1f77b4', width=3)) objs.append(surf) surf = go.Mesh3d(x=xp, y=yp, z=zp, color=color, delaunayaxis='x', opacity=0.5) objs.append(surf) return objs
def plot_diseases_or_countries_3d(years=[2000],axis='disease',method='mds',outname='d_clusters_by_c_pattern_mds',data_pd=fdata_pd): # axis is 'disease' or 'country' # years is subset range 1990-2016 # method is 'pca' or 'mds' scaler = StandardScaler() if axis=='disease': year_slices = [scaler.fit_transform(data_pd.loc[(fdata_pd['year'].isin([year])),lambda s: s.columns[2:]].T) for year in years] elif axis=='country': year_slices = [scaler.fit_transform(data_pd.loc[(fdata_pd['year'].isin([year])),lambda s: s.columns[2:]]) for year in years] if method=='mds': red = MDS(n_components=3) elif method=='pca': red = PCA(n_components=3) # fit with full data all_year_slices = np.concatenate([year_slices[i] for i in range(len(year_slices))],axis=0) red.fit(all_year_slices) # transform individuals... could use above, not most efficient, can fix if time is issue. year_slices = [red.fit_transform(item) for item in year_slices] traces = []; for row in year_slices: traces.append([Scatter3d(x=year[:,0],y=year[:,1],z=year[:,2],mode='markers') for year in year_slices]) data = Data(traces) iplot(data, filename = outname)
def yerrorbar(self, ax, X, Y, error, Z=None, color=Tango.colorsHex['mediumBlue'], label=None, error_kwargs=None, **kwargs): error_kwargs = error_kwargs or {} if (error.shape[0] == 2) and (error.ndim == 2): error_kwargs.update( dict(array=error[1], arrayminus=error[0], symmetric=False)) else: error_kwargs.update(dict(array=error, symmetric=True)) if Z is not None: return Scatter3d(x=X, y=Y, z=Z, mode='markers', error_y=ErrorY(color=color, **error_kwargs or {}), marker=Marker(size='0'), name=label, showlegend=label is not None, **kwargs) return Scatter(x=X, y=Y, mode='markers', error_y=ErrorY(color=color, **error_kwargs or {}), marker=Marker(size='0'), name=label, showlegend=label is not None, **kwargs)
def plot_axis_lines(self, ax, X, color=Tango.colorsHex['mediumBlue'], label=None, marker_kwargs=None, **kwargs): if X.shape[1] == 1: annotations = Annotations() for i, row in enumerate(X): annotations.append( Annotation( text='', x=row[0], y=0, yref='paper', ax=0, ay=20, arrowhead=2, arrowsize=1, arrowwidth=2, arrowcolor=color, showarrow=True, #showlegend=i==0, #label=label, )) return annotations elif X.shape[1] == 2: marker_kwargs.setdefault('symbol', 'diamond') opacity = kwargs.pop('opacity', .8) return Scatter3d(x=X[:, 0], y=X[:, 1], z=np.zeros(X.shape[0]), mode='markers', projection=dict(z=dict(show=True, opacity=opacity)), marker=Marker(color=color, **marker_kwargs or {}), opacity=0, name=label, showlegend=label is not None, **kwargs)
def plot(self, ax, X, Y, Z=None, color=None, label=None, line_kwargs=None, **kwargs): if 'mode' not in kwargs: kwargs['mode'] = 'lines' if Z is not None: return Scatter3d(x=X, y=Y, z=Z, showlegend=label is not None, line=Line(color=color, **line_kwargs or {}), name=label, **kwargs) return Scatter(x=X, y=Y, showlegend=label is not None, line=Line(color=color, **line_kwargs or {}), name=label, **kwargs)
def plot(self): """ Plot the figure. Call this last.""" traces = [] for dataset in self.xy_datasets: kwargs = {} if 'name' in dataset and dataset['name'] is not None: kwargs['name'] = dataset['name'] self.zindex = kwargs['name'] else: kwargs['showlegend'] = False zvals = np.full(np.size(dataset['x']), self.zindex) traces.append(Scatter3d( x = dataset['x'], z = dataset['y'], y = zvals, mode = 'lines', **kwargs )) if not isinstance(self.zindex, str): self.zindex += 1 data = Data(traces) plotly.offline.iplot({ 'data': data, 'layout': self.makeLayout() })
def test_append_scatter3d_after_deleting_scene(): fig = tls.make_subplots(rows=2, cols=1, specs=[[{'is_3d': True}], [{'is_3d': True}]]) trace = Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3]) fig['layout'].pop('scene1', None) fig.append_trace(trace, 1, 1)
def test_figure_json_encoding(): df = pd.DataFrame(columns=['col 1'], data=[1, 2, 3]) s1 = Scatter3d(x=numeric_list, y=np_list, z=mixed_list) s2 = Scatter(x=df['col 1']) data = Data([s1, s2]) figure = Figure(data=data) js1 = json.dumps(s1, cls=utils.PlotlyJSONEncoder, sort_keys=True) js2 = json.dumps(s2, cls=utils.PlotlyJSONEncoder, sort_keys=True) assert (js1 == '{"type": "scatter3d", "x": [1, 2, 3], ' '"y": [1, 2, 3, null, null, null, "2014-01-05"], ' '"z": [1, "A", "2014-01-05", ' '"2014-01-05 01:01:01", "2014-01-05 01:01:01.000001"]}') assert (js2 == '{"type": "scatter", "x": [1, 2, 3]}') # Test JSON encoding works json.dumps(data, cls=utils.PlotlyJSONEncoder, sort_keys=True) json.dumps(figure, cls=utils.PlotlyJSONEncoder, sort_keys=True) # Test data wasn't mutated assert (bool( np.asarray(np_list == np.array( [1, 2, 3, np.NaN, np.NAN, np.Inf, dt(2014, 1, 5)])).all())) assert (set(data[0]['z']) == set([ 1, 'A', dt(2014, 1, 5), dt(2014, 1, 5, 1, 1, 1), dt(2014, 1, 5, 1, 1, 1, 1) ]))
def plot_mesh_via_plotly(in_mesh, colormap=cm.RdBu, plot_edges=None, vertex_color=None, show=True): '''Alternative to plotting a mesh with plotly.''' x = in_mesh.vertices[:, 0] y = in_mesh.vertices[:, 1] z = in_mesh.vertices[:, 2] simplices = in_mesh.triangles tri_vertices = map(lambda index: in_mesh.vertices[index], simplices) # vertices of the surface triangles I, J, K = ([triplet[c] for triplet in simplices] for c in range(3)) triangles = Mesh3d(x=x, y=y, z=z, i=I, j=J, k=K, name='', intensity=vertex_color) if plot_edges is None: # The triangle edges are not plotted. res = Data([triangles]) else: # Define the lists Xe, Ye, Ze, of x, y, resp z coordinates of edge end points for each triangle # None separates data corresponding to two consecutive triangles lists_coord = [[[T[k % 3][c] for k in range(4)] + [None] for T in tri_vertices] for c in range(3)] Xe, Ye, Ze = [reduce(lambda x, y: x + y, lists_coord[k]) for k in range(3)] # Define the lines to be plotted lines = Scatter3d(x=Xe, y=Ye, z=Ze, mode='lines', line=Line(color='rgb(50, 50, 50)', width=1.5)) res = Data([triangles, lines]) if show: iplot(res) else: return res
def dots_3d(x, y, z, **attributes): return Scatter3d( x=x, y=y, z=z, mode='markers', name=attributes['name'] if 'name' in attributes else 'unnamed-dots', marker=dict_without_keys(attributes, 'name'))
def test_figure_json_encoding(): s = Scatter3d(x=numeric_list, y=np_list, z=mixed_list) data = Data([s]) figure = Figure(data=data) json.dumps(s, cls=utils._plotlyJSONEncoder) json.dumps(data, cls=utils._plotlyJSONEncoder) json.dumps(figure, cls=utils._plotlyJSONEncoder)
def getGraphResult(self): _representSpeed = self.dfPacmod.query("remove==0").groupby( "groupBrake").mean()["speed"].values _representBrake = self.dfPacmod.query("remove==0").groupby( "groupBrake").mean()["brake"].values _representAcceleration = self.dfPacmod.query("remove==0").groupby( "groupBrake").mean()["accFiltered"].values _surface = Surface(x=self.brakeResult, y=self.speedResult, z=self.predictedAcceleration * (self._accMaxNum - self._accMinNum) + self._accMinNum, colorscale='YlGnBu', name="predictSurface") _scatterRepresent = Scatter3d(x=_representBrake, y=_representSpeed, z=_representAcceleration, mode='markers', marker=dict(size=2, color="green"), name="Boss") _scatterRemove = Scatter3d( x=self.dfPacmod.query("remove==0").brake, y=self.dfPacmod.query("remove==0").speed, z=self.dfPacmod.query("remove==0").accFiltered, mode='markers', marker=dict(size=3, color="blue"), name="RemoveOutliers") layout = go.Layout(title="ThrottleModel", scene=dict(xaxis=dict(title="CMD(Brake)", range=[0, 0.7]), yaxis=dict(title="speed", range=[20, 0]), zaxis=dict(title="acceleration", range=[-3, 0]))) fig = go.Figure(data=[_surface, _scatterRepresent, _scatterRemove], layout=layout) _figName = "brake.html" print("saveGraphFileName:" + self.resultDirectory + _figName) plotly.offline.plot(fig, filename=self.resultDirectory + _figName)
def make_edge(x, y, z, weight): return Scatter3d( x=x, y=y, z=z, # line=dict(color='rgb(' + str(int(100 + (weight ** 2 - 0.25) * 100)) + ',100,100)', width=(weight * 3) ** 2), line=dict(color='rgb(' + str(int(weight) * 180) + ', 0, 0)', width=(weight * 3)**2), hoverinfo='none', mode='lines')
def _plot_trajectory(self, trajectory, label, color, dashed): trace = Scatter3d( x=trajectory.x.to(u.km).value, y=trajectory.y.to(u.km).value, z=trajectory.z.to(u.km).value, name=label, line=dict( color=color, width=5, dash='dash' if dashed else 'solid', ), mode="lines", # Boilerplate ) self._data.append(trace)
def triplot(pca, dat, title='', components=(0, 1, 2), color=None): pc1, pc2, pc3 = components # 0,1 denote PC1 and PC2; change values for other PCs xvector = pca.components_[pc1] yvector = pca.components_[pc2] zvector = pca.components_[pc3] tmp = pca.transform(dat.values) xs = tmp[:, pc1] ys = tmp[:, pc2] zs = tmp[:, pc3] annotations = [ Scatter3d(x=xs, y=ys, z=zs, mode='markers', marker=dict(size=2, opacity=0.2, color=color), name='scatter') ] for i in range(len(xvector)): txt = list(dat.columns.values)[i] annotations.append( Scatter3d( x=[0, xvector[i] * max(xs)], y=[0, yvector[i] * max(ys)], z=[0, zvector[i] * max(zs)], mode='lines+text', text=['', txt], name=txt, )) py.iplot({ "data": annotations, "layout": Layout(xaxis=XAxis(title='Principal Component One'), yaxis=YAxis(title='Principal Component Two'), title=title) })
def _plot_trajectory(self, trajectory, label, color, dashed): trace = Scatter3d( x=trajectory.x.to(u.km).value, y=trajectory.y.to(u.km).value, z=trajectory.z.to(u.km).value, name=label, line=dict(color=color, width=5, dash="dash" if dashed else "solid"), mode="lines", # Boilerplate ) self._figure.add_trace(trace) return trace
def _line3d(self, points: ndarray) -> Scatter3d: """ Обрахунок тривимірної ламаної на поверхні сфери. """ x, y, z = inflate(points, r=self._r, z=self._z) return Scatter3d(x=x, y=y, z=z, mode='lines', hoverinfo='skip', line={ 'color': self._outer_line_color, 'width': self._outer_line_width })
def _plotly_3d_scatter(coords, partition=None): """ _plotly_3d_scatter(coords, partition=None) Make a scatterplot of treeCl.CoordinateMatrix using the Plotly plotting engine """ from plotly.graph_objs import Scatter3d, Data, Figure, Layout, Line, Margin, Marker # auto sign-in with credentials or use py.sign_in() colourmap = { 'A': '#1f77b4', 'B': '#ff7f0e', 'C': '#2ca02c', 'D': '#d62728', 'E': '#9467bd', 1: '#1f77b4', 2: '#ff7f0e', 3: '#2ca02c', 4: '#d62728', 5: '#9467bd' } df = coords.df if partition: assert len(partition.partition_vector) == df.shape[0] labels = [x + 1 for x in partition.partition_vector] else: labels = [1 for _ in range(df.shape[0])] x, y, z = df.columns[:3] df['Label'] = labels colours = [colourmap[lab] for lab in df['Label']] trace = Scatter3d(x=df[x], y=df[y], z=df[z], mode='markers', marker=Marker(size=9, color=colours, line=Line(color=colours, width=0.5), opacity=0.8), text=[str(ix) for ix in df.index]) data = Data([trace]) layout = Layout( margin=Margin(l=0, r=0, b=0, t=0), hovermode='x', ) fig = Figure(data=data, layout=layout) return fig
def _plotly_cube_mesh(x, y, z, dx, dy, dz, include_mesh=False, opacity=0.5, include_lines=True): xv0 = [0, 1, 1, 0, 0, 1, 1, 0] xv = [xvi * dx + x for xvi in xv0] yv0 = [0, 0, 1, 1, 0, 0, 1, 1] yv = [yvi * dy + y for yvi in yv0] zv0 = [0, 0, 0, 0, 1, 1, 1, 1] zv = [zvi * dz + z for zvi in zv0] objs = list() if include_mesh: i = [1, 4, 1, 3, 1, 2, 5, 7, 3, 4, 2, 7] j = [0, 5, 0, 2, 2, 6, 6, 4, 0, 7, 6, 3] k = [4, 1, 3, 1, 5, 5, 7, 5, 4, 3, 7, 2] mesh = go.Mesh3d(x=xv, y=yv, z=zv, color='#1f77b4', i=i, j=j, k=k, lighting=dict(ambient=0.2), opacity=opacity) objs.append(mesh) if include_lines: lines = [(0, 1), (1, 5), (5, 4), (4, 0), (4, 7), (7, 3), (3, 0), (3, 2), (2, 6), (6, 7), (5, 6), (1, 2)] for lv in lines: xl = [xv[lv[0]], xv[lv[1]]] yl = [yv[lv[0]], yv[lv[1]]] zl = [zv[lv[0]], zv[lv[1]]] line = Scatter3d(x=xl, y=yl, z=zl, marker=dict( size=4, color='#1f77b4', ), line=dict(color='#1f77b4', width=3)) objs.append(line) return objs
def frame_plane_3d(): """ Функція побудови 3D-рамки контуру. Тепер вже додається z-координата. """ figure = Figure() shape = contour() figure.add_trace( Scatter3d(x=shape[:, 0], y=shape[:, 1], z=zeros((len(shape), )), mode='lines', hoverinfo='skip', line={'color': 'red'})) figure.show()
def test_figure_json_encoding(): s1 = Scatter3d(x=numeric_list, y=np_list, z=mixed_list) s2 = Scatter(x=pd['col 1']) data = Data([s1, s2]) figure = Figure(data=data) js1 = json.dumps(s1, cls=utils._plotlyJSONEncoder, sort_keys=True) js2 = json.dumps(s2, cls=utils._plotlyJSONEncoder, sort_keys=True) assert (js1 == '{"type": "scatter3d", "x": [1, 2, 3], ' + '"y": [1, 2, 3], "z": [1, "A", "2014-01-05"]}') assert (js2 == '{"type": "scatter", "x": [1, 2, 3]}') json.dumps(data, cls=utils._plotlyJSONEncoder, sort_keys=True) json.dumps(figure, cls=utils._plotlyJSONEncoder, sort_keys=True)
def TestShow(self, sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals): x = [min(sequence_containing_x_vals), max(sequence_containing_x_vals)] y = [min(sequence_containing_y_vals), max(sequence_containing_y_vals)] z = [min(sequence_containing_z_vals), max(sequence_containing_z_vals)] trace1 = Scatter3d( x=sequence_containing_x_vals, y=sequence_containing_y_vals, z=sequence_containing_z_vals, mode='markers', name='ryannair', marker=dict( #color='rgb(127, 127, 127)', size=6, symbol='circle', line=dict(color='rgb(204, 204, 204)', width=0.1), opacity=1)) cubeX, cubeY, cubeZ = self.createCuboid(x, y, z) trace2 = Scatter3d( x=cubeX, y=cubeY, z=cubeZ, mode='lines', name='Selected planes', ) data = [trace1, trace2] layout = Layout(scene=dict( xaxis=dict(range=[-1, 1], ), yaxis=dict(range=[-1, 1], ), zaxis=dict(range=[-1, 1], ), ), ) fig = Figure(data=data, layout=layout) plot(fig)
def test_append_scatter3d(): expected = Figure( data=Data([ Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene="scene1"), Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene="scene2"), ]), layout=Layout( scene1=Scene(domain={ "y": [0.575, 1.0], "x": [0.0, 1.0] }), scene2=Scene(domain={ "y": [0.0, 0.425], "x": [0.0, 1.0] }), ), ) fig = tls.make_subplots(rows=2, cols=1, specs=[[{ "is_3d": True }], [{ "is_3d": True }]]) trace = Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3]) fig.append_trace(trace, 1, 1) fig.append_trace(trace, 2, 1) d1, d2 = strip_dict_params(fig["data"][0], expected["data"][0]) assert d1 == d2 d1, d2 = strip_dict_params(fig["data"][1], expected["data"][1]) assert d1 == d2 d1, d2 = strip_dict_params(fig["layout"], expected["layout"]) assert d1 == d2
def frame_sphere(): """ Графік, що проектує зчитану фігуру на сферу. Основна логіка перетворення прописана у функції нижче, тут присутня лише візуалізація. """ figure = Figure() x, y, z = inflate(contour()) figure.add_trace( Scatter3d(x=x, y=y, z=z, mode='lines', hoverinfo='skip', line={'color': 'red'})) figure.show()