Viewing Fields
Plotting 2d Vector Fields
With the help of Numpy
we’ll create the plot with Plotly
import plotly.figure_factory as ff
import plotly.graph_objects as go
import numpy as np
Field Definition:
We’ll define the coordinate grid with a meshgrid of x and y values ranging from -4 to 4 with a step of 0.2.
x, y = np.meshgrid(np.arange(-4, 4.2, .2), np.arange(-4, 4.2, .2))
Then we’ll separately define the x and y components of our 2d vector field. In this example, the vector field is defined by the functions np.sin(x + y)
and np.cos(y - x)
, respectively. These functions generate the vector components based on the input coordinates.
u = np.sin(x + y)
v = np.cos(y - x)
Iterating Upon the Field Definition to Produce the Plot:
We can use Plotly’s create_quiver
function to generate a plot of the vector field. It passes the meshgrid of x and y values along with the corresponding u and v components to create arrows representing the vector field. Additional parameters such as scale
, arrow_scale
, and line_width
are adjusted to control the appearance of the plot. The update_yaxes
function ensures that the aspect ratio of the plot is maintained.
fig = ff.create_quiver(x, y, u, v,
scale=.25,
arrow_scale=.1,
name='Field',
line_width=1)
fig.update_yaxes(
scaleanchor="x",
scaleratio=1)
fig.show()
Plotting 3d Vector Fields
We can use Plotly’s 3d cone plot function to generate a plot of a 3d vector field. It passes the meshgrid of x, y, and z values along with the corresponding u, v, and w components to create cones representing the vector field.
import plotly.graph_objects as go
import numpy as np
x, y = np.meshgrid(np.arange(-4, 4.2, 0.2), np.arange(-4, 4.2, 0.2))
z = np.zeros_like(x)
u = np.sin(x + y)
v = np.cos(y - x)
w = np.zeros_like(x) # w is zero
# Create the plot
fig = go.Figure(data=go.Cone(
x=x.flatten(),
y=y.flatten(),
z=z.flatten(),
u=u.flatten(),
v=v.flatten(),
w=w.flatten(),
colorscale='Blues',
sizemode="absolute",
sizeref=4))
fig.update_layout(scene=dict(aspectratio=dict(x=1, y=1, z=0.8),
camera_eye=dict(x=1.2, y=1.2, z=0.6)))
fig.show()
Here’s another example
import plotly.graph_objects as go
import numpy as np
# Define the coordinate grid
x, y, z = np.meshgrid(np.arange(-4, 4.2, 0.8),
np.arange(-4, 4.2, 0.8),
np.arange(-4, 4.2, 0.8))
# Define the components of the vector field using polynomial functions
u = y - z
v = x + z
w = x - y
# Create the plot
fig = go.Figure(data=go.Cone(
x=x.flatten(),
y=y.flatten(),
z=z.flatten(),
u=u.flatten(),
v=v.flatten(),
w=w.flatten(),
sizemode="scaled",
sizeref=3,
colorscale="Portland",
cmin=0,
cmax=15,
hoverinfo="u+v+w"))
fig.update_layout(scene=dict(aspectratio=dict(x=1, y=1, z=0.8),
camera_eye=dict(x=1.2, y=1.2, z=0.6)))
fig.show()