Skip to content

Instantly share code, notes, and snippets.

@millerh1
Created March 3, 2022 00:00
Show Gist options
  • Save millerh1/bb0d169b23d911bce548014f630ce3c0 to your computer and use it in GitHub Desktop.
Save millerh1/bb0d169b23d911bce548014f630ce3c0 to your computer and use it in GitHub Desktop.
Polyglot Python + R RMarkdown example
---
title: "Minimal examples of polyglot Rmd"
author: "Henry Miller"
date: "3/2/2022"
output: html_document
---
## Minimal example of polyglot python + R in RMarkdown
First, we load the `iris` dataset using seaborn in **python**:
```{python}
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset('iris')
iris
```
Then, we plot this in **R**:
```{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")
```
### We can also do the *reverse*.
Load the `iris` dataset using `data()` in **R**
```{r}
data(iris)
head(iris)
```
Then, we plot this in **python**
```{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()
```
@millerh1
Copy link
Author

millerh1 commented Mar 3, 2022

The output is here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment