[英]How can I set the background color of a svg element which contains a D3 heat map?
我正在構建一個熱圖,其中顯示了該帳戶在一周內的推文活動。 我的數據集由一系列字典組成,其中包含工作日,小時以及工作日+小時組合重復多少次的計數。 由於通常人們在晚上不發推文,因此數據集中不存在某些平日+小時組合。 我的問題是,當我繪制矩形時,只能為現有組合繪制它們,而不存在的組合則保持空白。 這是結果的鏈接,希望可以使事情更清楚:
如您所見,在凌晨2:00至8:00之間有空白。
我不知道如何解決這個問題,但是我想我可以給整個熱圖賦予白色背景,然后再對包含現有組合的矩形着色,以使不存在的矩形變為白色而不是空白。 我怎樣才能做到這一點? 如果這不可能,那么我的問題是否還有其他解決方案?
這是我的代碼:
[var data = timestamps_final;
var days = \["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"\], times = \["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"\];
var margin = { top: 40, right: 50, bottom: 40, left: 50 };
var w = Math.max(Math.min(window.innerWidth, 1000), 500) - margin.left - margin.right - 20,ngridSize = Math.floor(w / times.length), h = gridSize * (days.length + 2);
var svg = d3.select("#heat_map")
.append("svg")
.attr("width", w + margin.top + margin.bottom)
.attr("height", h + margin.left + margin.right)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var colours = d3.scaleLinear()
.range(\["#F0C881", "#F244C7", "#173490",\])
.domain(\[1, 50, 100\]);
var dayLabels = svg.selectAll(".dayLabel")
.data(days)
.enter()
.append("text")
.text(function (d) { return d; })
.attr("x", 0)
.attr("y", function (d, i) { return i * gridSize; })
.style("text-anchor", "end")
.style('fill', 'white')
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
var timeLabels = svg.selectAll(".timeLabel")
.data(times)
.enter()
.append("text")
.text(function (d) { return d; })
.attr("x", function (d, i) { return i * gridSize; })
.attr("y", 0)
.style("text-anchor", "middle")
.style('fill', 'white')
.attr("transform", "translate(" + gridSize / 2 + ", -6)");
var rectangles = svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function (d) { return d.hour * 36; })
.attr("y", function (d) { return d.weekday * 36; })
.attr("width", 36)
.attr("height", 36)
.style("stroke-width", 1)
.style("stroke", "white")
.style("fill", function (d) { return colours(d.value); });
謝謝您的幫助。
在添加周+小時rect
之前先添加一個大白色rect
svg.append("rect")
.style("fill", "white")
.attr("width", 36 * 24)
.attr("height", 36 * 7);
var rectangles = svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function (d) { return d.hour * 36; })
.attr("y", function (d) { return d.weekday * 36; })
.attr("width", 36)
.attr("height", 36)
.style("stroke-width", 1)
.style("stroke", "white")
.style("fill", function (d) { return colours(d.value); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.