Plotting functions
Cadabra can plot your functions of one or two variables using thecdb.graphics.plot
packages.
Plotting itself is handled by matplotlib (with a backend for plotly in preparation), but you do not have to know anything about that
in order to use the plotting facilities.Functions of one variable
Functions of one variable can be plotted using theplot
function of the cdb.graphics.plot
package. Its
basic form takes a Cadabra expression which is a function of one variable, as well as a triplet containing
the independent variable and its start and end value.from cdb.graphics.plot import *
plot($\sin(x) (1-x**2)$, ($x$, 0, 20));
Multiple functions can be plotted in the same figure by simply feeding a list of functions as the first argument
to
plot
, as in the example below. This also shows how to customise the plot by setting the title and axes.plot([$\sin(x) (1-x**2)$, $100 \cos(x)$], ($x$, 0, 20), title="Two functions", xlabel="time", ylabel="value", grid=True);
Parametric plots in two dimensions
If you have a parametric representation of the curve you want to plot, there is a functionparametric_plot
, which
takes two arguments (or two lists of arguments). In the example below, we plot two parametric curves.
The first argument is a list of two functions (of the parameter $t$) for the
$x$-coordinates, while the second argument is a list of two functions for the $y$-coordinates. In order to make this
more readable, we have defined the functions as Cadabra expressions on separate lines.f1x := (1-(t/20)**2) \cos(t);
f1y := (1-(t/20)**2) \sin(t);
f2x := 1.2\cos(t);
f2y := 1.2\sin(t);
parametric_plot([f1x, f2x], [f1y, f2y], ($t$, 0, 20), xrange=[-1.7, 1.7]);
\(\displaystyle{}\left(1 - \frac{1}{400}{t}^{2}\right) \cos{t}\)
(1 - 1/400 (t)**2) \cos(t)
\(\displaystyle{}\left(1 - \frac{1}{400}{t}^{2}\right) \sin{t}\)
(1 - 1/400 (t)**2) \sin(t)
\(\displaystyle{}1.2 \cos{t}\)
1.2 \cos(t)
\(\displaystyle{}1.2 \sin{t}\)
1.2 \sin(t)
Animations
You can make animations of functions by plotting each successive frame separately, but re-using the output cell into which the frames are displayed. In the example below,out
is the ID of the output cell (initially zero),
and the display
function is used to display each frame, overwriting the content of the output cell (this functionality
is currently unavailable when using Cadabra from Jupyter).out=0
import time
for a in np.concatenate( [np.linspace(0.5, 3.0, 100), np.linspace(3.0, 0.5, 100)] ):
p = plot($\sin( @(a) x) (1 - x**2)$, ($x$, 0, 10), yrange=[-50, 50], title=f"a = {a:.2f}")
out = display(p, out)
time.sleep(0.01)
You can do this with any of Cadabra's plot types, e.g. parametric plots, as in the example below.
out=0
import time
for a in np.linspace(0, 3*6.28, 100):
p = parametric_plot($\cos(t)$, $\sin(t)$, ($t$, a, a+0.5), xrange=[-1.5, 1.5], yrange=[-1.2, 1.2])
out = display(p, out)
time.sleep(0.01)