Gregg
Gregg

Reputation: 109

How can I use column values for SVG colors using JS/D3?

I searched for this and found a lot of info on how to set scales, but I'm trying to color individual SVGs created in D3 using values from a column that's populated with hex values. In the code below "Color1" is the column populated with different hex color values, e.g., #000000;

Here's what I've tried that makes intuitive sense to me but isn't working, instead the chart populates with the fill as black:

  var circles = svg.selectAll('circle')
      .data(data)
      .enter()
    .append('circle')
      .attr('cx',function (d) { return xScale(d.xvalue) })
      .attr('cy',function (d) { return yScale(d.yvalue) })
      .attr('r','3')
      .attr('stroke','black')
      .attr('stroke-width',1)
      .attr('fill', function (d) {return d.Color1})

I've also tried surrounding the function with "'" but was unsuccessful.

Upvotes: 1

Views: 95

Answers (1)

Andrew Reid
Andrew Reid

Reputation: 38171

The color property should not include a semicolon:

var data = [
  {Color1: "#aaaaaa;"}, 
  {Color1: "#aaaaaa"}
]

var svg = d3.select("body").append("svg");

var circles = svg.selectAll('circle')
   .data(data)
    .enter()
    .append('circle')
      .attr('cx',(d,i)=>i*100+50)
      .attr('cy', 100)
      .attr('r','10')
      .attr('stroke','black')
      .attr('stroke-width',1)
      .attr('fill', function(d) { return d.Color1; })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

You could just slice the last character off if you have the semicolon hard coded in your data:

.attr("fill", function(d) { return d.Color1.slice(0,-1); })

Upvotes: 1

Related Questions