How can I use Javascript / D3 to create a color scale mapping 5 hex colors to 17 colors?

If I start with the array of hexadecimal colors

['#1147FF', '#86D8FF', '#FFEF67', '#FF7D11', '#F30000']
in JavaScript, I can achieve the color scale I desire by adjusting the steps on the scales website from 5 to 17. This simplifies the process as I can use 6-hex hex values.

Currently, my method involves converting hex values to RGB values and then iterating through them in a cumbersome manner. Here is a snippet of what I'm doing, disregarding the `green` variables:


    green0pct = { r: 17, g: 71, b: 255 };
    green7p5pct = { r: 134, g: 216, b: 255 };
    green15pct = { r: 252, g: 233, b: 70 };
    green22p5pct = { r: 255, g: 125, b: 17 };
    green30pct = { r: 243, g: 0, b: 0 };

    for (let j = 0; j <= 30; j++) {
        if (j % 2 === 0) {
            if (j < 7.5) {
                newR = green0pct.r - (j * (green0pct.r - green7p5pct.r) / 7.5);//
                newG = green0pct.g - (j * (green0pct.g - green7p5pct.g) / 7.5);
                newB = green0pct.b - (j * (green0pct.b - green7p5pct.b) / 7.5);
            } else if (j < 15) {
                newR = green7p5pct.r - ((j - 7.5) * (green7p5pct.r - green15pct.r) / 7.5);
                newG = green7p5pct.g - ((j - 7.5) * (green7p5pct.g - green15pct.g) / 7.5);
                newB = green7p5pct.b - ((j - 7.5) * (green7p5pct.b - green15pct.b) / 7.5);
            } else if (j < 22.5) {
                newR = green15pct.r - ((j - 15) * (green15pct.r - green22p5pct.r) / 7.5);
                newG = green15pct.g - ((j - 15) * (green15pct.g - green22p5pct.g) / 7.5);
                newB = green15pct.b - ((j - 15) * (green15pct.b - green22p5pct.b) / 7.5);
            } else {
                newR = green22p5pct.r - ((j - 22.5) * (green22p5pct.r - green30pct.r) / 7.5);
                newG = green22p5pct.g - ((j - 22.5) * (green22p5pct.g - green30pct.g) / 7.5);
                newB = green22p5pct.b - ((j - 22.5) * (green22p5pct.b - green30pct.b) / 7.5);
            }
            displayPct = playerOrTeam === 'Team' ? (j - 15) / 2 : j - 15;
            greenScale.push({ text: `${displayPct}%`, col: `rgb(${newR},${newG},${newB})` });
        }}

Answer №1

To create a gradient effect, consider utilizing a d3-interpolator:

d3.interpolateRgbBasis(colors) <>

This function generates a smooth transition of colors using a B-spline interpolator through the specified array of colors. These colors are then converted to RGB color space. The interpolator automatically calculates control points so that the output at 0 is colors[0] and at 1 is colors[colors.length - 1]. (source)

To start, you can create a new set of n colors using an array of colors and the interpolator as shown below:

// Initial colors:
var colors = ['#1147FF', '#86D8FF', '#FFEF67', '#FF7D11', '#F30000'];

// Create an interpolator:
var interpolate = d3.interpolateRgbBasis(colors);

// Generate 17 new colors: 
var n = 17;
var newColors = d3.range(n).map(function(d) {
  return interpolate(d/(n-1));  // d/(n-1) ranges from 0 to 1
})

Here's an example of how this can be executed:

var colors = ['#1147FF', '#86D8FF', '#FFEF67', '#FF7D11', '#F30000'];
var interpolate = d3.interpolateRgbBasis(colors);

var n = 17;
var newColors = d3.range(n).map(function(d) {
  return interpolate(d/(n-1));
})

console.log(newColors);

d3.select("svg")
  .selectAll("rect")
  .data(newColors)
  .enter()
  .append("rect")
  .attr("fill", function(d) { return d; })
  .attr("width", 10)
  .attr("height",10)
  .attr("x", function(d,i) {
    return i*12;
  })
  .attr("y", 20);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>

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

Steps for dynamically loading the content of a Bootstrap 4 Modal

I am currently in the process of developing a website that will showcase a wide range of images. The design is set up as a landing page with all content contained within the main HTML page - there is only an index.html file for now. This website will serv ...

ClassSerializerInterceptor in NestJS does not show the _id field

I am encountering an issue with properly exposing the _id when using the Serializer. Here is my current setup: @UseInterceptors(ClassSerializerInterceptor) @SerializeOptions({ strategy: 'excludeAll' }) This is how I defined the Class: export cl ...

Exploring the use of single character alternation in regex with Webstorm's Javascript Regex functionality

I've been attempting to divide the string using two different separators, like so: "some-str_to_split".split(/-|_/) It successfully splits the string based on both "-" and "_". However, Webstorm is issuing a warning: Single character alternation ...

How to arrange elements at the same level in Node.js using sequelize-hierarchy?

Is there a way to change the order of items on the same level in sequelize-hierarchy for creating a menu? I've noticed that currently, the items are ordered by their sequence of insertion. But what if I want to manually set the order? Here is an exam ...

Steps to eliminate a choice from the MUI Datagrid Column Show/Hide feature

I am attempting to customize which columns are displayed on the <GridToolbarColumnsButton/> component within the MUI Datagrid toolbar (refer to the image below) https://i.stack.imgur.com/joZUg.jpg Potential solution: I have been exploring the AP ...

Ways to remove all attributes from a JSON data type

In my code, I am working with the following object: [ { "Name": "John Johnsson", "Adress": "Linkoping", "Id": 0, "Age": "43", "Role": "Software Engineer" }, { &qu ...

Reposition the initial element to the end of an array using setInterval() within a React component

I'm attempting to rearrange the elements in an array in React, specifically by moving the first item to the last position using a setInterval function: const [cardOrder, setCardOrder] = useState([card1, card2, card3, card4]); setInterval(() => { ...

Ways to safeguard your API endpoint

Just starting out with Node.js/Express, I'm looking to have my front end retrieve data from an endpoint ('/1') without displaying the JSON data to users when they access that specific endpoint. Any guidance on how to accomplish this would be ...

Ways to dynamically update a Vuetify 3 element's placeholder text?

Here is the code snippet from my component.vue file: <template> <v-text-field name="Foo" :label="$t('foo')" type="text" hint="This is a hint" persistent-hint >& ...

ESLint has detected an unexpected use of an underscore in the variable name "__place". Avoid using dangling underscores in variable names to follow best coding practices

I received the JSON response shown below. To validate the _place, I used responseData.search[0].edges[0].node._place { "data": { "search": [ { "_place": "SearchResultItemConnection", "edges": [ { "cursor": ...

In Vue firebase, ensure that the prop is only passed down after it has been

I am facing an issue where I need to pass down the Firebase user as a prop from the root component to my child components. I managed to achieve this by passing the user to my router. However, the problem arises when I wrap my new Vue instance in an onAuthS ...

Having trouble loading background color or image in three.js

I've been struggling to load a background image or color on my webpage. Despite trying various methods, including commenting out javascript files and checking the stylesheet link, nothing seems to work. Even when I load the three.js scene with javascr ...

What causes the function execution to not be delayed by setTimeout?

function attemptDownloadingWebsite(link) { iframe = document.getElementById('downloadIFrame'); iframe.src = link; setTimeout(removeFile(link), 25000); } This is the remove file function: function removeFile(link){ $.ajax ...

Is there a way to make this variable function properly within the google.maps.LatLng() method?

I've been working on a function that goes through some JSON data and retrieves latlong information to be displayed inside google.maps.LatLng(). The issue I'm facing is that I keep getting a null return and I can't seem to identify the reason ...

Issue encountered: Unable to fetch username and password from request

Currently, I am developing a login and registration system. However, when I input the correct details in my register Post method, the request remains pending and I cannot identify the error. The specific error message it presents is data and salt arguments ...

Internet Explorer displaying incorrect formatting for HTML CSS tables

Having an issue with table display on IE 9/10/11. Tested code on different browsers and platforms, everything looks good except when viewed on my HTTP server (lighttpd and python SimpleHTTPServer), the table is showing up incorrectly: var cell = $(&apos ...

Inaccurate Guild Member Filtering

Recently, I've been working on creating a unique member counter for my server. The goal is to accurately count the total number of members in the server, excluding bots, and counting only bots as well. However, when I attempt to display these counts i ...

What is the best way to handle an AJAX request within an if-else statement?

Attempting to utilize an if-else condition in order to make a jQuery Ajax call to an API. Having trouble understanding why the ajax function is being called even though it should be in the else statement. Below is the code snippet: if (e.value == null | ...

Implement AJAX in order to circumvent fees from Google Maps and display maps exclusively upon user interaction by clicking a designated button

Starting July 16, 2018, the Google Maps API is no longer completely free. After July 16, 2018, in order to continue utilizing the Google Maps Platform APIs, you must activate billing for each of your projects. (https://developers.google.com/maps/documentat ...

Difficulty with AngularJS pagination and encountering errors when trying to read the property 'slice' of an undefined value

Could someone please help me with this issue I'm facing? Here is the code snippet: (function () { var app = angular.module('store', ['ui.bootstrap']); app.controller('StoreController', function ($scope, $http) ...