0
代碼.. jsfiddle
(function(d3) {
'use strict';
var dataset = [{
"colorName":"red",
"hexValue":"#f00"
},
{
"colorName":"green",
"hexValue":"#0f0"
},
{
"colorName":"blue",
"hexValue":"#00f"
},
{
"colorName":"cyan",
"hexValue":"#0ff"
},
{
"colorName":"magenta",
"hexValue":"#f0f"
},
{
"colorName":"yellow",
"hexValue":"#ff0"
},
{
"colorName":"black",
"hexValue":"#000"
}
]
var width = 360;
var height = 360;
var legendRectSize = 18; // NEW
var legendSpacing = 4; // NEW
var svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g');
var legend = svg.selectAll('.legend') // NEW
.data(dataset) // NEW
.enter() // NEW
.append('g') // NEW
.attr('class', 'legend') // NEW
.attr('transform', function(d, i) { // NEW
// var height = 0; // NEW
var horz = 100*i; // NEW
var vert = 6; // NEW
return 'translate(' + horz + ',' + vert + ')'; // NEW
}); // NEW
legend.append('rect') // NEW
.attr('width', legendRectSize) // NEW
.attr('height', legendRectSize) // NEW
.style('fill', function (d, i) {
return d.hexValue;
}) // NEW
.style('stroke', function (d, i) {
return d.hexValue;
}); // NEW
legend.append('text') // NEW
.attr('x', legendRectSize + legendSpacing) // NEW
.attr('y', legendRectSize - legendSpacing) // NEW
.text(function(d) {return d.colorName; }); // NEW
})(window.d3);
但它被削減關閉正確的尺寸。如果可用寬度小於圖例寬度,如何確保它進入下一行。
此外,我已經看過這個問題(How to create a horizontal legend with d3.js),但無法計算如何在我的情況下使用相同的。 如果有人能告訴我如何確保不會像在我的代碼中那樣硬編碼寬度(colorbox + text),那將會很棒。