2

我准备了以下混合 Python 和 R 的 R Markdown 文档!代码:

---
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")
```

编译为:

我的 R 降价代码的编译版本

如您所见,我在代码块中重复了 FirstHist字符串 3 次。

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

4

0 回答 0