Тип визуализации geoshape в Vega и Vega-Lite
предназначен для отображения географических объектов: стран, регионов,
административных границ, морей, дорог, рек и любых произвольных
геометрий в формате GeoJSON или TopoJSON.
В отличие от обычных графиков, где используются координаты
x и y, картографические визуализации работают
через географические проекции. Vega автоматически преобразует долготу и
широту в экранные координаты.
geoshape используется для:
geoshapeМинимальный пример:
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"data": {
"url": "data/world-110m.json",
"format": {
"type": "topojson",
"feature": "countries"
}
},
"mark": "geoshape"
}
В этом примере:
countries;GeoJSON хранит геометрию напрямую.
Пример:
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [...]
},
"properties": {
"name": "Kazakhstan"
}
}
Поддерживаются:
PointLineStringPolygonMultiPolygonMultiLineStringTopoJSON — оптимизированный формат поверх GeoJSON.
Особенности:
В Vega-Lite чаще используются именно TopoJSON-файлы.
{
"data": {
"url": "data/world-110m.json",
"format": {
"type": "topojson",
"feature": "countries"
}
},
"mark": {
"type": "geoshape",
"fill": "#dcdcdc",
"stroke": "#ffffff"
}
}
featureУказывает объект внутри TopoJSON:
"feature": "countries"
Если в файле несколько слоёв:
{
"objects": {
"countries": {},
"rivers": {},
"lakes": {}
}
}
можно выбирать нужный слой.
Без проекции геометрия не может быть корректно отображена.
{
"projection": {
"type": "mercator"
}
}
"projection": {
"type": "mercator"
}
Особенности:
"projection": {
"type": "equalEarth"
}
Особенности:
"projection": {
"type": "orthographic"
}
Создаёт эффект глобуса.
"projection": {
"type": "naturalEarth1"
}
Подходит для атласов и инфографики.
"projection": {
"type": "albers"
}
Часто применяется для США.
"projection": {
"type": "mercator",
"scale": 150
}
"projection": {
"type": "mercator",
"center": [67, 48]
}
Формат:
[longitude, latitude]
"projection": {
"type": "orthographic",
"rotate": [-90, -30]
}
"projection": {
"translate": [400, 300]
}
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"width": 800,
"height": 500,
"data": {
"url": "data/world-110m.json",
"format": {
"type": "topojson",
"feature": "countries"
}
},
"projection": {
"type": "equalEarth",
"scale": 140
},
"mark": {
"type": "geoshape",
"fill": "#4c78a8",
"stroke": "#ffffff",
"strokeWidth": 0.5
}
}
"mark": {
"type": "geoshape",
"fill": "#4682b4"
}
"encoding": {
"color": {
"field": "population",
"type": "quantitative"
}
}
Хороплетная карта — карта, где регионы окрашиваются по значениям.
Пример:
{
"encoding": {
"color": {
"field": "gdp",
"type": "quantitative",
"scale": {
"scheme": "blues"
}
}
}
}
Часто геометрия хранится отдельно от статистики.
Используется lookup.
{
"transform": [
{
"lookup": "id",
"from": {
"data": {
"url": "data/population.csv"
},
"key": "country_id",
"fields": ["population"]
}
}
]
}
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"width": 900,
"height": 500,
"data": {
"url": "data/world-110m.json",
"format": {
"type": "topojson",
"feature": "countries"
}
},
"transform": [
{
"lookup": "id",
"from": {
"data": {
"url": "data/gdp.csv"
},
"key": "id",
"fields": ["gdp"]
}
}
],
"projection": {
"type": "equalEarth"
},
"mark": {
"type": "geoshape",
"stroke": "#ffffff"
},
"encoding": {
"color": {
"field": "gdp",
"type": "quantitative",
"scale": {
"scheme": "greens"
}
}
}
}
"mark": {
"type": "geoshape",
"fill": null,
"stroke": "#000000"
}
"mark": {
"strokeWidth": 2
}
"mark": {
"strokeDash": [4, 2]
}
Для координат используются поля:
{
"data": {
"url": "data/cities.csv"
},
"mark": "circle",
"encoding": {
"longitude": {
"field": "lon",
"type": "quantitative"
},
"latitude": {
"field": "lat",
"type": "quantitative"
},
"size": {
"field": "population",
"type": "quantitative"
}
}
}
Карта обычно строится через layer.
{
"layer": [
{
"data": {
"url": "data/world-110m.json",
"format": {
"type": "topojson",
"feature": "countries"
}
},
"mark": {
"type": "geoshape",
"fill": "#eeeeee",
"stroke": "#ffffff"
}
},
{
"data": {
"url": "data/cities.csv"
},
"mark": "circle",
"encoding": {
"longitude": {
"field": "lon",
"type": "quantitative"
},
"latitude": {
"field": "lat",
"type": "quantitative"
},
"size": {
"field": "population",
"type": "quantitative"
}
}
}
]
}
Для маршрутов и дорог используются:
LineStringMultiLineString{
"data": {
"values": [
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[71.43, 51.12],
[76.95, 43.25]
]
}
}
]
},
"mark": {
"type": "geoshape",
"stroke": "red",
"strokeWidth": 3
}
}
Polygon используется для:
Многие страны состоят из нескольких частей.
Например:
В этом случае используется:
"MultiPolygon"
Vega автоматически обрабатывает такие структуры.
sphere)Сфера представляет всю поверхность Земли.
{
"data": {
"sphere": true
},
"mark": {
"type": "geoshape",
"fill": "#dbefff"
}
}
Graticule — координатная сетка.
{
"data": {
"graticule": true
},
"mark": {
"type": "geoshape",
"stroke": "#cccccc"
}
}
{
"layer": [
{
"data": {
"sphere": true
},
"mark": {
"type": "geoshape",
"fill": "#ddeeff"
}
},
{
"data": {
"graticule": true
},
"mark": {
"type": "geoshape",
"stroke": "#cccccc"
}
}
]
}
Текст можно выводить поверх карты.
{
"mark": "text",
"encoding": {
"longitude": {
"field": "lon",
"type": "quantitative"
},
"latitude": {
"field": "lat",
"type": "quantitative"
},
"text": {
"field": "city"
}
}
}
Интерактивные подсказки особенно важны для карт.
"encoding": {
"tooltip": [
{
"field": "country",
"type": "nominal"
},
{
"field": "population",
"type": "quantitative"
}
]
}
{
"params": [
{
"name": "hover",
"select": {
"type": "point",
"on": "mouseover"
}
}
]
}
"encoding": {
"fillOpacity": {
"condition": {
"param": "hover",
"value": 1
},
"value": 0.5
}
}
Vega-Lite ограниченно поддерживает навигацию по карте. Для полноценного zoom/pan обычно используется Vega.
Подходит для:
Плюсы:
Подходит для:
Пример Vega-спецификации:
{
"$schema": "https://vega.github.io/schema/vega/v5.json",
"width": 800,
"height": 500,
"projections": [
{
"name": "projection",
"type": "mercator"
}
],
"data": [
{
"name": "world",
"url": "data/world-110m.json",
"format": {
"type": "topojson",
"feature": "countries"
}
}
],
"marks": [
{
"type": "shape",
"from": {
"data": "world"
},
"transform": [
{
"type": "geoshape",
"projection": "projection"
}
],
"encode": {
"update": {
"fill": {
"value": "#4c78a8"
},
"stroke": {
"value": "#ffffff"
}
}
}
}
]
}
geoshape в VegaВ Vega используется отдельная трансформация:
{
"type": "geoshape",
"projection": "projection"
}
Она преобразует географическую геометрию в SVG path.
При работе с большими картами возникают проблемы:
TopoJSON существенно уменьшает размер данных.
GIS-инструменты:
Для веба редко нужна сверхточная геометрия.
"projection": {
"type": "identity"
}
Для обычных геоданных это почти всегда ошибка.
Правильный порядок:
[longitude, latitude]
Не наоборот.
lookup"lookup": "id"
и
"key": "country_id"
должны содержать совместимые значения.
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"width": 700,
"height": 500,
"data": {
"url": "data/kazakhstan.json",
"format": {
"type": "topojson",
"feature": "regions"
}
},
"projection": {
"type": "mercator",
"center": [67, 48],
"scale": 2500
},
"mark": {
"type": "geoshape",
"fill": "#87b5e5",
"stroke": "#ffffff",
"strokeWidth": 1
},
"encoding": {
"tooltip": [
{
"field": "name",
"type": "nominal"
}
]
}
}
Процесс построения карты:
Плюсы:
Минусы:
Плюсы:
Минусы:
{
"config": {
"view": {
"renderer": "canvas"
}
}
}
Карты часто объединяются с:
Через вычисляемые поля можно строить тематические карты.
Пример:
{
"transform": [
{
"calculate": "datum.population / datum.area",
"as": "density"
}
]
}
Vega позволяет:
Это особенно важно для:
Внутри Vega используются многие механизмы D3 Geo:
Поэтому поддерживаются практически все основные географические проекции D3.
geoshapegeoshape оптимален для: