首页 > 解决方案 > 使用 jupyter notebook 在 markdown 中导出 Plotly Graph

问题描述

我想在 Markdown 中导出带有绘图图表的笔记本以将其放在我的博客上,但是当我在我的网站上打开帖子时,图表没有显示。

我没有使用 javascript 的经验,但我可以在与这些图相关的 markdown 文件 HTML 代码中看到,这是一个示例:

<div id="52c4552b-3ced-4862-859b-5db04f4d3c5a" style="height: 500px; width: 1000px;" class="plotly-graph-div"></div><script type="text/javascript">require(["plotly"], function(Plotly) { window.PLOTLYENV=window.PLOTLYENV || 
{};window.PLOTLYENV.BASE_URL="https://plot.ly";Plotly.newPlot("52c4552b-3ced-4862-859b-5db04f4d3c5a", [{"type": "area", "r": [6409, 6019, 7254, 7226, 7625, 8353, 7271, 5100, 8178, 8833, 8123, 7091], "t": ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"], "name": "Total Number of accidents", "marker": {"color": "rgb(106,81,163)"}}, {"type": "area", "r": [697, 602, 761, 786, 794, 839, 714, 565, 802, 813, 802, 729], "t": ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"], "name": "Grave accidents", "marker": {"color": "rgb(158,154,200)"}}], {"title": "Repartition of accidents per Hour", "autosize": false, "width": 1000, "height": 500, "orientation": -90}, {"showLink": true, "linkText": "Export to plot.ly"})});</script>

那么我应该怎么做才能使图表正确显示?谢谢 !

标签: jupyter-notebookmarkdownplotlyjupyter

解决方案


我想,你错过的是添加包含的脚本标签,你可以在这里plotly.js阅读更多。因此,您需要做的是包括以下行。

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

另外,我假设您正在使用plotly.offline您的绘图,因此您需要像这样将绘图转换为 html。

import pandas as pd
import numpy as np
import plotly.offline as py_offline
import plotly.graph_objs as go
py_offline.init_notebook_mode()

N = 10
random_x = np.linspace(0, 1, N)
random_y = np.random.randn(N)

trace = go.Scatter(
    x = random_x,
    y = random_y
)

data = [trace]

py_offline.plot(data, filename='basic-line', include_plotlyjs=False, output_type='div')

上面这个话题详细讨论了->SO Answer

因此,有了这个,您将获得绘图 html 作为字符串。

注意:您总是应该只有一个plotly.js,您可以设置include_plotlyjstrue不包含上述脚本标签,或者设置为false并使用脚本标签,但请注意,您需要始终只有一个 plotly.js 文件存在。

因此,您需要粘贴到博客中的最​​终内容将是。

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<div id="22495cec-ac95-42d5-b3b1-4566a5848585" style="height: 100%; width: 100%;" class="plotly-graph-div"></div><script type="text/javascript">window.PLOTLYENV=window.PLOTLYENV || {};window.PLOTLYENV.BASE_URL="https://plot.ly";Plotly.newPlot("22495cec-ac95-42d5-b3b1-4566a5848585", [{"type": "scatter", "x": [0.0, 0.1111111111111111, 0.2222222222222222, 0.3333333333333333, 0.4444444444444444, 0.5555555555555556, 0.6666666666666666, 0.7777777777777777, 0.8888888888888888, 1.0], "y": [-0.2706323284096669, -0.5368085060076518, -0.3650022122835297, 1.0837185699917664, -1.6123886503326845, 1.3256691068338189, -0.31083903066205104, 0.6951190301897303, -1.624361384686101, 1.852523980751262]}], {}, {"showLink": true, "linkText": "Export to plot.ly"})</script>

如果您的问题得到解决,请告诉我!


推荐阅读