Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a graph from a CSV file and render to browser with Django and the Pandas Python library

I'm learning how to use the Django framework for a work project that will allow users to load files in various formats (at the moment I am only dealing with CSV files), graph that data using Pandas, and display that data back to the user via a Django template. I haven't had any problems creating the graph in iPython, but have been struggling with getting it to an HTML Django template.

I've followed the following example from matplotlib:

# graph input file

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter

def graph(request):
    fig = Figure()
    ax = fig.add_subplot(111)
    x = []
    y = []
    now = datetime.datetime.now()
    delta = datetime.timedelta(days=1)
    for i in range(10):
        x.append(now)
        now += delta
        y.append(random.randint(0, 1000))
    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas = FigureCanvas(fig)
    response = HttpResponse( content_type = 'image/png')
    canvas.print_png(response)
    return response

The above example works great and I can see it in a template, but that's just a graph with hard-coded values.

I've attempted to use Pandas because of its seemingly simplistic syntax and my attempts in Django are as follows:

# graph input file

import pandas as pd
from pandas import DataFrame

def graph(request):
    data_df = pd.read_csv("C:/Users/vut46744/Desktop/graphite_project/sampleCSV.csv")
    data_df = pd.DataFrame(dataArray)
    data_df.plot()
    response = HttpResponse( content_type = 'image/png')

    return response

In Django calling the .plot() displays the graph fine, but displays a blank page to the HTML template. I've also tried using Numpy's genfromtxt() and loadtxt(), but to no avail. Also, my Google searches have not been fruitful either.

Any help or suggestion would be great. If you know of a better alternative to Pandas then I am willing to try other options.

like image 479
alacy Avatar asked Sep 30 '22 06:09

alacy


1 Answers

Haven't tried this yet, but I would attack it something like:

def graph(request):
    fig = Figure()
    ax = fig.add_subplot(111)
    data_df = pd.read_csv("C:/Users/vut46744/Desktop/graphite_project/sampleCSV.csv")
    data_df = pd.DataFrame(data_df)
    data_df.plot(ax=ax)
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
like image 184
Josha Inglis Avatar answered Oct 03 '22 08:10

Josha Inglis