mybuddy/reports/graphs/feeding_amounts.py

78 lines
2.7 KiB
Python
Raw Normal View History

2019-05-29 17:05:30 +00:00
# -*- coding: utf-8 -*-
from django.utils import timezone
2019-05-29 17:05:30 +00:00
from django.utils.translation import gettext as _
import plotly.offline as plotly
import plotly.graph_objs as go
from reports import utils
from core import models
2019-05-29 17:05:30 +00:00
2022-01-31 01:20:50 +00:00
2019-05-29 17:05:30 +00:00
def feeding_amounts(instances):
"""
Create a graph showing daily feeding amounts over time.
:param instances: a QuerySet of Feeding instances.
:returns: a tuple of the the graph's html and javascript.
"""
2022-02-10 00:00:30 +00:00
feeding_types, feeding_types_desc = map(
list, zip(*models.Feeding._meta.get_field("type").choices)
)
2022-01-31 01:20:50 +00:00
total_idx = len(feeding_types) + 1 # +1 for aggregate total
totals_list = list()
2022-01-30 23:18:17 +00:00
for i in range(total_idx):
totals_list.append({})
for instance in instances:
end = timezone.localtime(instance.end)
date = end.date()
2022-02-10 00:00:30 +00:00
if date not in totals_list[total_idx - 1].keys():
2022-01-30 23:18:17 +00:00
for item in totals_list:
2022-01-31 01:20:50 +00:00
item[date] = 0
feeding_idx = feeding_types.index(instance.type)
totals_list[feeding_idx][date] += instance.amount or 0
2022-02-10 00:00:30 +00:00
totals_list[total_idx - 1][date] += instance.amount or 0
zeros = [0 for a in totals_list[total_idx - 1].values()]
2022-01-31 01:20:50 +00:00
# sum each feeding type for graph
amounts_array = []
2022-01-30 23:18:17 +00:00
for i in range(total_idx):
2022-01-31 01:20:50 +00:00
amounts_array.append([round(a, 2) for a in totals_list[i].values()])
traces = []
2022-02-10 00:00:30 +00:00
for i in range(total_idx - 1):
for x in amounts_array[i]:
if x != 0: # Only include if it has non zero values
2022-02-10 00:00:30 +00:00
traces.append(
go.Bar(
name=str(feeding_types_desc[i]),
x=list(totals_list[total_idx - 1].keys()),
y=amounts_array[i],
text=amounts_array[i],
hovertemplate=str(feeding_types_desc[i]),
)
)
break
2022-01-30 23:18:17 +00:00
2022-02-10 00:00:30 +00:00
traces.append(
go.Bar(
name=_("Total"),
x=list(totals_list[total_idx - 1].keys()),
y=zeros,
hoverinfo="text",
textposition="outside",
text=amounts_array[total_idx - 1],
showlegend=False,
)
)
2022-01-30 23:18:17 +00:00
2019-05-29 17:05:30 +00:00
layout_args = utils.default_graph_layout_options()
2022-02-10 00:00:30 +00:00
layout_args["title"] = _("<b>Total Feeding Amount by Type</b>")
layout_args["xaxis"]["title"] = _("Date")
layout_args["xaxis"]["rangeselector"] = utils.rangeselector_date()
layout_args["yaxis"]["title"] = _("Feeding amount")
2019-05-29 17:05:30 +00:00
2022-02-10 00:00:30 +00:00
fig = go.Figure({"data": traces, "layout": go.Layout(**layout_args)})
fig.update_layout(barmode="stack")
output = plotly.plot(fig, output_type="div", include_plotlyjs=False)
2019-05-29 17:05:30 +00:00
return utils.split_graph_output(output)