Lab: Plotting with Python
In this lab, you will develop a program to plot mathematical equations using Python.
Instructions
You should complete this lab individually.
Step 1: Review Starter Code
Download and review the starter code, consulting the documentation for these Python modules:
Before running the starter code, you must install seaborn.
Next, use the --help
option to see program’s command-line interface:
> python plot.py --help
usage: plot.py [-h] [--x-min X_MIN] [--x-max X_MAX] [--output OUTPUT] expr
Plot mathematical equations.
positional arguments:
expr A mathematical expression in terms of x
options:
-h, --help show this help message and exit
--x-min X_MIN The minimum x-value to display
--x-max X_MAX The maximum x-value to display
--output OUTPUT Name of the output file to save
Step 2: Implementation
Modify the starter code to support plotting x,x2, and x3. This will involve calculating the corresponding y-value for each x-value, according to the expression specified by the user. By default, the program will save plots to output.png
.
If implemented correctly, you should see output like:
> python plot.py x
> python plot.py "x**2"
> python plot.py "x**3"
Note: Quotation marks are used around "x**2"
and "x**3"
, because the *
character has a special meaning to the command-line shell.
Note: Do not change the visual styling of the graphs, or the autograder will get confused.
Optional: Support Arbitrary Expressions
Rather than hardcode the calculation of x,x2, and x3, it is possible to support graphing any mathematical expression. I recommend implementing this functionality using the SymPy library. For example, you could interpret the expression typed by the user with sympify()
and you could substitute values into the expression using subs()
.
A further benefit of using SymPy is that you can solve for an equation’s inverse. For example, this shows the plot of 1x−2 and its inverse:
> python plot.py "1/(x-2)"
Submit
Upload plot.py
to Gradescope.
Learning Goals
- Evaluate equations in Python
- Graph equations in Python