我正在使用 d3.js 中的一些代码在 html 页面中动态构建单元格表。因此,如果它是 5x5 .csv 报告,它将在页面上生成 5x5 等。
此报告用于监控我们的某些机器,因此如果数值在一定范围内,我想分别显示绿色、黄色或红色表示良好、警告或严重。
这是一个每小时生成的 .csv 报告,将从早上 6 点到下午 6 点监控我们的机器。数值反射(reflect)了我们是否要显示绿色、黄色或红色。
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js">
</script>
<script src="d3.min.js?v=3.2.8">
</script>
<meta content="30" http-equiv="refresh">
<title></title>
</head>
<body>
<script>
d3.text("myCSV.csv", function(data) {
var parsedCSV = d3.csv.parseRows(data);
var container = d3.select("body")
.append("table")
.selectAll("tr")
.data(parsedCSV).enter()
.append("tr")
.selectAll("td")
.data(function(d) { return d; }).enter()
.append("td")
.text(function(d) { return d; });
});
</script>
</body>
</html>
出于概念目的,我们的报告如下所示:
最佳答案
我建议您使用阈值范围,其中:
are similar to quantize scales, except they allow you to map arbitrary subsets of the domain to discrete values in the range. The input domain is still continuous, and divided into slices based on a set of threshold values. The input domain is typically a dimension of the data that you want to visualize, such as the height of students (measured in meters) in a sample population. The output range is typically a dimension of the desired output visualization, such as a set of colors (represented as strings).
所以,如果你这样做:
var colorScale = d3.scale.threshold()
.domain([30, 70])
.range(["red", "yellow", "green"]);
您将创建一个比例,如果值小于 30,则返回“红色”;如果值在 30 到 70 之间,则返回“黄色”;如果值超过 70,则返回“绿色”。
然后,你会:
.style("background-color", function(d){
return colorScale(d);
})
查看这个演示(我使用的是我自己的表格代码,与你的有点不同,但原理是相同的):
var parsedCSV = d3.csv.parse(d3.select("#csv").text());
var colorScale = d3.scale.threshold()
.domain([30, 70])
.range(["red", "yellow", "green"]);
var body = d3.select("body");
var headers = Object.keys(parsedCSV[0]);
var table = body.append('table')
var thead = table.append('thead')
var tbody = table.append('tbody');
var head = thead.selectAll('th')
.data(headers)
.enter()
.append('th')
.text(function(d) {
return d;
});
var rows = tbody.selectAll('tr')
.data(parsedCSV)
.enter()
.append('tr');
var cells = rows.selectAll('td')
.data(function(d) {
return Object.values(d);
})
.enter()
.append('td')
.style("background-color", function(d) {
return colorScale(d);
})
.text(function(d) {
return d;
});
pre {
display: none;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td,th {
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<pre id="csv">foo,bar,baz
32,55,67
12,34,99
11,21,32
11,65,76
99,14,23</pre>
关于javascript - 如何根据 .csv 报告中的数值以及动态创建表格时更改表格单元格颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41147934/