javascript - 如何在 HTML/D3 代码中对数据进行排序
问题描述
我的问题是如何在下面显示的 HTML/D3 代码中对数据进行排序。我用 Python 编写代码,而 HTML/CSS 对我来说是新的。我有以下代码,我正在准备里面的数据,我该如何对这些数据进行排序。不考虑和不照顾标签。我只想对数据进行排序。我怎样才能做到这一点。非常感谢。我正在学习这个。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Sorting visual elements</title>
<script src="//d3js.org/d3.v5.min.js" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
//Width and height
var w = 600;
var h = 250;
var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
var xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.rangeRound([0, w])
.paddingInner(0.05);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset)])
.range([0, h]);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create bars
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d,i) => xScale(i) )
.attr("y", d => h - yScale(d) )
.attr("width", xScale.bandwidth())
.attr("height", d => yScale(d) )
.attr("fill", d => "rgb(0, 0, " + (d * 10) + ")" )
.on("mouseover", function() {
d3.select(this)
.attr("fill", "orange");
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(250)
.attr("fill", "rgb(0, 0, " + (d * 10) + ")")
})
.on("click", () => sortBars() );
//Create labels
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d)
.attr("text-anchor", "middle")
.attr("x", (d, i) => xScale(i) + xScale.bandwidth() / 2)
.attr("y", d => h - yScale(d) + 14 )
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
//Define sort function
var sortBars = function() {
svg.selectAll("rect")
.sort((a, b) => d3.ascending(a, b) )
.transition()
.duration(1000)
.attr("x", (d, i) => xScale(i) );
};
</script>
</body>
</html>
解决方案
推荐阅读
- python - 从 MarketWatch 获取数据
- c# - How to Convert User input to Encoder value type
- swift - 如何检查屏幕是否有关联的扬声器
- javascript - 如何正确地将jquery div附加到html
- flutter - 如何在flutter中实现循环页面动画
- javascript - 数据表未对齐,直到以模态排序
- javascript - 将此传递给子函数
- python - 由于数据值似乎太小,无法使用 lmfit 拟合高斯拟合
- macos - .zshrc JAVA_HOME 在新终端上返回空白,但在显式源 mac OS (catalina) 时有效
- php - 使用 firebird 中的外部数据库更新 wordpress 数据库