我使用的代码可以在以下位置找到:
https://www.d3-graph-gallery.com/graph/heatmap_basic.html
特别是,我想更改以下代码段:
// Build color scale
var myColor = d3.scaleLinear()
.range(["white", "#69b3a2"])
.domain([1,100])
因此它接受颜色作为参数。我的意图是为热图的每一行使用单独的颜色。这可能吗?
答案 0 :(得分:1)
给出您在此处的描述:
我的目的是为热图的每一行使用单独的颜色。
我假设对于每一行,您想要的色阶范围从"white"
到特定颜色。
如果这是正确的,那么您可以简单地设置一系列颜色,例如...
var colorArray = d3.schemeCategory10;
//d3.schemeCategory10 is this array of colours:
//["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"]
...,然后使用myVars
数组在匿名函数内部动态设置缩放范围:
.style("fill", function(d) {
var thisColor = colorArray[myVars.indexOf(d.variable)]
myColor.range(["white", thisColor])
return myColor(d.value)
})
这是与该更改链接的代码:
// set the dimensions and margins of the graph
var margin = {
top: 30,
right: 30,
bottom: 30,
left: 30
},
width = 450 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Labels of row and columns
var myGroups = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
var myVars = ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10"]
// Build X scales and axis:
var x = d3.scaleBand()
.range([0, width])
.domain(myGroups)
.padding(0.01);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
// Build X scales and axis:
var y = d3.scaleBand()
.range([height, 0])
.domain(myVars)
.padding(0.01);
svg.append("g")
.call(d3.axisLeft(y));
var colorArray = d3.schemeCategory10;
// Build color scale
var myColor = d3.scaleLinear()
.domain([1, 100])
//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/heatmap_data.csv", function(data) {
svg.selectAll()
.data(data, function(d) {
return d.group + ':' + d.variable;
})
.enter()
.append("rect")
.attr("x", function(d) {
return x(d.group)
})
.attr("y", function(d) {
return y(d.variable)
})
.attr("width", x.bandwidth())
.attr("height", y.bandwidth())
.style("fill", function(d) {
var thisColor = colorArray[myVars.indexOf(d.variable)]
myColor.range(["white", thisColor])
return myColor(d.value)
})
})
<script src="https://d3js.org/d3.v4.js"></script>
<div id="my_dataviz"></div>