显示 R Markdown 中的 Seaborn 图(flexdashboard)

Showing Seaborn Plots from R Markdown (flexdashboard)

我想知道是否有人对使用 {reticulate} 在 R Markdown 中显示 Seaborn Python 图有任何见解。

为了重现性,这里有一个来自这篇文章的例子:https://towardsdatascience.com/python-seaborn-plots-in-r-using-reticulate-fb59cebf61a7

设置:

library(reticulate)
#importing required Python libraries/modules
sns <- import('seaborn')
plt <- import('matplotlib.pyplot')
pd <- import('pandas')

图表:

#using R's inbuilt AirPassengers dataset
df <- datasets::AirPassengers
#converting Time-Series object into an R Dataframe 
#Thx: 
df1 <- data.frame(tapply(df, list(year = floor(time(df)), month = month.abb[cycle(df)]), c))
df1 <- df1[month.abb]
#building a heatmap using seaborn 
#please note the function r_to_py() that converts R object into a python 
sns$heatmap(r_to_py(df1), fmt="g", cmap ='viridis')
#display the plot
plt$show()

这在 RStudio Plots 窗格中按预期显示:

但是在编写 .Rmd 文件 (flexdashboard) 时会生成相同的图,它会弹出一个查看器,在我关闭它后,报告会以这种方式呈现:

Flexdashboard 代码(代码块上的两个反引号而不是 3 个用于格式化):

---
title: "Untitled"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

``{r setup, include=FALSE}
library(reticulate)
#importing required Python libraries/modules
sns <- import('seaborn')
plt <- import('matplotlib.pyplot')
pd <- import('pandas')
``

Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

``{r}
#using R's inbuilt AirPassengers dataset
df <- datasets::AirPassengers
#converting Time-Series object into an R Dataframe 
#Thx: 
df1 <- data.frame(tapply(df, list(year = floor(time(df)), month = month.abb[cycle(df)]), c))
df1 <- df1[month.abb]
#building a heatmap using seaborn 
#please note the function r_to_py() that converts R object into a python 
sns$heatmap(r_to_py(df1), fmt="g", cmap ='viridis')
#display the plot
plt$show()
``

关于如何在此处的 flexdashboard 中显示 seaborn 情节有什么想法吗?

避免显示情节,将seaborn情节保存到文件中,然后使用Markdown查看。有点难看,但它有效。

```{r}
#using R's inbuilt AirPassengers dataset
df <- datasets::AirPassengers
#converting Time-Series object into an R Dataframe 
#Thx: 
df1 <- data.frame(tapply(df, list(year = floor(time(df)), month = month.abb[cycle(df)]), c))
df1 <- df1[month.abb]
#building a heatmap using seaborn 
#please note the function r_to_py() that converts R object into a python 
# assign the result of the heatmap to a variable so it doesn't get shown
ss <- sns$heatmap(r_to_py(df1), fmt="g", cmap ='viridis')
#save the plot
plt$savefig('passenger_heatmap.png')
# Avoid the pop up by not showing the plot
#plt$show()
```

![heatmap](passenger_heatmap.png)