在Rmarkdown中调用Python代码

Myosotics 2023-10-19 {Coding} [R Markdown, Python, R]

Rmarkdown中调用Python代码块需要用到reticulate

install.packages("reticulate")

在我们运行python代码块之前首先需要设置好Python环境。下面我们需要指定Python路径, 在命令窗口输入where pythonpython的路径 接下来在R中指定Pyrhon路径

library(reticulate)
use_python('E:/software/Program Files/python3.11.0')

最后即可在Rmarkdown中运行python代码块了

import numpy as np
import matplotlib.pyplot as plt
# 计算正弦曲线上的 x 和 y 坐标
x = np.arange(0, 3*np.pi, 0.1)
y = np.sin(x)
plt.title('sine wave form')
# 使用 matplotlib 来绘制点
plt.plot(x, y)
plt.show()