javascript - 基于数组值的d3动态url
问题描述
我正在尝试使用 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+`)`)
;
这段代码的问题是我得到了网址中的所有国家。我只想要json数组中每个值对应的国家。
这是数据数组:
data = d3.json('data.json')
.then(data => {data
.forEach(d => {
d.country = d.country;
d.population = +d.population * 1000;
});
render(data);
});
我也尝试过编写一个函数,但是因为我对此很陌生,所以我无法弄清楚。谢谢大家。
解决方案
谢谢穆塔。这就是我最终做的事情,它似乎工作正常:
数据:
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)
;
推荐阅读
- java - Why the below pattern matching is giving True for the String "ababx300000055773908"
- r - Teradata QVCI 功能已禁用
- uno - Uno 不适用于现有的 PCL 项目。.NetStandar 2.0 出现 uwp 错误
- python - 在 pyspark 中出现相同的字数 -
- sql-server - 使用另一个表中去年的计算更新列
- c++ - C++ 中的堆栈程序
- google-app-engine - Google Stackdriver Profling:如何理解此配置文件
- r - 使用 stat_density2d 显示计数而不是“级别”
- bash - 为什么我的脚本 sed 命令在命令行中运行良好但失败了
- scala - 如何重命名 Scala 中由 count() 函数生成的列