[英]D3 choropleth map with legend
我有一張顯示總人口的美國等值地圖。 我想在地圖上添加一個圖例來顯示分位數范圍值。我已經看到了關於這個主題的其他類似問題,但似乎無法讓它適用於我的特定情況。 我知道我需要包含顏色范圍或顏色域,但不確定這是否正確。 截至目前,圖例中只顯示了一個功能,可能是所有圖例功能都疊加在一起。 我怎么知道,我該如何解決這個問題。
//Define default colorbrewer scheme
var colorSchemeSelect = "Greens";
var colorScheme = colorbrewer[colorSchemeSelect];
//define default number of quantiles
var quantiles = 5;
//Define quantile scale to sort data values into buckets of color
var color = d3.scale.quantile()
.range(colorScheme[quantiles]);
d3.csv(data, function (data) {
color.domain([
d3.min(data, function (d) {
return d.value;
}),
d3.max(data, function (d
return d.value
})
]);
//legend
var legend = svg.selectAll('rect')
.data(color.domain().reverse())
.enter()
.append('rect')
.attr("x", width - 780)
.attr("y", function(d, i) {
return i * 20;
})
.attr("width", 10)
.attr("height", 10)
.style("fill", color);
如果您有一個序數比例 ,那么您正在使用的圖例代碼將非常有效,其中域由一對一基礎上與顏色范圍相關的離散值組成。 但是你使用的是分位數量表 ,因此需要采用不同的方法。
對於d3分位數標度 ,域是所有可能輸入值的列表,范圍是離散輸出值的列表。 域列表按升序排序,然后分成相等大小的組,這些組分配給范圍中的每個輸出值。 組的數量由輸出值的數量確定。
考慮到這一點,為了獲得每種顏色的一個圖例條目,您將需要使用顏色范圍的范圍而不是域作為圖例的數據。 然后,您可以使用quantileScale.invertExtent()
方法查找使用該顏色繪制的最小和最大輸入值。
示例代碼,使每個圖例條目為<g>
包含彩色矩形和顯示相應值的文本標簽。
var legend = svg.selectAll('g.legendEntry')
.data(color.range().reverse())
.enter()
.append('g').attr('class', 'legendEntry');
legend
.append('rect')
.attr("x", width - 780)
.attr("y", function(d, i) {
return i * 20;
})
.attr("width", 10)
.attr("height", 10)
.style("stroke", "black")
.style("stroke-width", 1)
.style("fill", function(d){return d;});
//the data objects are the fill colors
legend
.append('text')
.attr("x", width - 765) //leave 5 pixel space after the <rect>
.attr("y", function(d, i) {
return i * 20;
})
.attr("dy", "0.8em") //place text one line *below* the x,y point
.text(function(d,i) {
var extent = color.invertExtent(d);
//extent will be a two-element array, format it however you want:
var format = d3.format("0.2f");
return format(+extent[0]) + " - " + format(+extent[1]);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.