我需要为这个简单的多条形图添加一个图例,例如
我尝试添加一个传奇,就像在垂直条形图中一样。但我不能。
jQuery(function($) {
var names = ['John', 'Tim', 'Sam', 'Greg', 'Charles'],
hotdogs = [8, 4, 9, 12, 11],
chart,
width = 400,
bar_height = 20,
height = bar_height * names.length;
var x, y;
x = d3.scale.linear()
.domain([0, d3.max(hotdogs)])
.range([0, width]);
y = d3.scale.ordinal()
.domain(hotdogs)
.rangeBands([0, height]);
var color = d3.scale.category10();
var left_width = 100;
var gap = 2;
y = d3.scale.ordinal()
.domain(hotdogs)
.rangeBands([0, (bar_height + 2 * gap) * names.length]);
chart = d3.select($("#step-5")[0])
.append('svg')
.attr('class', 'chart')
.attr('width', left_width + width + 40)
.attr('height', (bar_height + gap * 2) * names.length + 30)
.append("g")
.attr("transform", "translate(10, 20)");
chart.selectAll("line")
.data(x.ticks(d3.max(hotdogs)))
.enter().append("line")
.attr("x1", function(d) { return x(d) + left_width; })
.attr("x2", function(d) { return x(d) + left_width; })
.attr("y1", 0)
.attr("y2", (bar_height + gap * 2) * names.length);
chart.selectAll("rect")
.data(hotdogs)
.enter().append("rect")
.attr("x", left_width)
.attr("y", function(d) { return y(d) + gap; })
.attr("width", x)
.attr("height", bar_height)
.style('fill', function(d) {
return color(d);
});
我如何添加一个图例,它代表颜色及其包含的数据?任何帮助表示赞赏。感谢