在R Markdown文档中用Python代码绘制matplotlib图形 [英] Graphing matplotlib with Python code in a R Markdown document
本文介绍了在R Markdown文档中用Python代码绘制matplotlib图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用Python matplotlib代码在RStudio中绘制图形?
Is it possible to use Python matplotlib code to draw graph in RStudio?
例如下面的Python matplotlib代码:
e.g. below Python matplotlib code:
import numpy as np
import matplotlib.pyplot as plt
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
plt.plot (X, Y+1, color='blue', alpha=1.00)
plt.plot (X, Y-1, color='blue', alpha=1.00)
plt.show()
输出图将是:
然后,我需要编写一个R Markdown来包含这些代码,并在编织完Markdown之后自动生成图形.
Then I need to write a R Markdown to include these code and generate graph automatically after knitting the markdown.
推荐答案
一种可能的解决方案是将绘图另存为图像,然后将文件加载到markdown.
One possible solution is save the plot as a image, then load the file to markdown.
### Call python code sample
```{r,engine='python'}
import numpy as np
import matplotlib.pyplot as plt
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
fig, ax = plt.subplots( nrows=1, ncols=1 )
ax.plot (X, Y+1, color='blue', alpha=1.00)
ax.plot (X, Y-1, color='blue', alpha=1.00)
#plt.show()
fig.savefig('foo.png', bbox_inches='tight')
print "finished"
```
Output image:
![output](foo.png)
#### The End
输出:
这篇关于在R Markdown文档中用Python代码绘制matplotlib图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文