d3.js 如何在不旋转图例的情况下创建垂直连续图例

wkftcu5l  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(89)

我已经使用线性渐变创建了水平连续图例。但是我的图例可以是水平的也可以是垂直的,这取决于旗帜。我如何才能使相同的图例垂直,但我不想旋转它,因为它占用了太多的空间。

const svgLegend = select(divRef.current).append("svg")
const defs = svgLegend.append("defs")
const linearGradient = defs
.append("linearGradient")
.attr("id", "linear-gradient")
.attr("x1", "0%")
.attr("x2", "100%") //since it's a horizontal linear gradient
.attr("y2", "0%");

//其他代码添加颜色

svgLegend
.append("rect")
.attr("x", 25)
.attr("y", 30)
.attr("width", 250)
.attr("height", 25)
.style("fill", "url(#linear-gradient)");

const xLeg = scaleLinear().domain([min, max]).range([10, 258]);
const axisLeg = axisBottom(xLeg).tickValues(colorScale.domain());
svgLegend
.attr("class", "axis")
.append("g")
.attr("transform", "translate(15, 55)")
.style("font-size", "10px")
.style("font-weight", "700")
.call(axisLeg);

小提琴链接:https://jsfiddle.net/r1t60ges/3/
所需输出:

os8fio9y

os8fio9y1#

<div id="container">
  <svg class="axis" style="background-color: rgba(255, 255, 255, 0.8); border-radius: 5px;">
    <defs>
        <linearGradient id="linear-gradient" x1="0%" x2="0%" y1="0%" y2="100%">
            <stop offset="0%" stop-color="#ff0000"></stop>
            <stop offset="25%" stop-color="#ffff00"></stop><stop offset="50%" stop-color="#00ff00"></stop>
            <stop offset="75%" stop-color="#00ffff"></stop><stop offset="100%" stop-color="#0000ff"></stop>
        </linearGradient></defs>
        <text class="legendTitle" x="25" y="10">Legend</text>
        <rect x="25" y="20" width="25" height="150" style="fill: url(&quot;#linear-gradient&quot;);"></rect>
          <g transform="translate(15, 55)" fill="none" font-size="10" font-family="sans-serif" text-anchor="middle" style="font-size: 10px; font-weight: 700;">
</svg>
</div>

相关问题