Dev4: utilizing scaleOrdinal for color mapping and selection

I have developed a code that generates line graphs on an SVG canvas, however, I am facing difficulties in altering the colors as I defined using the d3.scaleOrdinal function.

Despite defining 12 distinct colors, the output I am getting looks like this. Is there anyone who can assist me with this? Thank you.

  var colorScheme = d3.scaleOrdinal().range([
      '#673ab7',
      '#9c27b0',
      '#e91e63',
      '#f44336',
      '#ff5722',
      '#ff9800',
      '#ffc107',
      '#ffeb3b',
      '#cddc39',
      '#8bc34a',
      '#4caf50',
      '#009688'])
    .domain(d3.range(1,13));

  var line = d3.line()
    .x(function(d) { return x(d.day); })
    .y(function(d) { return y(d.temp); });

  var generateLineChart = function(csvfile, i) {
    d3.csv(csvfile, function(error, data){
      data.forEach(function(d){
        d.month = +d.month,
        d.day= +d.day,
        d.temp= +d.temp;
      });

      svg.append('path')
        .data([data])
        .attr('class','line')
        .style('stroke', function(i){ return colorScheme(i);})
        .attr('d', line);

    }); //end of read csv
  }; //end of line chart

  generateLineChart('/static/data/temp1.csv'1);
  generateLineChart('/static/data/temp2.csv'2);
  generateLineChart('/static/data/temp3.csv'3);
  generateLineChart('/static/data/temp4.csv'4);
  generateLineChart('/static/data/temp5.csv',5);
  generateLineChart('/static/data/temp6.csv',5);
  generateLineChart('/static/data/temp7.csv',6);
  generateLineChart('/static/data/temp8.csv',7);
  generateLineChart('/static/data/temp9.csv',8);
  generateLineChart('/static/data/temp10.csv',80);
  generateLineChart('/static/data/temp11.csv',90);
  generateLineChart('/static/data/temp12.csv',100);

Answer №1

One issue to address is that in D3, the first argument is consistently the data, regardless of whether it is named d, i, or p. Therefore, the following adjustment should be made:

.style('stroke', function(d, i){ return color2(i);})

However, simply making this change will not suffice due to a second concern.

The second problem lies in repeatedly calling lineChart for each line, resulting in the index always being 0 upon each invocation.

A potential solution involves passing the index as an argument, like so:

lineChart('/static/data/temp1.csv', 1);
lineChart('/static/data/temp2.csv', 2);
lineChart('/static/data/temp3.csv', 3);
//...

Within the function (although the function declarations were omitted), consider including:

function lineChart(url, index){
    //your existing code
    .style('stroke', function(){ return color2(index);})
    .attr('d', line);
};

Please refer to this demonstration for further clarity:

var svg = d3.select("body").append("svg").attr("width", 500).attr("height", 200);

var color2 = d3.scaleOrdinal().range(['#673ab7','#9c27b0','#e91e63','#f44336','#ff5722','#ff9800','#ffc107','#ffeb3b','#cddc39','#8bc34a','#4caf50','#009688'])
    .domain(d3.range(1,13));

function draw(dimention, index){
  svg.append("rect").attr("x", Math.random()*470)
  .attr("y", Math.random()*170).attr("width", dimention).attr("height", dimention)
  .attr("fill", function(d,i){ console.log("index is " + i); return color2(index)});
}
  
draw(30, 1);draw(10, 2);draw(25, 3);draw(20, 4);draw(5, 5);
draw(10, 6);draw(8, 7);draw(12, 8);draw(10, 9);draw(17, 10);
<script src="https://d3js.org/d3.v4.min.js"></script>

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

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

Struggling to store the results of multiple fetch API calls in an array for future access beyond the function

fetching data from multiple APIs and storing it in an array has been a challenge. While attempting to set the data using useState, only one piece of data successfully makes it into the array. Even after trying Promise.all method, the same issue persists al ...

Combining CodeIgniter4 with Vue.js and Webpack's devServer to handle CORS issues

Exploring Vue & CodeIgniter 4, starting from https://github.com/flavea/ci4-vue. No matter what I try, I encounter a persistent CORS error in dev mode: Access to XMLHttpRequest at 'http://example.com/public/api/book/get' from origin &apo ...

Assistance needed with implementing jQuery tabs

I'm looking to add a link that takes me directly to content within a non-default tab on another page. Here's the code snippet that explains what I need: My Code: This is from my profile_edit.php page: The javascript: <script src="Javascrip ...

What is the best way to display an Error 404 page in a statically rendered client-side page using Next.js?

import { onAuthStateChanged } from "firebase/auth"; import Link from "next/link"; import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import { auth } from "../../lib/firebase&qu ...

Tips for effectively utilizing props in react

Within one of my components named header, there is a button that I want to use to toggle the visibility of the navbar component. To achieve this, I attempted to create a prop in the main component below which houses all the other components including heade ...

What is the method with the greatest specificity for applying styles: CSS or JS?

When writing code like the example below: document.querySelector('input[type=text]').addEventListener('focus', function() { document.querySelector('#deletebutton').style.display = 'none' }) input[type=text]:focu ...

Is there a way to retrieve the response body in Express framework?

In my NodeJS API using Express, I am attempting to save the response body of a request. To achieve this, I have created two middleware functions. app.use((req, res,next) => { res.status(404).json({ errors: [{ field: "url", ...

Translating Bootstrap 5 into Angular components for version 13 and above

In Angular, the lack of support for optional host-elements and containerless components means that each component comes with its own div wrapper. However, when designing Bootstrap components, a host-less component (without an extra div) is needed to mainta ...

Error encountered while trying to implement sleep function in script

Good evening. I've been attempting to implement the sleep function from the system-sleep library, but my script keeps crashing. This is the code snippet I'm working with: page.html <html lang="en"> <head> <meta charset= ...

Controller unable to update AngularJS view

As the title suggests... I'm facing a challenge with this code snippet: (function(angular) { 'use strict'; angular.module('app', []) .controller('ctrl', ['$scope', function($scope) { $scope.ini ...

What could be causing my dangerouslySetInnerHTML to show altered content?

I am working on a project using React and have encountered an issue with the code: const externalMarkup = ` <a data-refpt='DN_0OKF_177480_ID0EMPAC' /> <ol> <li value='1'> <p> <strong&g ...

Add items to a separate array only if the material UI checkbox is selected

Exploring the world of React, I decided to create a simple todo app using React JS and Material UI. With separate components for user input (TodoInput.js) and rendering individual todos with checkboxes (TodoCards.js), I aim to display the total number of c ...

Tips for inserting an object into an array

Here's the data I received: { 0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 } 1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60} 2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60} item ...

Instructions on removing rows by using buttons within a JavaScript-generated table

This snippet displays JS code to create a quiz index table and HTML code to display the index. function load(){ var data = [ { "id": "qc1111", "quizName": "Quiz1", "course": "111", "dueDate": "1/ ...

Avoid triggering the resizecolumn event in ExtJS while the columns are still loading

Currently, I am involved in a project using ExtJS 6.2 and facing a challenge related to performing operations when the columns in a grid are resized. It seems like the suitable event for this task is columnresize. However, the issue arises because the colu ...

Steer clear of using multiple returns in a loop in JavaScript by utilizing async/await to eliminate the callback pyramid or callback hell

My code consists of multiple return blocks, such as the SignUp() function. connectors.js const connectors = { Auth: { signUp(args) { return new Promise((resolve, reject) => { // Validate the data if (! ...

JavaScript function is returning 'undefined' instead of an integer

My JavaScript/jQuery function is not functioning correctly and instead of returning an integer, it returns undefined. function __getLastSelectedCategory(table_id) { if ( jQuery('.categories_table[data-table-id="1"]').find('td.active&apo ...

Checking for valid zip code using a regular expression in JavaScript

Thank you for the suggestions, everyone. I have made some modifications to the script based on your advice and it appears to be functioning correctly now. <script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script> $ ...

Is it possible to achieve consistent scrollY height values across various screen sizes?

Looking to apply a class when a certain screen height is reached? Here's my approach: window.onscroll = function() {scrollPost()}; function scrollPost () { var x = window.screen.width; var i = window.scrollY; var a = i / x; animator ...