Using Python's Matplotlib with Rmarkdown
One way to include Matplotlib plots in Rmarkdown files within Blogdown is to save them to the /static
directory. Files in this directory are then copied over to the /public
directory for publishing.
pwd
mkdir -p ../../static/post/2017-10-28-using-python-s-matplotlib-with-rmarkdown_files
# The p flag will create the directory (and intermediate subdirectories) if it doesn't exist, otherwise will do nothing
## /Users/zac/git/zacbook.net/content/post
knitr::current_input() # will return the name of the Rmd file
## [1] "2017-10-28-using-python-s-matplotlib-with-rmarkdown.Rmd"
getwd() # will return the current work directory
## [1] "/Users/zac/git/zacbook.net/content/post"
rprojroot::find_rstudio_root_file() # will return the root of the project
## [1] "/Users/zac/git/zacbook.net"
# So should ensure that a directory is created in
# (ROOT)/(current work directory, removing project root, replace 'content' with 'static')/filename/
# Could also, perhaps, simply replace 'content' with 'static' in current work directory?
# although it seems that blogdown does not make subdirectories within 'static' to put images from rcode, so perhaps need to simplify to projectroot/static/filename ?
# The above statement is incorrect - blogdown does create subdirectories within static. The version that was not in a subdirectory was an old version!
For example:
import numpy as np
import matplotlib.pyplot as plt
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2*X)
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot (X, Y+1, color='blue', alpha=1.00)
## [<matplotlib.lines.Line2D object at 0x14f9e2f40>]
ax.plot (X, Y-1, color='blue', alpha=1.00)
## [<matplotlib.lines.Line2D object at 0x14f9e2a00>]
fig.savefig(
(
'../../static/post/'
'2017-10-28-using-python-s-matplotlib-with-rmarkdown_files/foo.png'
),
bbox_inches='tight',
dpi=600
)
Then using
![A wavy plot.](/post/2017-10-28-using-python-s-matplotlib-with-rmarkdown_files/foo.png)
the plot will be included in the post. Note that the subdirectory 2017-10-28-using-python-s-matplotlib-with-rmarkdown
needed to be created by hand. Knitr will not create these automatically as is done with plots generated from R code.
Output image:
This method does have limitations, such as breaking the inline previews in Rstudio, since they are expected to be in the same directory as the *.Rmd
file.