Python Plotly - 嵌入HTML的离线图表(不工作)

Sco*_*tEU 15 html python plotly

我已经构建了一个图表,我想将其嵌入到HTML文件中.如果我plotly在线使用,它可以按预期工作.但是,如果我使用OFFLINE离线图表工作(即它打开一个单独的HTML图表),但它没有嵌入HTML(nick.html),iframe即为空.

这是我的代码:

fig = dict(data=data, layout=layout)
plotly.tools.set_credentials_file(username='*****', api_key='*****')
aPlot = plotly.offline.plot(fig, config={"displayModeBar": False}, show_link=False,
                             filename='pandas-continuous-error-bars.html')

html_string = '''
<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <style>body{ margin:0 100; background:whitesmoke; }</style>
    </head>
    <body>
        <h1>Monthly Report</h1>

        <!-- *** Section 1 *** --->
        <h2></h2>
        <iframe width="1000" height="550" frameborder="0" seamless="seamless" scrolling="no" \
src="''' + aPlot + '''.embed?width=800&height=550"></iframe>
        <p> (Insights).</p>


    </body>
</html>'''

f = open("C:/Users/nicholas\Desktop/nick.html",'w')
f.write(html_string)
f.close()
Run Code Online (Sandbox Code Playgroud)

任何人都知道它为什么不嵌入以及如何修复它?

Max*_*ers 15

aPlot 是Plotly文件的文件名.

iframe你的添加.embed?width=800&height=550到文件名,导致文件名不存在.

当你删除这个字符串,即src="''' + aPlot + '''"它应该工作.

您可以使用此处建议的方法生成较小的HTML文件,即生成div包含所有相关信息并包含plotly.js在标题中的方法,而不是嵌入整个HTML文件.

import plotly

fig = {'data': [{'x': [1,2,3],
                  'y': [2,5,3],
                  'type': 'bar'}],
      'layout': {'width': 800,
                 'height': 550}}

aPlot = plotly.offline.plot(fig, 
                            config={"displayModeBar": False}, 
                            show_link=False, 
                            include_plotlyjs=False, 
                            output_type='div')

html_string = '''
<html>
    <head>
      <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
      <style>body{ margin:0 100; background:whitesmoke; }</style>
    </head>
    <body>
      <h1>Monthly Report</h1>
      ''' + aPlot + '''
    </body>
</html>'''

with open("nick.html", 'w') as f:
    f.write(html_string)
Run Code Online (Sandbox Code Playgroud)

  • 嘿,谢谢。我只是登机,所以无法检查它是否有效,但是逻辑看起来不错,我理解,所以非常感谢:) (2认同)