Code blocks that produce figures#
This can be done with notebooks, but it’s not easy to make references to figures in notebooks. You can also place the code that produces and saves the figure in a separate .py
file, and include that in a markdown file. Let’s say we want to make a simple sine wave:
Place the code of the figure in a
.py
file. In this case,sinewave.py
produces our figure. The code looks like this:import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, endpoint=True) y = np.sin(x) plt.figure() plt.plot(x, y) plt.title('$y=\sin(x)$') plt.xlabel('$x$') plt.ylabel('$y$') plt.savefig('sinewave.svg')
Warning
It is important that the name of the saved figure is exactly the same as the name of the Python script that generates it. Otherwise, the figure will not be generated by the Runner.
Test your code and make sure that the figure looks good. When you are ready to commit, place your code file in
book/code
.
The book uses a Matplotlib style sheet; to see what this looks like on your local machin you will have to run plt.style.use('../../config/matplotlibrc')
after importing Matplotlib. This should be done outside of the *.py
file you are creating. Note that the example style sheet path assumes you are working in the book/code
directory. It is recommended to preserve a list of figures using a notebook in code_checks
, where there are also working examples. It is not necessary to commit *.svg
files as these are cleaned when the book is generated.
Now include the code file by using the following directives:
````{toggle} ```{eval-rst} .. literalinclude:: ../sinewave.py :language: python ``` ````
Note
the outer most directive needs an extra tick mark for nested cases.
Include the figure as described above. Remember that figures are saved in the
book/figures
directory. We also use a naming convention of*_py.svg
for figures generated from code, to easily include them in.gitignore
, since they are built in the CI/CD pipeline.