1

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.

  • In case you are not happy and not depended on the graph being interactive: [This](https://matplotlib.org/stable/gallery/user_interfaces/web_application_server_sgskip.html) is another method to integrate static plots as png or svg to your webapp. – Tarquinius Aug 10 '23 at 09:49
  • Can I ask the advantage of this approach? In case I ever need it in the future. – Muhammad Taimoor Aug 12 '23 at 06:06
  • 1
    Well I am no expert on this, but it states as follows: "When using Matplotlib in a web server it is strongly recommended to not use pyplot" because of memory leaks. The main advantage is (imo) that the plot looks exactly like the matplotlib plot without any changes of `mpld3`. Basically you are keeping it 100% matplotlib. – Tarquinius Aug 13 '23 at 19:00

1 Answers1

1

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.

Tarquinius
  • 1,468
  • 1
  • 3
  • 18