Amanda
Amanda

Reputation: 12777

Why is d3 ignoring my color array?

I'm trying to build out a simple color chart, as an introductory d3 exercise, and I'm already stuck.

I have the following:

var colors = ["#ffffcc","#c7e9b4","#7fcdbb","#41b6c4","#2c7fb8","#253494"];

var barHeight = 20,
    barWidth = 20,
    width = (barWidth + 5) * colors.length;


d3.select("body").selectAll("svg")
    .data(colors)
    .enter().append("rect")
     .attr("class", "block")
     .attr("width", barWidth)
     .attr("height", barHeight - 1)
    .text(function(d) { return d; })
    .attr("fill", function(d) { return d; });

https://jsfiddle.net/xryamdkf/1/

The text works fine. I see the hex codes, but the height and width are definitely not respected, and I can't seem to set the color.

This works to set the color: .style("background", function(d) { return d; }) but I think that is the text background, not the rect fill.

What am I doing wrong here? How can I make 20x20 rectangles filled with color in d3?

Upvotes: 0

Views: 893

Answers (2)

vaibhav pawar
vaibhav pawar

Reputation: 81

As you are not giving any index and reference of colors array into your function the code will not understand from where to pick colors. try with below code it will help.

d3.select("body").selectAll("svg")
.data(colors).enter().append("rect")
  .attr("class", "block")
  .attr("width", barWidth)
  .attr("height", barHeight - 1)
.text(function(d) {
    return d;
})
.attr("fill", function(d,i) { return colors[i]; });

Upvotes: 2

Andrew
Andrew

Reputation: 4624

So, a few things. You should call data() on what will be an empty selection of the things you will be adding.

svg.selectAll("rect").data(colors)
.enter().append("rect")

The rect doesn't have a text property. There is an svg text node that shows text and you'll want to add it separately.

I hope this https://jsfiddle.net/xryamdkf/8/ gets you closer.

Upvotes: 1

Related Questions