Color Scales with Bar Charts

1,671 views
Skip to first unread message

Guerino1

unread,
Mar 20, 2012, 5:41:12 PM3/20/12
to d3...@googlegroups.com
Hi,

Having a color mapping problem... I put my code up on github (https://gist.github.com/2141479).  This is my first attempt at doing so, so if there's a problem viewing it, please let me know and I'll just put the code in the thread.

I read the documentation and tried to read through threads in the group but couldn't find something that was a straightforward answer.

I started with learning Mike's Bar Chart tutorial and I've been working on my own to build an example that draws bar charts into HTML pages with multiple other HTML layout constructs.

I'm trying to assign different colors to different bars and I think i'm, both, misunderstanding and misusing the color scale categories.

I have an array of values that I pass into the chart drawing function...

var data1 = [4, 8, 15, 16, 23, 42];
function drawBars(barValues, selectString) {....

I then try to map the colors to the values in the data set "barValues"...

var colorScale = d3.scale.category20c()
.domain(barValues);

Later, when I go to apply the fill color, they're all a light orange, which appears to lock onto the quantity of the "barValues" array, which is "6", rather than assigning one color to each bar.

Can someone please take a look and tell me what I'm doing wrong?

Thanks,

Frank
 

 

Frank Guerino

unread,
Mar 21, 2012, 2:56:03 PM3/21/12
to d3...@googlegroups.com
Ok, I think I've figured it out...

Using your data array...

var myArray = [10, 25, 5, 9, 11, 22, 13, 5, 9];

Define your color scale...

var colorScale = d3.category20c();

Bind your data to your drawing element...

svg.selectAll("rect")
          .data(myArray)
          .enter().append('rect')
          .attr("y", y)
          .attr("width", x)
          .attr("height", y)
          .attr("height", y.rangeBand())
          .style("fill", function(d, i) { return colorScale(i); });

And, (in the last line above) use a function to return a different color from your color scale, based on something like the "myArray" array index ("i") to use as the fill for the object you're trying to fill.

This seems to work.  I hope others find it useful.

Frank




sohowaboutthis

unread,
Sep 9, 2012, 11:15:26 AM9/9/12
to d3...@googlegroups.com
I think you meant

var colorScale = d3.scale.category20c();


... which is where it's found in d3.v2.js


James
Reply all
Reply to author
Forward
0 new messages