简体   繁体   中英

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?

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]; });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM