我有一个D3JS散点图,其数据源是MYSQL请求。 基本上数据点是(x,y,类别),类别可以是(A,B,C,D,E)。 有时,MySQL Select请求的类别为A或B。
没有任何意义但是,我希望所有类别都包含在我的图例中,无论数据源中表示的每个类别是否至少有一个点。
今天,我有以下代码用于点,其中颜色是" harcoded"确保分类" A"点总是#4a9b5b颜色(B,C,D E也一样):
// draw dots
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 7)
.attr("cx", xMap)
.attr("cy", yMap)
.style("fill", function(d) {
if (d.category == "A") {return "#4a9b5b"}
else if (d.category == "B") { return "#5caeb9" }
else if (d.category == "C") { return "#df4b4b" }
else if (d.category == "D") { return "#cb7e51" }
else { return "#ffffff" }
;})
. [ ... ]
以下传说[NOT WORKING]:
var legend = svg.selectAll(".legend")
.data(color.domain())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
// draw legend colored rectangles
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
// draw legend text
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d;});
我正在寻找类似点的东西,无论数据源是什么都有相同的图例,如:
Category A [#4a9b5b"]
Category B [#5caeb9"]
Category C [#df4b4b"]
Category D [#cb7e51"]
Category E [#ffffff"]
答案 0 :(得分:2)
这样做是为了制作色标:
Clear()
制作这样的传奇
//make color as re the possible domain
var color = d3.scale.ordinal()
.domain(["A", "B", "C", "D", "E"])
.range([#4a9b5b", "#5caeb9" , "#df4b4b", "#cb7e51", "#ffffff"]);
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 7)
.attr("cx", xMap)
.attr("cy", yMap)
.style("fill", function(d) {
return color(d.category);//no need for if now
;})
希望这有帮助!