Snick
Snick

Reputation: 1042

Horizontal gradient in a bar chart

I have a bar chart.

enter image description here

function svg_render(data, svg) {
 var node = d3.select(svg).append("svg")
.attr("class", "chart")
.attr("width", width)
.attr("height", height);

var y = d3.scale.linear().range([height, -height]);
var max_val = d3.max(data, function(d) {
return d;
});
y.domain([-max_val, max_val]);
var x = d3.scale.linear().domain([0, data.length]);
var bar_width = width / data.length;

var chart = node.attr("width", width).attr("height", height);

var bar = chart.selectAll("g")
.data(data)
.enter().append("g") // svg "group"
.attr("transform", function(d, i) {
  return "translate(" + i * bar_width + ",0)";
});

bar.append("rect")
.attr("y", function(d) {
  var yv = height - Math.abs(y(d) / 2) - height / 2 + 2;
  return yv;
})
.attr("height", function(d) {
  return Math.abs(y(d));
})
.attr("width", bar_width);

var axis = d3.svg.axis()
.scale(y)
.ticks(12)
.orient("left");

d3.select(".svg").append("svg")
.attr("class", "axis")
.attr("width", 60)
.attr("height", height)
.append("g")
.attr("transform", "translate(40," + (height / 2) + ")")
.call(axis);
}

would be great to be able to have a gradient towards the chart. An horizontal one.

Something like

enter image description here

Each bar can have a specific rgb code, but would be better if it was all calculated with a single gradient.

Also, bonus question, why i have that white lines as a border of my bars if i actually didn't specify any border at all (feels like aliasing svg issue)

Upvotes: 0

Views: 977

Answers (1)

Snick
Snick

Reputation: 1042

So, i managed to achieve that by doing

var color = d3.scale.linear()
.domain([0, width])
.range(["hsl(62,100%,90%)", "hsl(222,30%,20%)"]);

And later on, for each bar element append

.style("fill", function(d, i) {
  return color(i);
});

wonder if it's the fast way to do this

Upvotes: 2

Related Questions