在 RMarkdown html 文档中显示 python 绘图图

Display python plotly graph in RMarkdown html document(在 RMarkdown html 文档中显示 python 绘图图)
本文介绍了在 RMarkdown html 文档中显示 python 绘图图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why plotly package of python can not display figure in RMarkdown but matplotlib can? For example:

 ```{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代码显示不出来,代码有什么问题?

The R code can work well, but the python code can not dispay the figure, what is wrong with the code?

推荐答案

这是我所做的:

  1. 离线使用:
    • import plotly.plotly as py 替换为 import plotly.offline as py
    • 离线模式下无需设置用户名和api key.
  • py.iplot() 用于 Jupyter 笔记本(它将绘图直接嵌入到笔记本中)
  • auto_open = False 参数是为了避免情节弹出.
  • py.iplot() is for Jupyter notebooks (it embeds the plot directly into the Notebook)
  • auto_open = False argument is to avoid that the plot pops up.

使用以下代码将 html 图嵌入到 Rmarkdown 中:

embedded the html plot into the Rmarkdown by using the following:

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

结果如下:

这篇关于在 RMarkdown html 文档中显示 python 绘图图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)