d3.js - d3 堆积条只更新 3 次
问题描述
我想要一个水平堆积条更新 3 次以上。我使用的不是随机数据,而是实际数据。我有 60 年的数据。这个例子有四个,但它只会更新 3 年。
它使用 data.filter,但是当我尝试使用 ++years 时,它不会更新条形图。它只会说 stack.exit 不是一个函数。
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500)
var data = [
{ year: 2005, bananas: [10, 20, 30, 20], apples: [20, 10, 30, 10], pears: [30, 10, 20, 50] },
{ year: 2006, bananas: [30, 40, 20, 30], apples: [30, 30, 40, 20], pears: [40, 20, 30, 50] },
{ year: 2007, bananas: [50, 50, 30, 40], apples: [40, 40, 50, 30], pears: [50, 30, 40, 50] },
{ year: 2008, bananas: [70, 60, 30, 50], apples: [50, 50, 60, 40], pears: [60, 40, 50, 50] }
];
const BAR_HEIGHT = 50
const FRUITS = ['bananas', 'apples', 'pears']
const COLORS = ['#21CD69', '#f8bc29', '#fb4848', '#ccc']
svg.selectAll('g.stack')
.data(FRUITS)
.enter().append('g')
.attr('class', 'stack')
.attr('transform', (d, i) => `translate(0, ${i * (BAR_HEIGHT + 10)})`)
function update (year) {
var filteredData = data.filter(i => i.year === year)[0]
svg.selectAll('g.stack').nodes()
.forEach((node, i) => {
const fruitName = FRUITS[i]
const t = d3.transition().duration(1000)
const stack = d3.select(node)
.selectAll('rect')
.data(filteredData[fruitName], d => d)
stack.exit()
.transition(t)
.attr('width', 0)
.remove()
let x = 0
stack.enter().append('rect')
.attr('y', 0)
.attr('height', BAR_HEIGHT)
.merge(stack)
.attr('fill', (d, i) => COLORS[i])
.transition(t)
.attr('x', (d, i) => {
const retX = x
x += d * 5
return retX
})
.attr('width', d => d * 5)
})
}
let year = 2005
let inc = 0
update(year)
setInterval(() => {
inc = (inc + 1) % 3
update(year + inc)
}, 2000)
</script>
</body>
使用不同数据更新多达 60 次的堆叠条形图
解决方案
推荐阅读
- javascript - 坚持尝试复制某个 CSS 转换(向下滚动时移动到页面底角并得到修复的 CTA 按钮)
- python - seaborn和plotly中密度等高线图的差异
- php - Sendgrid 电子邮件批量无法发送 PHP
- laravel - 如何在 Laravel 中使用 SwiftMailer 获取 SMTP 会话错误
- c++ - 为什么有些例子使用“endl”而不是“\n”?
- python - Python Flask getlist of checkboxes返回空列表
- google-analytics - 如何在 Measurement Protocol 中设置用户代理(Google Analytics 4)
- html - 如何使用 html div 和 css 制作形状
- visual-studio-2015 - 将 VS2015 迁移到 VS2019 参考缺失
- php - 为什么我会在批量删除中获得 DataProvider\Document 实例?