Easily plot graphs in your website using Plotly + Python
For the last few days I have been scratching my head. How do you plot all the data in your django website, without having to figure out D3 or any other complicated graphing libraries?
I've looked at several solutions, including Djangos Graphos, Chartit, NVD3… Everyone online seems to be recommending to use charting libraries off of this list: https://djangopackages.org/grids/g/charts/
It's frustrating to try many solutions to find out that they are all too complicated to understand, and the copy+paste approach doesn't work most of the time.
Today I will show you how absolutely easy it is to plot graphs in Django using Plotly's Python API. We are going to make a simple interactive plot that looks like this:
To get a simple graph up and rendering in plotly is easy, just 8 lines of code:
from plotly.offline import plot
plt_div holds all the HTML needed to render the plot!
How easy was that?
If you want to quickly see your plot rendering in a web browser, paste the contents of
plt_div into an HTML file like so, and then open your HTML file with your browser.
Here is an example Django view and template to display this plot:
from django.shortcuts import render
The above code renders this:
Go ahead and click around on the plot, it’s fully responsive.
plotly.js in the source-code of my blog.
plot_div. This makes it simple to get plotly working on the web, since there are no dependancies, however the plots will load faster if you instead manually include
This is the change to
plot() that you will need to make:
plt_div = plot(fig, output_type='div', include_plotlyjs=False)
This is the change to the HTML you will need to make:
If you don’t want the link to the plotly website on your graph, you can turn it off with including these options:
plot_div = plot(... , show_link=False, link_text="")
Plotly is the only graphing library I know of that works the same in Python as it does on the web, meaning I don’t need to make any transformations of the data from a python format to generate the plots. This made it extremely easy for me to get started right away developing visuals for a project I'm working on.
Checkout https://plot.ly for more information on how to make different kinds of plots.
As always, any questions you have leave them in the comments below. I'd be glad to help, and maybe see what kind of projects you are working on.