Reputation: 931
I'm using code that can be found at:
https://www.d3-graph-gallery.com/graph/heatmap_basic.html
In particular, I want to change the following snippet of code:
// Build color scale
var myColor = d3.scaleLinear()
.range(["white", "#69b3a2"])
.domain([1,100])
So it accepts a color as an argument. My intention is to have a separate color for each row of the heat map. Is this possible?
Upvotes: 1
Views: 649
Reputation: 102174
Given what you described here:
My intention is to have a separate color for each row of the heat map.
I'm assuming that, for each row, you want a different range in the colour scale, going from "white"
to a specific colour.
If that is correct, you can simply set an array of colours, for instance...
var colorArray = d3.schemeCategory10;
//d3.schemeCategory10 is this array of colours:
//["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"]
... and then, using the myVars
array, set the scale range dynamically inside the anonymous function:
.style("fill", function(d) {
var thisColor = colorArray[myVars.indexOf(d.variable)]
myColor.range(["white", thisColor])
return myColor(d.value)
})
Here is the code you linked with that change:
// 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>
Upvotes: 1