Reputation: 901
Hello I am trying to add color fill to my bar chart which has a linear scale. The code which I am trying somehow wont work. could you please let me know what I am doing wrong. sorry, I am pretty new to D3jS and JavaScript.
Thanks!
<script>
var data = [{ "MonthYearShortName": "2014-09-13T00:00:00", "Product": "Deposits", "Actual": 330393232.5, "Forecast": 495589848.75, "Target": 495589848.75 }, { "MonthYearShortName": "2014-09-13T00:00:00", "Product": "Fee Based", "Actual": 111868709.42, "Forecast": 167803064.13, "Target": 167803064.13 }, { "MonthYearShortName": "2014-09-13T00:00:00", "Product": "Lending", "Actual": 18146873.33, "Forecast": 27220309.995, "Target": 27220309.995 }];
var color = d3.scale.linear()
.domain(0, function (d) { return max(d.Actual); })
.range(["#f3c40e", "#7d6507"]);
var width = 420,
barHeight = 20;
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width]);
var chart = d3.select('#ReportContent_ReportContent svg')
.attr("width", width)
.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data, function (d) { return d.Actual; })
.enter().append("g")
.attr("transform", function (d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", function (d) { return d.Actual / 1000000; })
.attr("height", function (d) { return d.Actual / 10000000;})
.attr("fill", color);
bar.append("text")
.attr("x", function (d) { return x(d.Actual) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function (d) { return d.Product; });
</script>
Upvotes: 0
Views: 201
Reputation: 6709
You'll need to pass a function to attr('fill, )
, not just a scale.
bar.append("rect")
.attr("width", function (d) { return d.Actual / 1000000; })
.attr("height", function (d) { return d.Actual / 10000000;})
.attr("fill", function(d) { return color(d); );
It also seems like your scale is not set up properly:
var color = d3.scale.linear()
.domain(0, THIS NEEDS TO BE A VALUE)
.range(["#f3c40e", "#7d6507"]);
The second part of the domain
needs to be a value (or a function that evaluates to one)
Upvotes: 1
Reputation: 5015
There are more issues with this bar chart than the color code, and even that one fix needs a bit more adjustment. The easiest thing was to work on a FIDDLE rather than try to squeeze all changes in a comment.
bar.append("rect")
.attr("width", function (d) { return x(d.Actual); }) //change
.attr("height", barHeight) //change
.attr("fill", function(d) { return color(d.Actual);} ); //change
There are still other changes...the domain setting was not quite right, and I also added a margin so that the text displays right using a text-anchor.
In any case, overall, I think this will take you closer to what you need.
Upvotes: 1