I want to add legend in my chart in a single line using rect
and text
. It has four items. I tried with the below code. But it displays each item line by line only.
var ChartId = '#' Id;
var LegendId = '#' Id 'Legend';
var size = 20;
var color = d3.scaleOrdinal()
.range(['#1A9AD4', '#10B981', '#F59E0B',
'#EF4444', '#bf6fe7', '#eb5b5b', '#607d8b',
'#80B300', '#809900', '#E6B3B3', '#6680B3', '#66991A',
'#FF99E6', '#CCFF1A', '#FF1A66', '#E6331A', '#33FFCC',
'#66994D', '#B366CC', '#4D8000', '#B33300', '#CC80CC',
'#66664D', '#991AFF', '#E666FF', '#4DB3FF', '#1AB399',
'#E666B3', '#33991A', '#CC9999', '#B3B31A', '#00E680',
'#4D8066', '#809980', '#E6FF80', '#1AFF33', '#999933',
'#FF3380', '#CCCC00', '#66E64D', '#4D80CC', '#9900B3',
'#E64D66', '#4DB380', '#FF4D4D', '#99E6E6', '#6666FF'
]);
$(LegendId).remove();
$(ChartId).parent().append('<div id="' Id 'Legend" style="width:15%"></div>');
var StatusAccessor = function (d) {
return d.key[1];
}
var filteredData = Grps; //.all();
var Status = d3.set(filteredData.map(StatusAccessor)).values();
var svg2 = d3.select(LegendId)
.append("svg")
.attr("width", 140)
.attr("height", 250);
var legend = svg2.selectAll(".legend")
.data(SortInOrder(Status.slice().reverse(), SortArray))
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) { return "translate(5," i * 22 ")"; });
legend.append("rect")
.attr("x", 2)
.attr("y", 10) // 100 is where the first dot appears. 25 is the distance between dots
.attr("width", size)
.attr("height", size)
.style("fill", function (d) { return color(d) })
legend.append("text")
.attr("x", 28)
.attr("y", 19) // 100 is where the first dot appears. 25 is the distance between dots
//.style("fill", function (d) { return color(d) })
.text(function (d) { return d.replace(/ *\([^)]*\) */g, "") })
.attr("text-anchor", "left")
.style("alignment-baseline", "middle")
I tried below style. Still it's not working.
.legend {
display: inline-block !important;
margin-left: 5px;
margin-right: 5px;
cursor: pointer;
}
CodePudding user response:
We can adjust translate()
as below to make it in a single line:
var legend = svg2.selectAll(".legend")
.data(SortInOrder(Status.slice().reverse(), SortArray))
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) {
if (d == "Alert Task")
return "translate(" i * 143 ", 0 )";
else
return "translate(" i * 100 ", 0 )";
});