mybuddy/reports/graphs/pumping_amounts.py

73 lines
2.3 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
from django.utils import timezone
from django.utils.translation import gettext as _
import plotly.offline as plotly
import plotly.graph_objs as go
from reports import utils
2022-03-04 15:39:13 +00:00
def pumping_amounts(objects):
"""
2022-03-04 15:39:13 +00:00
Create a graph showing pumping amounts over time.
:param instances: a QuerySet of Pumping instances.
:returns: a tuple of the the graph's html and javascript.
"""
2022-03-31 03:55:35 +00:00
objects = objects.order_by("time")
2022-03-31 03:55:35 +00:00
# We need to find date totals for annotations at the end
2022-04-04 15:40:25 +00:00
curr_date = ""
date_totals = {}
2022-03-31 03:55:35 +00:00
for object in objects:
date_s = timezone.localtime(object.time)
date_s = str(date_s.date())
2022-03-31 03:55:35 +00:00
if curr_date != date_s:
date_totals[date_s] = 0.0
2022-03-31 03:55:35 +00:00
curr_date = date_s
date_totals[date_s] += object.amount
2022-03-31 03:55:35 +00:00
2022-04-04 15:40:25 +00:00
dates = [] # Single array for each bar
amounts = [] # Array of arrays containing amounts
index_x, index_y = 0, -1
2022-03-31 03:55:35 +00:00
for object in objects:
date_s = timezone.localtime(object.time)
date_s = str(date_s.date())
2022-03-31 03:55:35 +00:00
if date_s not in dates:
dates.append(date_s)
index_y += 1
index_x = 0
if len(amounts) == 0 or len(amounts) <= index_x:
2022-04-04 15:40:25 +00:00
amounts.append([0] * len(date_totals.keys()))
2022-03-31 03:55:35 +00:00
amounts[index_x][index_y] = object.amount
index_x += 1
2022-04-04 15:40:25 +00:00
2022-03-31 03:55:35 +00:00
traces = []
2022-10-17 01:38:08 +00:00
for i in range(0, len(amounts)):
2022-03-31 03:55:35 +00:00
traces.append(
go.Bar(
name="Amount",
x=dates,
y=amounts[i],
text=amounts[i],
hovertemplate=amounts[i],
showlegend=False,
)
)
layout_args = utils.default_graph_layout_options()
2022-03-31 03:55:35 +00:00
layout_args["title"] = _("<b>Total Pumping Amount</b>")
layout_args["xaxis"]["title"] = _("Date")
layout_args["xaxis"]["rangeselector"] = utils.rangeselector_date()
2022-03-31 03:55:35 +00:00
layout_args["yaxis"]["title"] = _("Pumping Amount")
2022-04-04 15:40:25 +00:00
total_labels = [
{"x": x, "y": total * 1.1, "text": str(total), "showarrow": False}
for x, total in zip(list(dates), date_totals.values())
]
2022-03-31 03:55:35 +00:00
fig = go.Figure({"data": traces, "layout": go.Layout(**layout_args)})
fig.update_layout(barmode="stack", annotations=total_labels)
output = plotly.plot(fig, output_type="div", include_plotlyjs=False)
return utils.split_graph_output(output)