Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Draw the BMI weight chart with D3, along with the current value

Roland Geider824c1701743b
diff --git a/wger/manager/static/js/workout-manager.js b/wger/manager/static/js/workout-manager.js
index 4d45924c9..66f4c8855 100644
--- a/wger/manager/static/js/workout-manager.js
+++ b/wger/manager/static/js/workout-manager.js
@@ -245,8 +245,8 @@ function modal_dialog_form_edit()
// bootstrap's menu bar (drop downs won't open). So just do a normal
// redirect.
window.location.href = current_url;
-
-
+
+
/*
if(document.URL.indexOf(current_url))
{
@@ -292,11 +292,11 @@ function init_ingredient_autocompleter()
// After clicking on a result set the value of the hidden field
$('#id_ingredient').val(ui.item.id);
$('#exercise_name').html(ui.item.label);
-
+
// See if the ingredient has any units and set the values for the forms
$.get('/' + get_current_language() + '/nutrition/ingredient/' + ui.item.id + '/get-units',
function(data){
-
+
// Remove any old units, if any
var options = $('#id_weight_unit').find('option');
$.each(options, function(index, option_obj) {
@@ -305,10 +305,10 @@ function init_ingredient_autocompleter()
$(option_obj).remove();
}
});
-
+
// Add new units, if any
$.each(data, function(index, value) {
- $('#id_unit').append(new Option(value.name, value.id));
+ $('#id_unit').append(new Option(value.name, value.id));
$('#id_weight_unit').append(new Option(value.name_model, value.id));
});
});
@@ -352,7 +352,7 @@ function add_exercise(exercise)
$(result_div).prependTo("#exercise-search-log");
$("#exercise-search-log").scrollTop(0);
-
+
}
function get_exercise_formset(exercise_id)
@@ -363,7 +363,7 @@ function get_exercise_formset(exercise_id)
var formset_url = '/' + get_current_language() +
'/workout/get-formset/' + exercise_id +
'/' + set_value + '/';
-
+
$.get(formset_url, function(data) {
$('#formsets').prepend(data);
$("#exercise-search-log").scrollTop(0);
@@ -378,7 +378,7 @@ function update_all_exercise_formset()
if (set_value && parseInt(set_value))
{
$.each($('#exercise-search-log input'), function(index, value) {
-
+
var exercise_id = value.value;
if (exercise_id && parseInt(exercise_id))
{
@@ -405,7 +405,7 @@ function init_edit_set()
// Add the exercise to the list
add_exercise(ui.item);
-
+
// Load formsets
get_exercise_formset(ui.item.id)
@@ -415,7 +415,7 @@ function init_edit_set()
e.preventDefault();
exercise_id = $(this).parent('div').find('input').val()
$('#formset-exercise-'+exercise_id).remove();
- $(this).parent('div').remove();
+ $(this).parent('div').remove();
});
// Reset the autocompleter
@@ -429,7 +429,7 @@ function init_edit_set()
e.preventDefault();
var exercise_id = $(this).parent('div').find('input').val()
$('#formset-exercise-'+exercise_id).remove();
- $(this).parent('div').remove();
+ $(this).parent('div').remove();
});
// Slider to set the number of sets
@@ -691,11 +691,11 @@ function weight_log_chart(data, div_id, reps_i18n)
var reps = color.domain().map(function(name) {
- temp_values = data.filter(function(d) {
+ var temp_values = data.filter(function(d) {
return(+d[name] > 0);
});
- filtered_values = temp_values.map(function(d) {
+ var filtered_values = temp_values.map(function(d) {
return {date: d.date,
weight: +d[name],
log_id: d.id};
@@ -707,9 +707,11 @@ function weight_log_chart(data, div_id, reps_i18n)
};
});
+ //console.log(reps);
+
x.domain(d3.extent(data, function(d) { return d.date; }));
- // Add 1 kg of "breathing room" on the min value, so the diagrams don't
+ // Add 1 kg of "breathing room" on the min value, so the diagrams don't look
// too flat
y.domain([
d3.min(reps, function(c) { return d3.min(c.values, function(v) { return v.weight - 1; }); }),
@@ -742,9 +744,9 @@ function weight_log_chart(data, div_id, reps_i18n)
.style("stroke", function(d) { return color(d.name); });
reps.forEach(function(d){
- color_name = d.name
- temp_name = hex_random();
- color_class = 'color-' + color(color_name).replace('#', '');
+ var color_name = d.name
+ var temp_name = hex_random();
+ var color_class = 'color-' + color(color_name).replace('#', '');
svg.selectAll(".dot" + temp_name)
.data(d.values)
diff --git a/wger/nutrition/templates/bmi/form.html b/wger/nutrition/templates/bmi/form.html
index b253fef31..23e0ace98 100644
--- a/wger/nutrition/templates/bmi/form.html
+++ b/wger/nutrition/templates/bmi/form.html
@@ -4,6 +4,7 @@
{% load wger_extras %}
{% block header %}
+<script src="{% static 'js/d3.js' %}"></script>
<style>
div.table {
display:table;
@@ -22,27 +23,117 @@ div.bmi-legend {
}
</style>
+
<script>
-$(document).ready(function() {
+$(document).ready(function () {
+
+ /*
+ * Draw the static part of the chart
+ */
+ var margin = {top: 20, right: 20, bottom: 30, left: 50},
+ width = 600 - margin.left - margin.right,
+ height = 300 - margin.top - margin.bottom;
+
+ var x = d3.scale.linear()
+ .range([0, width]);
+
+ var y = d3.scale.linear()
+ .range([height, 0]);
+
+ var z = d3.scale.ordinal().range(['#000080', '#0000ff', '#00ffff', '#00ff00', '#ffff00', '#ff7f2a', '#ff0000', '#800000']);
+
+ var xAxis = d3.svg.axis()
+ .scale(x)
+ .orient("bottom");
+
+ var yAxis = d3.svg.axis()
+ .scale(y)
+ .orient("left");
+
+ var stack = d3.layout.stack()
+ .offset("zero")
+ .values(function(d) { return d.values; })
+ .x(function(d) { return d.height; })
+ .y(function(d) { return d.weight; });
+
+ var nest = d3.nest()
+ .key(function(d) { return d.key; });
+
+ var area = d3.svg.area()
+ .interpolate("linear")
+ .x(function(d) { return x(d.height); })
+ //.x(function(d) { return x(d.height); })
+ .y0(function(d) { return y(d.y0); })
+ //.y1(function(d) { return y(d.y0 + d.y); });
+ .y1(function(d) { return y(d.weight); });
+
+ var svg = d3.select("#bmi-chart").append("svg")
+ .attr("width", width + margin.left + margin.right)
+ .attr("height", height + margin.top + margin.bottom)
+ .append("g")
+ .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
+
+ d3.json("/nutrition/calculator/bmi/chart-data", function(data) {
+
+ var layers = stack(nest.entries(data));
+
+ x.domain(d3.extent(data, function(d) { return d.height; }));
+ //y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);
+ y.domain([0, d3.max(data, function(d) { return d.weight; })]);
+ //y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);
+
+ svg.selectAll(".layer")
+ .data(layers)
+ .enter().append("path")
+ .attr("class", "layer")
+ .attr("d", function(d) { return area(d.values); })
+ .style("fill", function(d, i) { return z(i); })
+ .style("opacity", 0.6);
+
+ svg.append("g")
+ .attr("class", "x axis")
+ .attr("transform", "translate(0," + height + ")")
+ .call(xAxis);
+
+ svg.append("g")
+ .attr("class", "y axis")
+ .call(yAxis);
+ });
+ /*
+ * Draw the calculated BMI
+ */
+ function draw_circle(weight, height)
+ {
+ svg.append("circle")
+ .attr("cx", x(height))
+ .attr("cy", y(weight))
+ .attr("fill", "black")
+ .attr("r", 5);
+ }
+
+ /*
+ * Process the form
+ */
$("#bmi-form").click(function(e){
e.preventDefault();
var url = $("#bmi-form").attr( 'action' );
$.post(url,
- $("#bmi-form").serialize(),
- function(data) {
- console.log(data);
-
- $('#bmi-result-container').show();
- $('#bmi-result-value').html(data.bmi);
-
- //$('.result').html(data);
- });
+ $("#bmi-form").serialize(),
+ function(data) {
+ $('#bmi-result-container').show();
+ $('#bmi-result-value').html(data.bmi);
+ draw_circle(data.weight, data.height);
+ });
});
- });
+});
</script>
+
+
+
+
{% endblock %}
<!--
@@ -91,6 +182,8 @@ $(document).ready(function() {
</div>
+
+
<img width="479"
height="300"
title="{% trans 'BMI' %}"
@@ -98,6 +191,7 @@ $(document).ready(function() {
src="{% static 'images/bmi.svg' %}"
style="margin-top:3em;"></img>
+<div id="bmi-chart"></div>
<h3>{% trans "Legend" %}</h3>
@@ -136,6 +230,7 @@ $(document).ready(function() {
</div>
</div>
+
{% endblock %}
diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.py
index 92d58b939..36a638fbe 100644
--- a/wger/nutrition/urls.py
+++ b/wger/nutrition/urls.py
@@ -114,6 +114,9 @@ urlpatterns = patterns('wger.nutrition.views',
url(r'^calculator/bmi/calculate$',
'bmi.calculate',
name='bmi-calculate'),
+ url(r'^calculator/bmi/chart-data$',
+ 'bmi.chart_data',
+ name='bmi-chart-data'), # JS
# Calories calculator
url(r'^calculator/calories$',
diff --git a/wger/nutrition/views/bmi.py b/wger/nutrition/views/bmi.py
index 2e7fa86ac..2e0ef7932 100644
--- a/wger/nutrition/views/bmi.py
+++ b/wger/nutrition/views/bmi.py
@@ -78,8 +78,36 @@ def calculate(request):
entry.save()
bmi = request.user.userprofile.calculate_bmi()
- result = {'bmi': '{0:.2f}'.format(bmi)}
+ result = {'bmi': '{0:.2f}'.format(bmi),
+ 'weight': form.cleaned_data['weight'],
+ 'height': request.user.userprofile.height}
data = json.dumps(result)
# Return the results to the client
return HttpResponse(data, 'application/json')
+
+
+def chart_data(request):
+ '''
+ Returns the data to render the BMI chart
+ '''
+
+ data = json.dumps([
+ {'key': 'Group1', 'height':160, 'weight': 40},
+ {'key': 'Group1', 'height':200, 'weight': 65},
+ {'key': 'Group2', 'height':160, 'weight': 44},
+ {'key': 'Group2', 'height':200, 'weight': 68},
+ {'key': 'Group3', 'height':160, 'weight': 48},
+ {'key': 'Group3', 'height':200, 'weight': 72},
+ {'key': 'Group4', 'height':160, 'weight': 63},
+ {'key': 'Group4', 'height':200, 'weight': 100},
+ {'key': 'Group5', 'height':160, 'weight': 76},
+ {'key': 'Group5', 'height':200, 'weight': 120},
+ {'key': 'Group6', 'height':160, 'weight': 88},
+ {'key': 'Group6', 'height':187, 'weight': 120},
+ {'key': 'Group7', 'height':160, 'weight': 102},
+ {'key': 'Group7', 'height':175, 'weight': 120}
+ ])
+
+ # Return the results to the client
+ return HttpResponse(data, 'application/json')
\ No newline at end of file