Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
Change colour based on data set (d3)

I have two dataset d1 and d2 as follows:

const d1 = [
 {group: "H", value: 6},
 {group: "I", value: 2},
 {group: "M", value: 3}
];
const d2 = [
 {group: "H", value: 1},
 {group: "I", value: 12},
 {group: "M", value: 2}
];

and a function called makethisgraph where the "data" that is sent is either d1 and d2 based on a button I click. In this function, based on the data I select, the bars change to match the values. I want to make it in such a manner that if I select d1 then the color of the bar changes to red and if d2 then it turns to green

function makethisgraph(data) {
 var u = svg.selectAll("rect")
 .data(data)
 u .enter()
 .append("rect")
 .merge(u)
 .transition()
 .duration(1000)
 .attr("x", function(d) { return x(d.group); })
 .attr("y", function(d) { return y(d.value); })
 .attr("width", x.bandwidth())
 .attr("height", function(d) { return height - y(d.value); })
 .attr("fill", function(d, i) {
    //  if ( data = d1)
    //  {
    //      return "red"
    //  }
    //  else
    //  {
    //      return "green"
    //  }
  return "blue"
});

I tried writing if the data I got is d1 then it will be red but it doesn't work. Is there any other way to solve this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Add a color parameter to makethisgraph:

function makethisgraph(data, color) {
  ...
  u.enter()
   ...
   .attr("fill", color);
}

...
makethisgraph(d1, 'red');
makethisgraph(d2, 'green');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!