Minimal example of polyglot python + R in RMarkdown

First, we load the iris dataset using seaborn in python:

import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset('iris')
iris
##      sepal_length  sepal_width  petal_length  petal_width    species
## 0             5.1          3.5           1.4          0.2     setosa
## 1             4.9          3.0           1.4          0.2     setosa
## 2             4.7          3.2           1.3          0.2     setosa
## 3             4.6          3.1           1.5          0.2     setosa
## 4             5.0          3.6           1.4          0.2     setosa
## ..            ...          ...           ...          ...        ...
## 145           6.7          3.0           5.2          2.3  virginica
## 146           6.3          2.5           5.0          1.9  virginica
## 147           6.5          3.0           5.2          2.0  virginica
## 148           6.2          3.4           5.4          2.3  virginica
## 149           5.9          3.0           5.1          1.8  virginica
## 
## [150 rows x 5 columns]

Then, we plot this in R:

library(ggplot2)
py <- reticulate::py  # Interface to python session
ggplot(py$iris, aes(x = sepal_length, y = petal_length)) +
  geom_point() +
  stat_smooth(method = "lm") +
  theme_bw(base_size = 13) +
  ggtitle("Relationship between sepal and petal length in Iris") 
## `geom_smooth()` using formula 'y ~ x'

We can also do the reverse.

Load the iris dataset using data() in R

data(iris)
head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

Then, we plot this in python

# the "r" object is the interface to the R environment.
sns.regplot(
  data=r.iris,
  x="Sepal.Length",
  y="Petal.Length"
).set(title="Relationship between sepal and petal length in Iris")
plt.show()