首页 > 解决方案 > Colour regions by order they appear in array

问题描述

Using this git, I have https://codepen.io/anon/pen/xNWzpq

I am want to colour the regions based on the sequence they appear in my array. It is currently colouring regions based on number of occurrences in the source data:

var areas=["AB", "AL", "B", "BA", "BB", "BD", "BH", "BL", "BN", "BR", "BS", "BT", "CA", "CB", "CF", "CH", "CM", "CO", "CR", "CT", "CV", "CW", "DA", "DD", "DE", "DG", "DH", "DL", "DN", "DT", "DY", "E", "EC", "EH", "EN", "EX", "FK", "FY", "G", "GL", "GU", "HA", "HD", "HG", "HP", "HR", "HS", "HU", "HX", "IG", "IP", "IV", "KA", "KT", "KW", "KY", "L", "LA", "LD", "LE", "LL", "LN", "LS", "LU", "M", "ME", "MK", "ML", "N", "NE", "NG", "NN", "NP", "NR", "NW", "OL", "OX", "PA", "PE", "PH", "PL", "PO", "PR", "RG", "RH", "RM", "S", "SA", "SE", "SG", "SK", "SL", "SM", "SN", "SO", "SP", "SR", "SS", "ST", "SW", "SY", "TA", "TD", "TF", "TN", "TQ", "TR", "TS", "TW", "UB", "W", "WA", "WC", "WD", "WF", "WN", "WR", "WS", "WV", "YO", "ZE"];

var areadata={};

_.each(areas, function(a) {
  areadata[a]=a.charCodeAt(0);
});

What I want to do is, for example:

var areas=["AB", "AL", "B", "BA"];

where AB is the darkest and BA is the lightest, and any unlisted remain the default colour.

I have tried

_.each(areas, function(a) {
  areadata[areas]=areas.charCodeAt(0);
});

and

  color.domain(d3.extent(_.toArray(areas))); 

but I'm not sure how to match the array order to colours

标签: javascriptd3.js

解决方案


如果我正确理解您的问题,您所需要的只是每个元素的索引:

areas.forEach(function(a, i) {
    areadata[a]=i;
});

此外,由于您的颜色数组从最高颜色变为最暗颜色,因此您必须反转范围或域:

color.domain(d3.extent(_.toArray(areadata)).reverse()); 

这是分叉的 CodePen:https ://codepen.io/anon/pen/byvjRE


推荐阅读