【问题标题】:How to add tick marks to color legend in d3.js如何在 d3.js 中为颜色图例添加刻​​度线
【发布时间】:2018-06-01 23:14:41
【问题描述】:

我在 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; })

【问题讨论】:

    标签: d3.js legend


    【解决方案1】:

    解决了这个问题。以下是有效的代码 sn-p:

    <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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      相关资源
      最近更新 更多