如何在d3.js中为彩色图例添加刻​​度线

时间:2017-12-19 13:42:26

标签: d3.js legend

我在d3.js版本4中创建了一个平滑的颜色图例:https://www.visualcinnamon.com/2016/05/smooth-color-legend-d3-svg-gradient.html

现在,我想添加刻度线,显示从一种颜色到下一种颜色的值。我怎么做?我的代码是:

<svg id="svgLegend" width="160" height="30"></svg>

//define a horizontal gradient
var defs = svg.append("defs")
var linearGradient = defs.append("linearGradient")
    .attr("id", "linear-gradient");

//Draw the legend rectangle and fill with gradient
d3.select("#svgLegend").append("rect")
    .attr("width", 160)
            .attr("height", 20)
            .style("fill", "url(#linear-gradient)");

var color = d3.scaleLinear()
        .domain([valuesIn[0], ((valuesIn[0] * 2 + valuesIn[1]) / 3), valuesIn[1]])  // input uses min and max values
        .range(["white", "blue", "green", "yellow", "red"]);  

//append multiple color stops by using D3's data/enter stop
    linearGradient.selectAll("stop")
        .data(color.range())
        .enter().append("stop")
        .attr("offset", function (d, i) { return i / (color.range().length - 1); } )
        .attr("stop-color", function (d) { return d; })

1 个答案:

答案 0 :(得分:1)

解决了这个问题。以下是有效的代码片段:

<svg id="svgLegend" width="160" height="40"></svg>

//create a horizontal gradient
var defs = svg.append("defs")
var linearGradient = defs.append("linearGradient")
    .attr("id", "linear-gradient");

//Draw the legend rectangle and fill with gradient
d3.select("#svgLegend").append("rect")
    .attr("width", 160)
    .attr("height", 20)
    .style("fill", "url(#linear-gradient)");

var dataRange = [];
dataRange = getDataRange();

var min = dataRange[0];
var max = dataRange[1];

//create tick marks
var x = d3.scaleLinear()
    .domain([min, max])
    .range([0, 200]);

var axis = d3.axisBottom(x);

d3.select("#svgLegend")
        .attr("class", "axis")
        .attr("width", 160)
        .attr("height", 40)
    .append("g")
        .attr("id", "g-runoff")
        .attr("transform", "translate(0,20)")
        .call(axis);