向地图图例添加标签

时间:2018-08-15 19:21:24

标签: d3.js

我不太明白这一点。尝试修改: https://bl.ocks.org/duspviz-mit/9b6dce37101c30ab80d0bf378fe5e583

可以在栏的左侧添加低值,在右侧添加高值。如果有人能指出正确的方向或显示另一个示例,将不胜感激。

1 个答案:

答案 0 :(得分:0)

只需复制域边界的轴刻度。

使svg大一些以适合文本

<html>
<head>
<script src="https://d3js.org/d3.v4.js"></script>
<style type="text/css">
.axis text {
  font: 10px sans-serif;
}

.axis line, .axis path {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}
svg{
  padding-left: 50px;
}
</style>
</head>
<body>
  <div id="legend1"></div>
  <script type="text/javascript">
    var w = 300, h = 50;

    var key = d3.select("#legend1")
      .append("svg")
      .attr("width", w+100)
      .attr("height", h+50);

    var legend = key.append("defs")
      .append("svg:linearGradient")
      .attr("id", "gradient")
      .attr("x1", "0%")
      .attr("y1", "100%")
      .attr("x2", "100%")
      .attr("y2", "100%")
      .attr("spreadMethod", "pad");

    legend.append("stop")
      .attr("offset", "0%")
      .attr("stop-color", "#f7fcf0")
      .attr("stop-opacity", 1);

    legend.append("stop")
      .attr("offset", "33%")
      .attr("stop-color", "#bae4bc")
      .attr("stop-opacity", 1);

    legend.append("stop")
      .attr("offset", "66%")
      .attr("stop-color", "#7bccc4")
      .attr("stop-opacity", 1);

    legend.append("stop")
      .attr("offset", "100%")
      .attr("stop-color", "#084081")
      .attr("stop-opacity", 1);

    key.append("rect")
      .attr("width", w)
      .attr("height", h - 30)
      .style("fill", "url(#gradient)")
      .attr("transform", "translate(50,10)");

    var y = d3.scaleLinear()
      .range([300, 0])
      .domain([68, 12]);

    var yAxis = d3.axisBottom()
      .scale(y)
      .ticks(5);

    key.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(50,30)")
      .call(yAxis)
      .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", -30)
      .attr("dy", "0")
      .attr("dx", "0")
      .attr("fill", "#000")
      .style("text-anchor", "end")
      .text("axis title");
    var extras = key.select(".y.axis").selectAll(".dummy")
       .data(y.domain())
       .enter()
       .append("g")
       .attr("class", "tick")
       .attr("transform", d => `translate(${y(d)},0)` );
    extras.each( function (d) {
        d3.select(this).append("line").attr("stroke", "#000").attr("y2", 6);
        d3.select(this).append("text").attr("fill", "#000").attr("y", 9).attr("dy", "0.71em").text(d);
    });
    </script>
</body>
</html>