python - 在 RMarkdown html 文档中显示 python plotly 图形

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

R代码可以正常运行,但是python代码不能显示数字,代码有什么问题吗?

最佳答案

这是我做的:

  1. 离线使用:
    • import plotly.plotly as py 替换为 import plotly.offline as py
    • 无需在离线模式下设置用户名和api key 。
  2. 使用 py.plot(fig, filename = "styled-scatter.html", auto_open=False):
    • py.iplot() 适用于 Jupyter notebook(它将绘图直接嵌入到 Notebook 中)
    • auto_open = False 参数是为了避免弹出 plotly 。
  3. 使用以下代码将 html 图嵌入到 Rmarkdown 中:

    ```{r, echo=FALSE}
    htmltools::includeHTML("styled-scatter.html")
    ```
    

    结果如下: enter image description here

关于python - 在 RMarkdown html 文档中显示 python plotly 图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50191208/

相关文章:

python - __name__ ==“__main__”怎么办?

python - 对行进行分组、排序并删除冗余

r - 根据另一列中的匹配复制值

r - Rstudio loadNamespace(name)中的Rstudio编织pdf:没有名为'rmarkdown'的软件包

r - R markdown和MikTex不同步

r - 在 RMarkdown 中使用 LaTeX 动画包

python - 参数比例及数学表达式

Python time.clock() 结果不精确并且偏离

r - 从 R 调用 Prolog

r - 使用 predictNLS 在 R 中的拟合值周围创建置信区间?