Как объединить цветовое кодирование в Vega-Lite Choropleth Map (geoshape) с помощью transform.lookup, используя JavaScript - PullRequest
1 голос
/ 04 мая 2020

Я пытаюсь агрегировать цветовую кодировку в Vega-lite Choropleth map, используя JavaScript.

Я сделал рабочий пример, чтобы было легче помочь и понять

Минимальный код:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "width": 600,
  "height": 500,
  "mark": "geoshape",
  "data": {
    "url": "https://gist.githubusercontent.com/benooghe/95c8b4d63f67f1856fdd81e6303c654e/raw/8ec1fdd91bfbf4973f97ffb8a5daacb8f431908e/geo_belgium.json",
    "format": {"type": "topojson", "feature": "data"}
  },
  "encoding": {
    "color": {
      "field": "properties.nis_code", 
      "type": "quantitative", 
      // "aggregate":"sum"               // <-- THIS BREAKS THE MAP
    }
  }
}

Это упрощенная версия, она работает, но если вы добавите , "aggregate: "sum" в encoding.color, он больше не будет работать.

В случае, если я слишком упрощу, моя полная карта будет немного сложнее: она имеет transform.lookup.

  let yourVlSpec = {
    "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
    "width": 600,
    "height": 500,
    "mark": "geoshape",
    "data": { // TOPOJSON DATA -----
      "url": 'geo_belgium.json',
      "format": {
        "type": "topojson",
        "feature": "data"
      }
    },
    "transform": [{ // LEFT JOIN DATA -----
      "lookup": "properties.nis_code",
      "from": {
        "data": {
          "url": "data.csv"
        },
        "key": "NIS5",
        "fields": ["Cases", "Deaths"]
      }
    }],
    "encoding": {
      "color": {
        "field": "Cases",
        "type": "quantitative",
        // "aggregate": "sum"      // <-- THIS BREAKS THE MAP
      }
    }
  };
  vegaEmbed('#vis', yourVlSpec);

РЕДАКТИРОВАТЬ: Я также попробовал это: в transform

"aggregate": [{"op": "sum", "field": 'Cases', "as": 'sum_cases'}],

EDIT2: данные в data.csv выглядят так:

Date,PostCode,Cases,Deaths,NIS5
2020-04-08,2470,1,,13036
2020-04-08,2430,1,,13053
2020-04-08,1457,1,,25124
2020-04-08,3212,1,,24066
2020-04-08,2400,1,,13025
2020-04-08,1651,1,,23003
2020-04-08,2360,1,,13031
2020-04-07,1070,22,12,21004
2020-04-07,1070,22,12,21001
2020-04-07,4000,24,11,62093
2020-04-07,4000,24,11,62063
2020-04-01,9320,1,,41002
2020-04-01,7380,1,,53068
2020-04-01,9308,1,,41002
2020-03-31,1070,34,7,21004
2020-03-31,1070,34,7,21001
2020-03-31,3500,7,7,71022
2020-03-31,3800,10,5,71053
2020-03-31,4000,28,4,62063
2020-03-31,4000,28,4,62093

Я ищу график для суммы "Случаев" для "NIS5", суммируя все Сроки

1 Ответ

0 голосов
/ 04 мая 2020

Когда вы express получаете сумму как часть кодировки, она группируется по всем другим полям кодирования. В вашем случае нет других полей кодирования, поэтому он объединяет все и выбрасывает геометрию.

Один из способов обойти это - добавить соответствующие поля в кодировку detail , чтобы агрегация не удаляла их из данных ( vega editor ):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "width": 600,
  "height": 500,
  "mark": "geoshape",
  "data": {
    "url": "https://gist.githubusercontent.com/benooghe/95c8b4d63f67f1856fdd81e6303c654e/raw/8ec1fdd91bfbf4973f97ffb8a5daacb8f431908e/geo_belgium.json",
    "format": {"type": "topojson", "feature": "data"}
  },
  "encoding": {
    "color": {"field": "properties.nis_code", "type": "quantitative", "aggregate": "sum"},
    "detail": [{"field": "geometry", "type": "nominal"}, {"field": "properties.id", "type": "nominal"}, {"field": "type", "type": "nominal"}]
  }
}

Однако в вашем случае это то же самое, что и исходная неагрегированная диаграмма, поскольку одна nis_code для каждой географической области c.

Если вы хотите сгруппировать по области, отличной от геометрической c области, лучший способ сделать это - использовать преобразование joinaggregate (которое не удаляйте безымянные поля) и группируйте по конкретным данным, по которым вас интересует группировка. Например, вот сумма nis_code, сгруппированная по функции level_2 ( редактор Vega ):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "width": 600,
  "height": 500,
  "mark": "geoshape",
  "data": {
    "url": "https://gist.githubusercontent.com/benooghe/95c8b4d63f67f1856fdd81e6303c654e/raw/8ec1fdd91bfbf4973f97ffb8a5daacb8f431908e/geo_belgium.json",
    "format": {"type": "topojson", "feature": "data"}
  },
  "transform" : [{
    "joinaggregate": [{"field": "properties.nis_code", "op": "sum", "as": "sum_nis_code"}],
    "groupby": ["properties.level_2"]
  }],
  "encoding": {
    "color": {"field": "sum_nis_code", "type": "quantitative"}
  }
}

enter image description here

...