SVG图例:未显示行

问题描述

我正在使用d3-svg-legend(https://d3-legend.susielu.com/)根据尺寸创建图例。我想复制此示例:https://d3-legend.susielu.com/#size-line

我使用的代码是:

library(stringi)

stri_locate_overlap <- function(str,pattern) {
  s <- stri_locate_all_regex(str,paste0("(?=",pattern,")")) # match start,length 0
  e <- stri_locate_all_regex(str,paste0("(?<=",")")) # match end,length 0
  # combine two results
  mapply(function(x,y) {
    data.frame(start = x[,1],end = y[,1])
  },x = s,y = e,SIMPLIFY = FALSE)
}

stri_locate_overlap(c("---","-1-"),"[1|-]{2}")
#> [[1]]
#>   start end
#> 1     1   3
#> 2     2   4
#> 
#> [[2]]
#>   start end
#> 1     1   3
#> 2     2   4

代码产生以下输出

let svg = d3.select(this.refs.canvas).append('svg');
const g = svg.append("g");

var linesize = d3.scaleLinear().domain([0,10]).range([2,10]);

g.attr("transform","translate(20,20)")
  .call(legendSize()
  .scale(linesize)
  .shape("line")
  .orient("horizontal")
  .shapeWidth(40)
  .labelAlign("start")
  .shapePadding(10)
  );

但是除了标签外,它不显示任何图例(即,不显示线元素):

Code output

解决方法

如果您查看相同的示例,您会发现她正在使用<style>中的<head>标签设置笔画:

.legendSizeLine line {
  stroke: rgb(46,73,123);
}

这是必要的,因为默认的<line>笔划是"none"

这是您使用该样式的SVG:

line {
  stroke: rgb(46,123);
}

text {
  font: 12px sans-serif;
}
<div style="margin-left: auto; margin-right: 20px;">
  <svg>
    <g transform="translate(20,20)">
      <g class="legendCells">
        <g class="cell" transform="translate(0,5)">
          <line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="2" style="fill: rgb(153,216,201);"></line>
          <text class="label" transform="translate( 0,15)" style="text-anchor: start;">0.0</text>
        </g>
        <g class="cell" transform="translate(50,5)">
          <line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="4" style="fill: rgb(211,74,65);"></line>
          <text class="label" transform="translate( 0,15)" style="text-anchor: start;">2.5</text>
        </g>
        <g class="cell" transform="translate(100,5)">
          <line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="6" style="fill: rgb(255,0);"></line>
          <text class="label" transform="translate( 0,15)" style="text-anchor: start;">5.0</text>
        </g>
        <g class="cell" transform="translate(150,5)">
          <line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="8" style="fill: rgb(255,15)" style="text-anchor: start;">7.5</text>
        </g>
        <g class="cell" transform="translate(200,5)">
          <line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="10" style="fill: rgb(255,15)" style="text-anchor: start;">10.0</text>
        </g>
      </g>
    </g>
  </svg>
</div>