Reputation: 21
I am attempting to display two plots in a Quarto document side by side. The issue is that one is generated through R and the other through Python. Ideally, I would like the plots to appear as they do in this document:
However, this seems to only work for images created by the same method (either both plots are created in R or both are created in Python). Here's the link where I got this example from: https://quarto.org/docs/get-started/computations/rstudio.html
Additionally, here is the code that I am using the create these plots:
R Plot:
```{r, fig.show = 'hold', out.width = '50%'}
#| label: fig-r
#| fig-cap: "Car Weight Vs. MPG Scatterplot (R)"
#| layout-ncol: 2
#| column: page
library(ggplot2)
# Color Scale
mtcars$pc <- predict(prcomp(~wt + mpg, mtcars))[,1]
# Scatter Plot
ggplot(mtcars, aes(wt, mpg, color = pc)) +
geom_point(shape = 16, size = 5, alpha = 0.4, show.legend = FALSE) +
theme_minimal() +
scale_color_gradient(low = "#0091ff", high = "#f0650e") +
xlab('Weight (1,000 lbs)') +
ylab('MPG') +
ggtitle('Weight Vs. MPG')
```
Python Plot:
```{python, fig.show = 'hold', out.width = '50%'}
#| label: fig-python
#| fig-cap: "Car Weight Vs. MPG Scatterplot (Python)"
#| layout-ncol: 2
#| column: page
import numpy as np
import pandas as pd
import seaborn as sns
import statsmodels.api as sm
mtcars = sm.datasets.get_rdataset('mtcars', 'datasets', cache = True).data
sns.scatterplot(x = "wt",
y = "mpg",
data = mtcars).set_title('Weight Vs. MPG')
sns.regplot(x = mtcars['wt'], y = mtcars['mpg'],
fit_reg = False)
```
Output:
Upvotes: 2
Views: 3180
Reputation: 20007
You can render a document with both R and python code with the knitr
engine specified, if you have the {reticulate}
R-package installed in your computer.
And to show plot (figures) side by side we can use pandoc figure divs with layout-ncol=2
.
---
title: "R and Python"
format: html
engine: knitr
---
::: {layout-ncol=2 .column-page}
```{r}
#| label: fig-r
#| fig-cap: "Car Weight Vs. MPG Scatterplot (R)"
#| echo: false
library(ggplot2)
# Color Scale
mtcars$pc <- predict(prcomp(~wt + mpg, mtcars))[,1]
# Scatter Plot
ggplot(mtcars, aes(wt, mpg, color = pc)) +
geom_point(shape = 16, size = 5, alpha = 0.4, show.legend = FALSE) +
theme_minimal() +
scale_color_gradient(low = "#0091ff", high = "#f0650e") +
xlab('Weight (1,000 lbs)') +
ylab('MPG') +
ggtitle('Weight Vs. MPG')
```
```{python}
#| label: fig-python
#| fig-cap: "Car Weight Vs. MPG Scatterplot (Python)"
#| echo: false
import numpy as np
import pandas as pd
import seaborn as sns
import statsmodels.api as sm
mtcars = sm.datasets.get_rdataset('mtcars', 'datasets', cache = True).data
sns.scatterplot(x = "wt",
y = "mpg",
data = mtcars).set_title('Weight Vs. MPG')
sns.regplot(x = mtcars['wt'], y = mtcars['mpg'],
fit_reg = False)
```
:::
Upvotes: 2