General way of iterating over a dictionary containing multiple mpld3 graph images in Django?

54 Views Asked by At

I am working on a personal project. One part of this is to display multiple histograms on a webpage. So far, I have been able to get this to work using the following code:

views.py:

import pandas as pd
import matplotlib.pyplot as plt,mpld3
import scipy.stats as stats
import numpy as np

def histogram_plot(request):
    context={}
    df = pd.read_csv(test_file) #Read using pandas
    for column in df.columns:
                fig=plt.figure()
                plt.hist(df[column])
                histogram=mpld3.fig_to_html(fig)
                context[f"{column}Histogram"]=[histogram]
    
    return render(request,"base.html",context)

base.html:

{% for elem in PregnanciesHistogram %}
   {{elem|safe}}
{% endfor %}
{% for elem in GlucoseHistogram %}
   {{elem|safe}}
{% endfor %}
{% for elem in BloodPressureHistogram %}
   {{elem|safe}}
{% endfor %}
{% for elem in SkinThicknessHistogram %}
   {{elem|safe}}
{% endfor %}
{% for elem in InsulinHistogram %}
   {{elem|safe}}
{% endfor %}
{% for elem in BMIHistogram %}
   {{elem|safe}}
{% endfor %}
{% for elem in DiabetesPedigreeFunctionHistogram %}
   {{elem|safe}}
{% endfor %}
{% for elem in AgeHistogram %}
   {{elem|safe}}
{% endfor %}

I do see all the histograms on my webpage, but the problem is that all of the HTML code uses hardcoded keys in the dictionary.

Is there a general way of writing what I wrote in this HTML code, using a for loop, without hardcoding the keys from the dictionary? I would appreciate it if someone could tell me how to do that.

1

There are 1 best solutions below

8
Tarquinius On BEST ANSWER

Try this:

def histogram_plot(request):
    context={}
    df = pd.read_csv(test_file) #Read using pandas
    hist_list = []
    for column in df.columns:
                fig=plt.figure()
                plt.hist(df[column])
                histogram=mpld3.fig_to_html(fig)
                hist_list.append([histogram])
    context["hist_list"] = hist_list
    
    return render(request,"base.html",context)
{% for histogram in hist_list %}
   {% for elem in histogram %}
       {{  elem|safe  }}
   {% endfor %}
{% endfor %}

This simply appends all your histograms to a list and then loops over them in your template.