2-dimensional plots of functions with SageMath
Plot of a symbolic function
A minimal plot:
Adding some options:
The list of options, along with some examples of use, is accessible via
It is also accessible online.
Storing the plot object in a Python variable:
Plot objects can be added:
The command show can be used to display the object g1+g2 with extra options:
The documentation for all possible options of show is returned by
It is also accessible online here.
Saving the plot in a pdf file (with the same options as in show):
Adding graphic objects in a Python loop:
Side remark: in the above code, we have implicitely redefined the Python variable i as an integer denoting the loop index, while i was predefined as the imaginary number such that . Consequently, we have now
To restore the use of the Python name i for the imaginary number, it suffices to run
Symbolic functions versus Python functions
Let us consider a symbolic function:
We can plot f(x) as we did above for sin(x^2):
It is also possible to pass the function f itself (not the symbolic expression f(x)), along with the lower and upper boundaries for the argument of f required in the plot, without having to specify any name for this argument:
This second way of plotting function is actually the one that must be used for the plot of Python functions:
Actually, if we use the first method, we obtain a strange result:
This occurs because the argument f1(x) of the function plot is evaluated prior to any loop on the values of x within the specified interval. Since for the symbolic variable x one has
the function f1 always returns cos(x), hence the plot.
What about plotting Python functions with more than one argument? For instance suppose we want to plot the following function for some fixed value of the argument a:
plot(f2, (0,4)) would return an error here. A first solution would be to wrap f2 into a single-argument Python function:
A better solution is to use create an anonymous function with the Python keyword lambda:
In particular, it is very usefull in loops:
Plot from data
Let us consider a list of values, of the type :
We can plot it with list_plot:
An alternative is to use line: