Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create charts with Plotly on Django?

I am trying to create a dashboard where I can analyse my model's data (Article) using the library plotly.

The Plotly bar chart is not showing on my template, I am wondering if I am doing something wrong since there's no error with the code below :

models.py

from django.db import models
from django.contrib.auth.models import User
import plotly.plotly as py
import plotly.graph_objs as go

class Article(models.Model):
    user = models.ForeignKey(User, default='1')
    titre = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=40)
    likes = models.ManyToManyField(User, related_name="likes")

    def __str__(self):
        return self.titre

    @property
    def article_chart(self):
        data = [
            go.Bar(
                x=[self.titre], #title of the article
                y=[self.likes.count()] #number of likes on an article
            )
        ]
        plot_url = py.plot(data, filename='basic-bar')

        return plot_url

dashboard.html

<div>{{ article.article_chart }}</div>

Why is the bar chart not visible? Any suggestion ?

like image 401
Hiroyuki Nuri Avatar asked Jan 29 '16 19:01

Hiroyuki Nuri


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.


2 Answers

The result of

py.plot(data, filename='basic-bar')

is to generate a offline HTML file and return a local URL of this file

e.g. file:///your_project_pwd/temp-plot.html

If you want to render it in Django framework, you need to

  • use <iframe> and restructure of your folder in Django settings

OR

  • use plotly.offline method to generate the HTML code with your input data

There is a example which I had tried:

figure_or_data = [Scatter(x=[1, 2, 3], y=[3, 1, 6])]

plot_html = plot_html, plotdivid, width, height = _plot_html(
    figure_or_data, True, 'test', True,
    '100%', '100%')

resize_script = ''
if width == '100%' or height == '100%':
    resize_script = (
        ''
        '<script type="text/javascript">'
        'window.removeEventListener("resize");'
        'window.addEventListener("resize", function(){{'
        'Plotly.Plots.resize(document.getElementById("{id}"));}});'
        '</script>'
    ).format(id=plotdivid)

html = ''.join([
            plot_html,
            resize_script])

return render(request, 'dashboard.html', {'html': html,})
like image 135
samcheuk Avatar answered Sep 28 '22 10:09

samcheuk


The above answer was very useful, I am in fact watching for parent resize, I am working in angular and I used the below code to achieve the resize, I am having a similar problem and this line of code was useful

<div class="col-lg-12" ng-if="showME" style="padding:0px">
   <div id="graphPlot" ng-bind-html="myHTML"></div>
</div>

The graph will be inserted through the variable myHTML

All i did was watch for the parent resize and got the div id alone using jquery and passed it to plotly and it worked.

$scope.$on("angular-resizable.resizeEnd", function (event, args){
        Plotly.Plots.resize(document.getElementById($('#graphPlot').children().eq(0).attr("id")));
});
like image 21
Naren Murali Avatar answered Sep 28 '22 11:09

Naren Murali