javascript - 将数据从 JSON 导入 D3 并在饼图部分显示
问题描述
我有一个饼图出现在这里https://imgur.com/MDdUKsQ,试图重现此图像:https ://imgur.com/rNKtAUD
一直在努力让每个部分出现大百分比的标题。我曾考虑过制作 HTML 元素并长期进行,但最好从 JSON 文件中提取它们,如下所示。我将如何做到这一点?使用 D3 的 V6
JSON:
[
{"name": "Less than a month","total": 100,"Percent":1.39},
{"name": "1-3 months","total": 290,"Percent":20.83},
{"name": "3-6 months","total": 400,"Percent":56.94},
{"name": "6-12 months","total": 600,"Percent":5.56},
{"name": "More than 12 months","total": 300,"Percent":15.28},
{"name": "There won't be business as usual","total": 100,"Percent":15.28}
]
// get data from JSON
function getData() {
d3.json("./data/piedata.json", function(d) {return d}).then(drawPie)
}
getData()
//draw the pie chart
function drawPie(data) {
colourScale.domain(data.map(d=>d.name))
const angles = pie(data)
const paths = pieCanvas.selectAll("path").data(angles)
paths.enter().append("path").attr("d", arcPath).attr("class","arc")
.attr("stroke","white").attr("fill", d=>colourScale(d.data.name))
//add legend
const legend = svg.selectAll('.legend').data(colourScale.domain()).enter().append('g')
.attr('class', 'legend').attr('transform', function(d, i) {
const height = legendRectSize + legendSpacing
const offset = height * colourScale.domain().length / 3
const horz = 20 * legendRectSize
const vert = i * height - offset + 260
return 'translate(' + horz + ',' + vert + ')'});
legend.append('rect').attr('width', legendRectSize).attr('height', legendRectSize)
.style('fill', colourScale).style('stroke', colourScale)
legend.append('text').attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing).text(function(d) { return d })
}
解决方案
试试 d3.json("./data/piedata.json", function(d){ drawPie(d); })
推荐阅读
- javascript - 图像 DRUPAL7 在服务 3.0 上加密
- json - 使用 JOLT 从 JSON 中的数组中选择性地获取某些数组
- python - Matplotlib -3D 数据可视化
- spring-boot - 使用 Spring Security 登录失败
- javascript - 在我的 html css 和 javascript 代码中,单击“fas fa-bars”时不会打开菜单
- node.js - nodejs serialport检测Windows上cts pin的变化
- python - 使用 re.sub() 在 Python 中删除字母和逗号之间的数字
- postgresql - 通过 ssh 隧道设置 pglogical,由对等方重置连接
- angular - 角度RXJS如何转换订阅响应类型
- javascript - 当 exerciseName = 到 input[i] 时,executiveName 给了我与 input[i] 不同的输出(参见代码)