JSFiddle - React, Tailwind, and code Playground
HTML
<div id="legend"></div>
CSS
body { font: 12px Arial;}
JavaScript
var width = 600;
var margin = {
top: 20,
right: 60,
bottom: 30,
left: 20
};
var legendData = [{
"color": "blue",
text: "Normal Distribution"
}, {
color: "green",
text: " Ave A"
}, {
color: "red",
text: "Ave B"
}]
var svg = d3.select("#legend").append("svg")
var legendBox = svg.selectAll("g legends")
.data(legendData)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(" + ((parseFloat(i) * 110) + margin.left) + ",20)"
})
var circles = legendBox.append("circle")
.attr("r", 5)
.attr("stroke", "black")
.attr("fill", function (d, i) {
return d.color
})
legendBox.append("text")
.attr("dx", function (d) {
return 10
})
.attr("dy", function (d) {
return 5
})
.attr("fill", "black")
.text(function (d) {
return d.text
})
var x_offset = 0;
svg.selectAll("g")
.attr("transform", function (d, i) {
var x_pos = d3.select(this).select("text").node().getComputedTextLength() + 20;
x_offset = x_offset + x_pos;
return "translate(" + (x_offset - x_pos + margin.left) + ", 20)"
})