关于Python Plotly:Python Plotly-脱机图表已嵌入HTML(无效)

Python Plotly - Offline chart embed into HTML (Not working)

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

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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>
        Monthly Report

        <!-- *** Section 1 *** --->
       
        <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()

有谁知道为什么不嵌入以及如何修复它?


aPlot是Plotly文件的文件名。

iframe中,将.embed?width=800&height=550添加到文件名,这将导致文件名不存在。

当您删除此字符串(即src="''' + aPlot + '''")时,它应该可以工作。

除了嵌入整个HTML文件之外,您还可以使用此处建议的方法,该方法将生成一个较小的HTML文件,即,生成包含所有相关信息的div并在标头中包含plotly.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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">
      <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>
      Monthly Report
      '''
+ aPlot + '''
    </body>
</html>'''


with open("nick.html", 'w') as f:
    f.write(html_string)