Creating a custom scale with defined intervals using d3js

These are the different categories I have:

    var BMICategories = [
        {color:'#F43E3E',min:40,max:200,name:'morbid or massive obesity'},
        {color:'#F4B4B4',min:35,max:40,name:'severe obesity'},
        {color:'#FAE9CA',min:30,max:35,name:'moderate obesity'},
        {color:'#FFFFD4',min:25,max:30,name:'overweight'},
        {color:'#E9FFDA',min:18.5,max:25,name:'healthy weight'},
        {color:'#FFFFD4',min:16.5,max:18.5,name:'underweight'},
        {color:'#F43E3E',min:0,max:16.5,name:'famine'}
    ];

(These represent Body Mass Index (BMI), but in French (IMC))

The BMI range goes from 0 to 200, with each category having a different width.

I am trying to define a scale using d3 where the domain is BMI and the range is color. The colors are discrete values, while the domain is continuous.

I want to input the weight into the scale and retrieve the corresponding color. Ideally, I would like to get the object containing color, name, min, and max based on the weight provided.

If you're interested in trying it out, here is the BMI function:

    function calculateBMI(weight) {
        return weight / (height * height);
    }

Given that ranges overlap, how can I set the minimum to be either excluded or included, and the maximum to be the opposite?

Thank you for your help!

If the scale receives BMI instead of weight, I can wrap my scale in a function to handle the conversion.

Answer №1

Utilize a threshold scale:

//reverse the array to ensure BMI is in ascending order 
IMCcat = IMCcat.reverse();

//initialize the scale
var scale = d3.scale.threshold()
  //define the domain by excluding the lowest weight value
  .domain(IMCcat.map(function(d){ return d.min; }).slice(1))
  //assign colors to the range of the scale
  .range(IMCcat.map(function(d){ return d.color; }))

This scale assigns colors based on BMI:

> scale(40)
"#F43E3E"
> scale(30)
"#FAE9CA"

To modify the scale to map BMI values to objects containing color and name, adjust the range accordingly:

> scale.range(IMCcat)
> scale(20)
Object {color: "#E9FFDA", min: 18.5, max: 25, name: "corpulence normale"}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that text is aligned alongside an image only when both elements are enclosed within <p> tags

When using an API to pull markdown content from Contentful and converting it to HTML with ReactMarkdown, a common issue arises. The resulting HTML structure often places the text content in separate paragraphs such as: <p>Some text content</p> ...

Adjust the Bootstrap date-time-picker to accommodate various languages, while ensuring that the selected date and time are displayed in English

As I work on my app, I've implemented localization support for multiple languages. When initializing the datetimepicker in the app, I provide the current language like this: datetimepicker({ locale: languageObj.language, format: 'DD MMM ...

JavaScript 12-hour Clock Displaying 24-hour Format with AM/PM Error

I am using JavaScript to display a 12-hour digital clock that updates continuously. However, the code I found online resulted in a 24-hour clock and incorrect am/pm output. Currently, it displays 13:33 am. I have experimented with various code snippets, in ...

Utilizing jQuery Ajax to submit multiple forms using a single selector in one go

I'm having an issue with jQuery Ajax involving multiple forms. Each time I execute it, only the top form works properly while the others do not function as expected. Can anyone provide assistance with this? Here is the source code: <form id="form_ ...

Steering clear of using relative paths for requiring modules in Node.js

When it comes to importing dependencies, I like to avoid using excessive relative filesystem navigation such as ../../../foo/bar. In my experience with front-end development, I have found that using RequireJS allows me to set a default base path for "abso ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

Connecting to the grunt server is currently not possible

const config = require('path/to/config'); module.exports = function(grunt) { // Project configuration. grunt.initConfig({ server: { port: config.port, base: config.base } }); }; C:\Program Files&bsol ...

Filter the ng-repeat in Angular based on the model's value

Within my "Saving" model, there is a field called "Retailer". I want to implement an ng-repeat directive that displays only items with the same "Retailer" value. Essentially, I am attempting to rectify this issue. <div ng-repeat="saving in savings | ...

Utilizing JsSIP in a real-world telephone device

After reviewing the JsSIP library, I found it to be quite promising. However, one downside is that there doesn't seem to be an actual demonstration or code provided for making calls to a mobile phone. My question is whether it's possible to call ...

What impact does async await have on the asynchronous nature of JavaScript?

Although JavaScript is synchronous, we utilize callback promises and async-await to achieve asynchronous behavior. However, with async-await, the code waits for the await statement to be completed before proceeding to the next statement, which may seem s ...

Can anyone assist me in developing a code that logs either YES or NO in Javascript?

Looking for a code that can log either YES or NO in Javascript. Can anyone help me out with this? console.log(Math.random() >= 0.5 ? 'YES' : 'NO'); I've attempted using console.log(Math.round(Math.random)) but it doesn't ...

Switching from using ngRouter to ui-router is a common

After purchasing an angularjs template for my application, I noticed that ngRouter was used instead of ui-router, which I am more comfortable with. So, I decided to switch to ui-router and update all the routes. However, I encountered some extra code in my ...

Array of arrays implemented in JavaScript

I'm working with a JavaScript array that contains string arrays: array1, array2, array3. I need to break this array down and access the individual arrays. What is the best way to achieve this? ...

Place jQuery popup box in position

After numerous attempts, I still can't seem to find a working solution. All I want is to move my jQuery dialog box down by about 50px from the top of the page. Any suggestions on how to achieve this? function openingDialog() { $("#message").dialo ...

Refresh a page on Django without the need to reload

Looking to enhance the functionality of my homepage.html by implementing a button action that retrieves server data without causing a full page reload. The project name is "T2KG". The form structure is as follows: <form method="POST> {% csrf ...

Is there a way to figure out the variance between text blocks using JavaScript or jQuery?

Two blocks of text are in front of me, and I am intrigued to determine the difference percentage between them. Is there a way for me to accomplish this? ...

Sort the array elements by a specific property while preserving the original order of the array

I created a function that can group an array by one or more properties: var groupBy = function (fields, data) { var groups = {}; for (var i = 0; i < data.length; i++) { var item = data[i]; var container = groups; for (va ...

Ways to ensure the first div always expands when sorting in AngularJS

In my AngularJS application, I have a set of div elements generated using ng-repeat. The first div is always expanded by default upon loading the page. Now, when I click a button to sort the divs based on their ID in the JSON data, I want the top div to ...

Iterate endlessly over CSS styles in Angular 4

I'm looking to create a website background 'screensaver' by looping through an array of background URLs with a delay between switches. Currently, I have the array stored in my .ts file and I am using the NgFor directive in my HTML. However, ...

Issue encountered while trying to utilize the reset function of the FormGroup with the angular2-tinymce plugin

I utilized the FormGroup feature to construct my form, and I required a textarea component. I decided to use the angular2-tinymce library/package to create the form. Here is my HTML template: <form (submit)="submitCallLog($event)" [formGroup]="callLo ...