用Python和R中的chunk进行标记是否有可能使用共享变量?

2024-06-17 10:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我准备了下面的R markdown文档,它混合了Python和R!代码:

---
title: "Sample document"
abstract: "This is a sample abstract."
author: "Mateusz Kędzior"
output: 
  bookdown::pdf_document2:
    keep_tex: true
---

## Sample Text

I wish to show Python histogram (Fig. \@ref(fig:FirstHist)) in my .tex

```{python, echo=FALSE}
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

w = np.random.randn(50, 4)
plt.hist(w, facecolor='green')

# Now I wish to include histogram in the generated document, so I've tried:
# plt.show()
# Unfortunately it shows shortly a window with histogram and waits until I close it.
# I think there's no such possibility, so I save it to file and then inserts in R code chunk:
plt.savefig('FirstHist.png', bbox_inches='tight')
```

```{r FirstHist, echo=FALSE, fig.align="center", out.width = ".8\\linewidth", fig.cap="Histogram of w"}
knitr::include_graphics("FirstHist.png")
```

其编译为:

compiled version of my R markdown code

如您所见,我在代码块中重复FirstHiststring三次。在

我想知道是否有重构的可能性-使用一个共享(在所有块之间)变量?在


Tags: tosample代码inimportabstractasfig