[Fixed]-How to create charts with Plotly on Django?

13πŸ‘

βœ…

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,})
πŸ‘€samcheuk

3πŸ‘

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")));
});
πŸ‘€Naren Murali

Leave a comment