In this recipe, we will see how to plot a 3D trefoil knot. A trefoil knot is a closed curve with three crossings. In this recipe, we will draw not just a curve, but a solid 3D curve. This is beyond the plotly capabilities, and we will implement this functionality using a trick.
In this recipe, we will:
plotly
.plotly
to draw the chart:import numpy as np import plotly.plotly as py from plotly.graph_objs import Scatter3d, Data, Layout from plotly.graph_objs import Figure, Line, Margin, Marker from numpy import linspace,pi,cos,sin phi = linspace(0,2*pi,250) x = sin(phi)+2*sin(2*phi) y = cos(phi)-2*cos(2*phi) z = -sin(3*phi) traces = list() colors = ['rgb(%d,50,210)' % c for c in np.abs(z / max(z)) * 255] for i in linspace(-np.pi,np.pi,50): trace = Scatter3d(x=x+np.cos(i)*.5, y=y+np.sin(i)*.5, z=z, mode='markers', marker=Marker(color=colors, size=13)) traces.append(trace) data = Data(traces) layout = Layout(showlegend=False, autosize=False, width=500, height=500, margin=Margin(l=0,r=0,b=0,t=65)) fig = Figure(data=data, layout=layout) plot_url = py.plot(fig, filename='3d-trifoil')
First, we generated all the points of our knot curve using the following parametric equations:
x = sin(phi)+2*sin(2*phi) y = cos(phi)-2*cos(2*phi) z = -sin(3*phi)
This means that x
, y
, and z
are parallel vectors, and the point (x[i]
, y[i]
, z[i]
) is a point of our curve in the 3D space. To generate a solid curve, we created a series of other curves around the main one. Indeed, we generated a set of Scatter3d
objects (each one is a curve).
To give to the knot a 3D effect, we draw each point of each curve with a different color. The color is the function of the z
coordinate, and it is blue when z
is equal to 0
and gradually becomes purple when z
moves away from 0
.
The colors were specified with a list of RGB triplets. Indeed, if we take a look at the values of the list colors, it will look like this:
['rgb(0,50,210)', 'rgb(19,50,210)', 'rgb(38,50,210)', 'rgb(57,50,210)', 'rgb(76,50,210)', ...
Each element is a string that contains the RGB value of one of the points of the curve.
The results are as follows:
Here, we can not only zoom in and out, but also rotate the figure.