Using the reticulate package enables Python usage within R and R Markdown documents.
library(reticulate)
For example, let's generate some random numbers from the Normal distribution with mean $\mu$ and standard deviation $\sigma$ which has the following probability density function:
$$ f(x \mid \mu, \sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2} } e^{ -\frac{(x-\mu)^2}{2\sigma^2} } $$
import numpy as np mu, sigma = 0, 0.1 # mean and standard deviation s = np.random.normal(mu, sigma, 1000)
\clearpage
import matplotlib import matplotlib.pyplot as plt if matplotlib.__version__ < '2.0.0': count, bins, ignored = plt.hist(s, 30, normed=True) else: count, bins, ignored = plt.hist(s, 30, density=True) plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2) ), linewidth=2, color='r') plt.show()
\clearpage
We can also visualize it in R via the exported py
object:
bins <- hist(py$s, col = "blue", breaks = 30, freq = FALSE, main = NULL, xlab = NULL, ylab = NULL) lines(bins$mids, dnorm(bins$mids, py$mu, py$sigma), col = "red", lwd = 2)
Note: likewise data from R can be accessed in Python using the exported r
object.
See this article for more information on using Python in R Markdown.
\clearpage
\footnotesize
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.