Skip to content Skip to sidebar Skip to footer

Python Pygal Chart Pulling Data From Database Not Matching Values To Labels

I am working on my first project and I am using Pygal to visualize some data from a database. I am using the latest version of Python (3.6.5), Flask, Pygal and my IDE is Pycharm Th

Solution 1:

I got it working!

In the end I realized I was over-complicating my question, so I pulled out a pen and paper and started doing some pseudo-code to see where was the first step in my code where I could comfortably calculate the floats sum that was causing me head-aches.

Step 1: In my route, I could create a list containing nested tuples (with 2 elements each: str and float)

Step 2: Now, if some of the tuples had the same elements on index [0], how do I sum the float elements on index [1]?

So, I asked the this question on reddit.com/r/learnpython and the user diesch gave me an idea that I could use successfully: to import the itertools package and from it, to use groupby().

Here is how my route code looks now:

@posts.route("/home")
def graphing():
    data_planned, data_actual = GraphData()

    title_planned = []
    value_planned = []
    title_actual = []
    value_actual = []
    planned = []
    actual = []

    for planned_row in data_planned:
        title_planned.append(planned_row[2])
        value_planned.append(planned_row[3])
        planned_list = zip(title_planned, value_planned)
        for key, group in itertools.groupby(sorted(planned_list), lambda  x: x[0]):
            asum = 0
            for i in group:
                asum += i[1]
            planned.append((key, asum))

    planned_dict = dict(planned)

    for actual_row in data_actual:
        title_actual.append(actual_row[2])
        value_actual.append(actual_row[3])
        actual_list = zip(title_actual, value_actual)
        for key, group in itertools.groupby(sorted(actual_list), lambda  x: x[0]):
            asum = 0
            for i in group:
                asum += i[1]
            actual.append((key, asum))

    actual_dict = dict(actual)

    graph = pygal.Bar(title=u'Total Planned Values vs Total Actual Values')
    graph.add('Planned', [{'value': sum(value_planned), 'label': 'Total for Planned Budget:'}])
    graph.add('Actual', [{'value': sum(value_actual), 'label': 'Total for Actual Amounts:'}])
    graph_data = graph.render_data_uri()

    graph_all = pygal.Bar(title=u'Planned Budget per item vs Actual Amounts per item')
    graph_all.x_labels = title_planned
    graph_all.add('Planned', planned_dict)
    graph_all.add('Actual', actual_dict)
    graph_all_data = graph_all.render_data_uri()

    return render_template('home.html', graph_data=graph_data, graph_all_data=graph_all_data)    

Post a Comment for "Python Pygal Chart Pulling Data From Database Not Matching Values To Labels"