【发布时间】:2021-01-13 21:37:23
【问题描述】:
我使用的这个图表会自动为我创建的图例提供颜色,但是如果我想指定哪些颜色应该是特定键或值的一部分怎么办。例如,A 应该是绿色,B 应该是橙色。
// select the svg area
var SVG = d3.select("#my_dataviz4")
// create a list of keys
var keys = ["A", "B", "C", "D"]
// Usually you have a color scale in your chart already
var color = d3.scaleOrdinal()
.domain(keys)
.range(d3.schemeSet1);
//var color = ["yellow", "red", "blue", "green"]
// Add one dot in the legend for each name.
var size = 20
SVG.selectAll("mydots")
.data(keys)
.enter()
.append("rect")
.attr("x", 100)
.attr("y", function(d, i) {
return 100 + i * (size + 5)
}) // 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)
})
// Add one dot in the legend for each name.
SVG.selectAll("mylabels")
.data(keys)
.enter()
.append("text")
.attr("x", 100 + size * 1.2)
.attr("y", function(d, i) {
return 100 + i * (size + 5) + (size / 2)
}) // 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
})
.attr("text-anchor", "left")
.style("alignment-baseline", "middle")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<svg id="my_dataviz4" width="550" height="500"></svg>
【问题讨论】:
标签: javascript html css d3.js