【问题标题】:d3 dynamic url based on array values基于数组值的d3动态url
【发布时间】:2020-05-18 22:54:24
【问题描述】:

我正在尝试使用 D3 将图像 URL 附加到 SVG 元素。我试过各种代码,包括这个。

svg.append('g')
.selectAll('image')
.data(data)
.enter()
.append('image')
.attr('class', 'countryflag')
.attr('href', `https://www.musiktrends.com/images/countryflags/`

+ 
data.map(yValues)
+
`.png`)

.attr('width', 50)
.attr('height', barHeight)
.attr('x', 0)
.attr('y', yPos)
.attr(`transform', `translate(5,`+0+`)`)
;

此代码的问题是我在 url 中获取了所有国家/地区。我只想要json数组中每个值对应的国家。

这是数据数组:

data = d3.json('data.json')
.then(data => {data
.forEach(d => {
d.country = d.country;
d.population = +d.population * 1000;
});
render(data);
});

我也尝试过编写一个函数,但因为我在这方面相当陌生,所以我无法弄清楚。提前谢谢大家。

【问题讨论】:

    标签: javascript arrays d3.js dynamic-url


    【解决方案1】:

    谢谢穆塔。这就是我最终做的,它似乎工作正常:

    数据:

    data = d3.json('data.json')
    .then(data => {data
    .forEach(d => {
        d.country = d.country;
      d.population = +d.population * 1000;
      d.flagurl = `../images/countryflags/`+d.country+`.png`;
    });
    
    console.log(data);
    render(data);
    });
    
    const yPos = d => yScale(yValues(d));
    

    图片

    svg.append('g')
    .selectAll('image')
    .data(data)
    .enter()
    .append('image')
    .attr('class', 'countryflag')
    
    .attr('href', d => (d.flagurl))
    
    .attr('width', 50)
    .attr('height', 0.8*barHeight)
    .attr('x', 0)
    .attr('y', yPos)
    .attr('opacity', 0)
    .attr('transform', `translate(`+0.05*barHeight+`,`+0.1*barHeight+`)`)
    
    // transition and delay         
    .transition()
    //.attr ('y', yPos)
    .attr ('opacity', 1)
    //.attr('height', yScale.bandwidth())
    
    .duration(animateDuration-625)
    .delay(delay+animateDuration+375)
    ;
    

    【讨论】:

      【解决方案2】:

      要构建标志 URL,您将函数 yValues 映射到 data 数组。你能展示一下它在做什么吗?

      如果您想要一个 pre 国家/地区的 URL,则不应在 URL 构建中使用 .map,而应围绕整个 svg. ... 调用进行循环。

      另外,请注意,在 .attr(`transform', `translate(5,`+0+`)`) 上,您在 transform 周围使用了不同类型的引号。

      【讨论】:

        猜你喜欢
        • 2014-09-12
        • 2021-09-29
        • 1970-01-01
        • 2021-05-23
        • 2017-12-30
        • 2020-08-03
        • 2018-09-08
        • 1970-01-01
        • 2013-01-28
        相关资源
        最近更新 更多