在RMarkdown html文档中显示python可绘制图形

lit*_*ely 4 python r r-markdown plotly

为什么python的plotly包不能在RMarkdown中显示图,而matplotlib可以显示图?例如:

 ```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
```

```{r}
library(plotly)
subplot(
     plot_ly(mpg, x = ~cty, y = ~hwy, name = 'default'),
     plot_ly(mpg, x = ~cty, y = ~hwy) %>%
         add_markers(alpha = 0.2, name = 'alpha'),
     plot_ly(mpg, x = ~cty, y = ~hwy) %>%
         add_markers(symbols = I(1), name = 'hollow')
 )
```

```{python}
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np

plotly.tools.set_credentials_file(username='xxx', api_key='xxx')

N = 500
trace0 = go.Scatter(x = np.random.randn(N), y = np.random.randn(N) + 2, name = "Above", mode = "markers",
marker = dict(size = 10, color = "rgba(152, 0, 0, .8)", line = dict(width = 2, color = "rgb(0,0,0)")))

trace1 = go.Scatter(x = np.random.randn(N), y = np.random.randn(N) - 2, name = "below", mode = "markers",
marker = dict(size = 10, color = "rgba(255, 182, 193, .9)", line = dict(width = 2, color = "rgb(0,0,0)")))

data = [trace0, trace1]
layout = dict(title = "Styled Scatter", yaxis = dict(zeroline = False), xaxis = dict(zeroline=False))
fig = dict(data = data, layout = layout)
py.iplot(fig, filename = "styled-scatter")
```
Run Code Online (Sandbox Code Playgroud)

R代码可以很好地工作,但是python代码无法解决这个问题,代码有什么问题?

byo*_*ess 5

这是我所做的:

  1. 离线使用
    • 替换import plotly.plotly as py为import plotly.offline as py
    • 无需在离线模式下设置用户名和api键。
  2. 用过的py.plot(fig, filename = "styled-scatter.html", auto_open=False):
    • py.iplot() 适用于Jupyter笔记本(它将情节直接嵌入到Notebook中)
    • auto_open = False 争论是避免情节弹出。
  3. 使用以下命令将html图形嵌入到Rmarkdown中:

    ```{r, echo=FALSE}
    htmltools::includeHTML("styled-scatter.html")
    ```
    
    Run Code Online (Sandbox Code Playgroud)

    结果如下: 在此处输入图片说明