D3地图图例问题

D3 map legend issue

我正在创建美国的人口地图。我有地图和图例,但我制作了一个下拉菜单,允许我按种族过滤。这有效并更改了地图和图例上的数据,但我遇到了一个问题,即图例文本显示新范围以及更改下拉菜单时的所有先前范围。有没有办法让它不与前面的文本重叠,而是只显示一个正确的文本?我正在使用 D3 和 React。

这是我图例的代码:

svg.append("g")
    .attr("transform", "translate(580,20)")
    .append(() => Legend(color, {title: `2019 Population (x10^${exp})`, width: 300,tickFormat: ".1f"}))

我的颜色变量的代码:

const color = d3.scaleQuantile([start/divider,end/divider], d3.schemeYlOrRd[9])

开始和结束的变化取决于人口规模

Edit/Update: 我找到了解决我的问题的方法,我只是不确定它是否是最佳实践,或者是否有另一种方法。我给了它一个背景颜色,这样以前的信息就被掩盖了

代码:

svg.append("g")
    .attr("transform", "translate(580,20)")
    .append(() => Legend(color, {title: `2019 Population (x10^${exp})`, width: 300,tickFormat: ".1f"}))
    .append("rect")
    .attr("width", "100%")
    .attr("height", "100%")
    .attr("fill", "grey")
    
    svg.append("g")
    .attr("transform", "translate(580,20)")
    .append(() => Legend(color, {title: `2019 Population (x10^${exp})`, width: 300,tickFormat: ".1f"}))

每次 svg.append('g').transform(...).append(() => Legend()) 都会添加一个新的 <g> 元素。

改为将 <g> 选择存储在变量中,然后在添加新图例之前删除其内容。

const legendG = svg.append('g').attr('transform', 'translate(580, 20)')

function renderLegend(legendOptions) {
  
  legendG.selectAll('*').remove() // removes everything inside 

  legendG.append(() => Legend(legendOptions))
}

// now call the `renderLegend` function every time you change something from the menu

并回答您的问题,看看您的做法是否良好。我会说它不是,因为每次用户在菜单中选择某些东西时你只是添加元素,它只是占用越来越多的内存来存储 DOM。不利于性能。