JohnB
JohnB

Reputation: 77

Django - how to best integrate matplotlib

I am trying to display a graph using matplotlib and django. I've read quite a lot of questions on stack but still don't understand what the best way is to use matplotlib in Django.

SITUATION:

I have a model that has a bunch of data in. In views.py I then have a simple form that captures some data and queries the model and returns a subset of the data. Here is the relevant views.py section:

def getinput(request):
     if request.method == 'POST':
         form = get_data(request.POST)

         if form.is_valid():
             down = form.cleaned_data['get_down']
             ytg = form.cleaned_data['get_ytg']
             yfog = form.cleaned_data['get_yfog']
             map_data = next_play.objects.filter(last_dwn__exact=down, last_yfog__exact=yfog, last_ytg__exact=ytg)
             context = {'form': form, 'query_data': map_data}
             return render(request, 'play_outcomes/output.html', context)
     else:
         form = get_data()


     return render(request, 'play_outcomes/getinput.html', {'form': form})

When I got to play_outcomes/getinput and enter dwn ytg yfog the template then outputs a whole ton of data.

It is this data I want to plot i.e., the data in map_data.

QUESTION:

How do I integrate matplotlib into this? Do I integrate the matplotlib code in views.py, should I set it up in a separate python module? Presumably I need to create a png file and then show that?

Upvotes: 2

Views: 477

Answers (1)

Giacomo Catenazzi
Giacomo Catenazzi

Reputation: 9533

A figure is a view, so view is a good place. On the other hand, matplot lib could be verbose, and you would like to set various constants, so that every figure look like with similar style. For such reason I would recommend to move all figure code in a new file.

In general, I avoid creating graphs in Django. Just a "off-line" batch, to create some statistic graphs, or I would try to use d3.js, to offload figure generation to clients (but so they receive the dataset). There are also some hybrid variants, which I never tried, e.g. http://subsetlab.com/super-fund-performance-and-fees.html (check the second part: "how to do it").

Upvotes: 2

Related Questions