Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding a Plotly chart in a Django template

I am trying to embed a plotly pie chart in a Django html template. This works fine when the chart is produced in 'online mode' (i.e. the html snippet is stored on the plotly server) but not in 'offline mode' (i.e. when the html is stored locally). In the latter case, the chart does not appear. I want to be able to store the html on my local server and embed the plots from there.

Here is the bit that works:

import plotly.plotly as py import plotly.graph_objs as go labels = [1,2,3,4] values = [10,20,30,40] ndata = 100 fig = {     'data': [{'labels': labels,           'values': values,           'type': 'pie',           'textposition':"none",           'textinfo':"percent",           'textfont':{'size':'12'},           'showlegend':'false'}],     'layout': {'title': 'Total:'+str(ndata),            'showlegend':'false',            'height':'200',            'width':'200',            'autosize':'false',            'margin':{'t':'50','l':'75','r':'0','b':'10'},            'separators':'.,'} } plotly_url = py.plot(fig, filename='myfile', auto_open=False) pie_url = '<iframe width="200" height="200" frameborder="0" seamless="seamless" scrolling="no" src='+plotly_url+'.embed?width=200&height=200&link=false&showlegend=false></iframe>' 

Note that pie_url is passed as a string in the Http render request in Django. The template interprets the string as html using the | safe tag, i.e. {{ pie_url|safe }}.

Here is the bit that doesn't work:

from plotly.offline import download_plotlyjs, plot import plotly.graph_objs as go labels = [1,2,3,4] values = [10,20,30,40] ndata = 100 fig = {     'data': [{'labels': labels,           'values': values,           'type': 'pie',           'textposition':"none",           'textinfo':"percent",           'textfont':{'size':'12'},           'showlegend':'false'}],     'layout': {'title': 'Total:'+str(ndata),            'showlegend':'false',            'height':'200',            'width':'200',            'autosize':'false',            'margin':{'t':'50','l':'75','r':'0','b':'10'},            'separators':'.,'} } plotly_url = plot(fig, filename='file:///home/website/pie.html', auto_open=False) pie_url = '''<iframe width="200" height="200" frameborder="0" seamless="seamless" scrolling="no" src=\"'''+plotly_url+'''.embed?width=200&height=200&link=false&showlegend=false\"></iframe>''' 

Any advice would be appreciated.

like image 371
Hooloovoo Avatar asked Apr 25 '16 16:04

Hooloovoo


People also ask

Can I use plotly with Django?

Plotly is an extremely useful and sophisticated visualization library in Python. It provides not only simple plotting functions but also a bunch of advanced functions. Dash is a web framework for web applications that are based on plotly.

How do you insert a plotly graph?

To share a plot from the Chart Studio Workspace, click 'Share' button on the left-hand side after saving the plot. The Share modal will pop-up and display a link under the 'Embed' tab. You can then copy and paste this link to your website. You have the option of embedding your plot as an HTML snippet or iframe.

How do you plot a graph in Python using a website?

Three steps are required to integrate a Python graph into an HTML Web site: generate the graph either in Plot.ly or Altair. save the graph as an HTML page. manipulate the generated HTML.


1 Answers

Instead of writing the html to a file you can have plotly return the html part of the graph as a string. For example, using a class based TemplateView:

EDIT: Update for using recent (as of 2021/08) versions of plotly. The template does not need any changes.

import plotly.graph_objects as go  class Graph(TemplateView):     template_name = 'graph.html'      def get_context_data(self, **kwargs):         context = super(Graph, self).get_context_data(**kwargs)          x = [-2,0,4,6,7]         y = [q**2-q+3 for q in x]         trace1 = go.Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 104, 'size': "10"},                             mode="lines",  name='1st Trace')          layout=go.Layout(title="Meine Daten", xaxis={'title':'x1'}, yaxis={'title':'x2'})         figure=go.Figure(data=['trace1'],layout=layout)          context['graph'] = figure.to_html()          return context 

This is the original code:

import plotly.offline as opy import plotly.graph_objs as go  class Graph(TemplateView):     template_name = 'graph.html'      def get_context_data(self, **kwargs):         context = super(Graph, self).get_context_data(**kwargs)          x = [-2,0,4,6,7]         y = [q**2-q+3 for q in x]         trace1 = go.Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 104, 'size': "10"},                             mode="lines",  name='1st Trace')          data=go.Data([trace1])         layout=go.Layout(title="Meine Daten", xaxis={'title':'x1'}, yaxis={'title':'x2'})         figure=go.Figure(data=data,layout=layout)         div = opy.plot(figure, auto_open=False, output_type='div')          context['graph'] = div          return context 

and the template:

{% if graph %} <div style="width:600;height:500"> {{ graph|safe }} </div> {% endif %} 
like image 161
Christian K. Avatar answered Sep 22 '22 13:09

Christian K.