0

I'm attempting to embed a graph into a HTML page using Python Plotly and Pandas, in Linux. I found this answer from user @Fermin Silva, which suggests using plotly.offline.plot to convert a plotly graph into a object. This can then be embedded directly in a HTML.

So here's what I tried:

  1 import pandas as pd
  2 import plotly.graph_objs as go
  3 from plotly import tools
  4 import plotly
  5 import plotly.express as px
  6 
  7 data = {'Weekday': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
  8         'Val': [4, 5, 9, 14, 26, 6, 14]}
  9 
 10 df = pd.DataFrame(data)
 11 
 12 fig1 = px.line(df, x='Weekday', y='Val')
 13 div = plotly.offline.plot(fig1, include_plotlyjs=False, output_type='div')  
 14 
 15 title = 'Example graph'
 16 
 17 html = '<html><head><title>{0}</title></head><body>{1}</body></html>'.format(title, div)
 18  
 19 with open('test3.html', 'w') as fw:
 20     fw.write(html)

When I run this script, it executes fully and creates the test3.html file, with the following contents:

<html>
      <head>
            <title>Example graph</title>
      </head>
      <body>
            <div>
        
        
            <div id="0e557daa-24ae-4b6f-865a-dbc84f6ede5c" class="plotly-graph-div" style="height:600px; width:100%;"></div>
            <script type="text/javascript">
                
                    window.PLOTLYENV=window.PLOTLYENV || {};
                    
                if (document.getElementById("0e557daa-24ae-4b6f-865a-dbc84f6ede5c")) {
                    Plotly.newPlot(
                        '0e557daa-24ae-4b6f-865a-dbc84f6ede5c',
                        [{"hoverlabel": {"namelength": 0}, "hovertemplate": "Weekday=%{x}<br>Val=%{y}", "legendgroup": "", "line": {"color": "#636efa", "dash": "solid"}, "mode": "lines", "name": "", "showlegend": false, "type": "scatter", "x": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], "xaxis": "x", "y": [4, 5, 9, 14, 26, 6, 14], "yaxis": "y"}],
                        {"height": 600, "legend": {"tracegroupgap": 0}, "margin": {"t": 60}, "template": {"data": {"bar": [{"error_x": {"color": "#2a3f5f"}, "error_y": {"color": "#2a3f5f"}, "marker": {"line": {"color": "#E5ECF6", "width": 0.5}}, "type": "bar"}], "barpolar": [{"marker": {"line": {"color": "#E5ECF6", "width": 0.5}}, "type": "barpolar"}], "carpet": [{"aaxis": {"endlinecolor": "#2a3f5f", "gridcolor": "white", "linecolor": "white", "minorgridcolor": "white", "startlinecolor": "#2a3f5f"}, "baxis": {"endlinecolor": "#2a3f5f", "gridcolor": "white", "linecolor": "white", "minorgridcolor": "white", "startlinecolor": "#2a3f5f"}, "type": "carpet"}], "choropleth": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "type": "choropleth"}], "contour": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "contour"}], "contourcarpet": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "type": "contourcarpet"}], "heatmap": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "heatmap"}], "heatmapgl": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "heatmapgl"}], "histogram": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "histogram"}], "histogram2d": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "histogram2d"}], "histogram2dcontour": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "histogram2dcontour"}], "mesh3d": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "type": "mesh3d"}], "parcoords": [{"line": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "parcoords"}], "scatter": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatter"}], "scatter3d": [{"line": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatter3d"}], "scattercarpet": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattercarpet"}], "scattergeo": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattergeo"}], "scattergl": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattergl"}], "scattermapbox": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattermapbox"}], "scatterpolar": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatterpolar"}], "scatterpolargl": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatterpolargl"}], "scatterternary": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatterternary"}], "surface": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "surface"}], "table": [{"cells": {"fill": {"color": "#EBF0F8"}, "line": {"color": "white"}}, "header": {"fill": {"color": "#C8D4E3"}, "line": {"color": "white"}}, "type": "table"}]}, "layout": {"annotationdefaults": {"arrowcolor": "#2a3f5f", "arrowhead": 0, "arrowwidth": 1}, "colorscale": {"diverging": [[0, "#8e0152"], [0.1, "#c51b7d"], [0.2, "#de77ae"], [0.3, "#f1b6da"], [0.4, "#fde0ef"], [0.5, "#f7f7f7"], [0.6, "#e6f5d0"], [0.7, "#b8e186"], [0.8, "#7fbc41"], [0.9, "#4d9221"], [1, "#276419"]], "sequential": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "sequentialminus": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]]}, "colorway": ["#636efa", "#EF553B", "#00cc96", "#ab63fa", "#FFA15A", "#19d3f3", "#FF6692", "#B6E880", "#FF97FF", "#FECB52"], "font": {"color": "#2a3f5f"}, "geo": {"bgcolor": "white", "lakecolor": "white", "landcolor": "#E5ECF6", "showlakes": true, "showland": true, "subunitcolor": "white"}, "hoverlabel": {"align": "left"}, "hovermode": "closest", "mapbox": {"style": "light"}, "paper_bgcolor": "white", "plot_bgcolor": "#E5ECF6", "polar": {"angularaxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}, "bgcolor": "#E5ECF6", "radialaxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}}, "scene": {"xaxis": {"backgroundcolor": "#E5ECF6", "gridcolor": "white", "gridwidth": 2, "linecolor": "white", "showbackground": true, "ticks": "", "zerolinecolor": "white"}, "yaxis": {"backgroundcolor": "#E5ECF6", "gridcolor": "white", "gridwidth": 2, "linecolor": "white", "showbackground": true, "ticks": "", "zerolinecolor": "white"}, "zaxis": {"backgroundcolor": "#E5ECF6", "gridcolor": "white", "gridwidth": 2, "linecolor": "white", "showbackground": true, "ticks": "", "zerolinecolor": "white"}}, "shapedefaults": {"line": {"color": "#2a3f5f"}}, "ternary": {"aaxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}, "baxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}, "bgcolor": "#E5ECF6", "caxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}}, "title": {"x": 0.05}, "xaxis": {"automargin": true, "gridcolor": "white", "linecolor": "white", "ticks": "", "zerolinecolor": "white", "zerolinewidth": 2}, "yaxis": {"automargin": true, "gridcolor": "white", "linecolor": "white", "ticks": "", "zerolinecolor": "white", "zerolinewidth": 2}}}, "xaxis": {"anchor": "y", "domain": [0.0, 0.98], "title": {"text": "Weekday"}}, "yaxis": {"anchor": "x", "domain": [0.0, 1.0], "title": {"text": "Val"}}},
                        {"responsive": true}
                    )
                };
                
            </script>
            </div>
       </body>
</html>

I try running this in Firefox using firefox test3.html, and no graph appears. I know that the block is there, because it appears when I "Inspect element". But it's not rendering a Plotly graph:

enter image description here

I've tried opening the file in Chrome in Windows, and it's the same result.

In Fermin Silva's answer, they mentioned

Remember that you'll need to include the plotly js file for all these charts to work.

You could include

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

just before putting the div you got. If you put this js at the bottom of the page, the charts won't work.

Honestly, I don't really understand this - I don't know what is meant by the plotly js file, nor whether this applies to my setup. Nonetheless, I tried inserting this snippet before the outer tag in my HTML file, and then I tried inserting it before the inner tag, like so:

Attempt 1:

  1 <html><head><title>Example graph</title></head><body>    
  2  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>                   
  3         <div>
  4 
  5 
  6             <div id="0e557daa-24ae-4b6f-865a-dbc84f6ede5c" class="plotly-gra    ph-div" style="height:600px; width:100%;"></div>

Attempt 2:

  1 <html><head><title>Example graph</title></head><body>                       
  2         <div>
  3  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
  4 
  5 
  6             <div id="0e557daa-24ae-4b6f-865a-dbc84f6ede5c" class="plotly-gra    ph-div" style="height:600px; width:100%;"></div>

And the graph still doesn't display.

I would appreciate anyone taking the time to explain what I'm doing wrong, and how I can correctly output a Plotly graph into a HTML file, so that it displays on a local webpage.

EDIT: So, a temporary workaround that I've found is to use fig1.write_html(filename, auto_open=False) to create a whole HTML file, then load that HTML file into BeautifulSoup and insert HTML as appropriate. I don't like it, because it means I'm effectively building a page around a graph, rather than the reverse, but it at least achieves my aim of getting a graph on a webpage.

If anyone knows how to fix the div insert, that would be great.

Lou
  • 2,200
  • 2
  • 33
  • 66
  • I don't see `Plotly` defined in the generated JavaScript. Is it loaded somewhere on the page? I see it in your 2nd attempt but it would be better to put it in the ``. – Alex W Oct 12 '20 at 15:30
  • I'm not sure what you mean by this to be honest. Where would you expect Plotly to be mentioned in the JavaScript? – Lou Oct 12 '20 at 15:32
  • It's being defined in the script that you're loading in the 2nd attempt from the CDN but you should move that `` block to be in the `` (more info [here](https://stackoverflow.com/questions/38407962/when-to-use-the-script-tag-in-the-head-and-body-section-of-a-html-page/38408000)) – Alex W Oct 12 '20 at 15:38
  • So I've tried moving the script portion to the head as you suggest, but it's still not displaying the graph unfortunately. I'm not sure why it works when I use `write_html`, but not when I just grab a `div` and put it into a html file myself. – Lou Oct 12 '20 at 15:52
  • Okay that's interesting. I've just realised that it works in Chrome and Internet Explorer on Windows, but not in Firefox on Linux. I'm running Linux in a VM on Windows. – Lou Oct 12 '20 at 16:12
  • This parameter in your Python code: `include_plotlyjs=False` if set to `True` would likely prevent you from needing to use the CDN script at all – Alex W Oct 12 '20 at 16:19
  • Ah! That worked! It's working both in Windows and in the Linux VM. Thanks :) – Lou Oct 12 '20 at 16:22
  • in your attempts, besides adding the `
    {0}{1}
    – Fermin Silva Oct 12 '20 at 18:15
  • @FerminSilva, I'm not too sure what you mean by this. Using the code from your answer, I've added everything which is fed into the `div` variable in the line `div = plotly.offline.plot(fig1, include_plotlyjs=False, output_type='div')`, into the HTML file. I've tried setting include_plotlyjs to True as Alex W suggested, and that does work, although it leads to a very verbose and lengthy HTML file. I haven't managed to make it work when include_plotlyjs is False. – Lou Oct 14 '20 at 15:59
  • Did you try something like this? `html = '{0}{1}'.format(title, div)` – Fermin Silva Oct 19 '20 at 13:16
  • So I tried this again, and for some reason now it works when I change the div line to `div = plotly.offline.plot(fig1, include_plotlyjs="cdn", output_type='div')`. Before, it was outputting a blank graph. Maybe I forgot the double quotes? Either way, my problem appears to be solved! – Lou Oct 19 '20 at 14:30
  • ...Okay, I tried this again the next day, and now it doesn't work again, even with the code unchanged. I tried creating a new file and inserting a basic graph into a different HTML page. It now only works in Windows Chrome, not Linux Firefox. – Lou Oct 20 '20 at 13:37

3 Answers3

0

Use Graph Objects.

import pandas as pd
import numpy as np
import chart_studio.plotly as py
import cufflinks as cf
import seaborn as sns
import plotly.express as px

import plotly.graph_objects as go

scoresByTeamId = {1: [100, 110, 115, 95, 112, 120, 110, 99], 2: [115, 99, 75, 111, 120, 77, 80, 110], 3: [100, 105, 102, 115, 99, 99, 100, 134]}
teamNamesByTeamId = {1: "John", 2: "Pete", 3: "Edgar"}
df_scores = pd.DataFrame(data=scoresByTeamId)

fig = go.Figure()

for team in scoresByTeamId:
    fig.add_trace(go.Scatter(x=[1,2,3,4,5,6,7,8],
                            y=scoresByTeamId[team],
                            name=teamNamesByTeamId[team],
                            mode="lines+markers"))

fig.update_layout(
    xaxis=dict(title="Week",
                tickvals=[1,2,3,4,5,6,7,8]),
    yaxis=dict(title="Points Scored"),
    title="PPG by Week"
)

fig.show() # this is just to see it in browser in case you want to, it isn't necessary.
html = fig.to_html(full_html=True, include_plotlyjs=True)
print(html)

# save html file
filePath="C:\\myFilePath\\myHtmlFile.html"
with open(filePath, "w") as f:
    f.write(html)
joeyagreco
  • 98
  • 2
  • 11
0

try this: from

include_plotlyjs=False

to

include_plotlyjs=True
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 26 '22 at 09:21
0

You can use

html_div = fig.to_html(full_html=False, include_plotlyjs= False )

to get a html div. You must iclude plotlyjs somewhere but

Error404
  • 84
  • 7