I'm developing a Django application where I'd like to be able to render a graph that updates when a user checks/unchecks checkbox inputs. I'm having trouble getting the data from the form to my server-side logic, and then rendering the plot (a histogram created via matplotlib) in the view.
The data comes from a SQL query in the sqlite database that comes prepackaged in Django. I have verified that the SQL query returns the correct data, and have a script that will create the correct histogram. However, since there are many different options for the user to click to generate the histogram, I'd like to not save each potential histogram as a static file to be served. Ideally, the histogram would update when the user toggles a checkbox.
I'm not opposed to using JavaScript/another plotting framework to render the histogram, however I'm not sure how I'd connect that to the database or to the view.
Any help would be greatly appreciated!
UPDATE WITH EXAMPLE
The checkboxes are options for the user to include/exclude in the histogram. Toggling them on and off will create a subset of the full dataset returned by the SQL query. Here's an example:
If there was a survey of preferred ice cream flavor and topping, the query return a dataframe like this (except with more flavors and toppings provided):
import pandas as pd
# Query from DB creates this via pd.read_sql_query(), but I'll just create by hand
df = pd.DataFrame({
'id': [1, 2, 3, 4, 5],
'flavor': ['chocolate', 'strawberry', 'vanilla', 'pineapple', 'chocolate'],
'topping': ['fudge', 'sprinkles', 'fruit', 'cookies', 'sprinkles']
})
The checkboxes create a subset of the checked ice cream flavors, and the histogram shows the distribution of preferred toppings. So if chocolate and strawberry are checked, we get:
sub = df[df['flavor'].isin(['chocolate', 'strawberry'])]
From sub
, I can calculate the percentage of responses for each topping. I have logic to handle this, so I'll just shortcut to the final
dataframe that will be used to make the histogram:
final = pd.DataFrame({
'topping': ['fudge', 'sprinkles'],
'pct_liked': [.333, .666]
})
Lastly, I plot the histogram:
import matplotlib.pyplot as plt
ax = final['pct_liked'].plot(
kind = 'bar',
title = f'Ice Cream Toppings by Chocolate and Strawberry Lovers',
width = 1.0
)
ax.figure
And this is the histogram that I want to display in my Django view. I've verified that this workflow in the script works properly.
The database where the responses would be stored is the sqlite database that comes with Django, but I'm unsure how to take the checkboxes for the flavors that the user clicks and pass them through this process, then how to take ax
and render it in the Django view.