Charts - 지도
Charts - 지도 (Map) 🧪
지리 데이터를 렌더링해요.
본문
:::warning 이 기능은 프리뷰 상태예요. 아직 프로덕션 사용 준비가 되지 않았으며, API, 시각적 요소, 동작은 향후 마이너 또는 패치 릴리스에서 변경될 수 있어요. :::
개요 (Overview)
지도 프로바이더 ChartsGeoDataProviderPremium는 세 가지 주요 props를 사용해요:
geoData: 지도를 정의하는 지리적 객체들의 배열 (국가, 도시, 도로 등)projection: SVG에 객체들이 어떻게 투영되어야 하는지 정의하는 문자열series:'mapShape'타입의 지리적 객체와 연결된 데이터
import * as React from 'react';
import Box from '@mui/material/Box';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot, MapShapePlot } from '@mui/x-charts-premium/Map';
import { ChartsTooltip } from '@mui/x-charts-premium/ChartsTooltip';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
import { ChartsLegend } from '@mui/x-charts-premium/ChartsLegend';
import { countryData, EU_COUNTRIES } from '../dataset/countryData';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
export default function BasicGeoDataPlot() {
return (
<Box sx={{ width: '100%', maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={countries}
projection="naturalEarth1"
height={420}
series={[
{
type: 'mapShape',
label: 'World',
color: 'lightgray',
highlightScope: { highlight: 'item', fade: 'global' },
data: countries.features.map((feature, index) => ({
name: feature.properties?.name,
color: `hsl(${(index / countries.features.length) * 360}, 50%, 70%)`,
})),
valueFormatter: (point) =>
point.value != null ? `${point.value} units` : 'No data',
},
{
type: 'mapShape',
label: 'European Union',
id: 'EU',
color: 'blue',
highlightScope: { highlight: 'item', fade: 'series' },
data: EU_COUNTRIES.map((code) => ({
name: countryData[code as keyof typeof countryData].worldAtlasName,
label: countryData[code as keyof typeof countryData].country,
})),
valueFormatter: (point) =>
point.value != null ? `${point.value} units` : 'No data',
},
]}
>
<ChartsLegend toggleVisibilityOnClick />
<ChartsSurface>
<GeoDataPlot fill="transparent" stroke="#0d47a1" />
<MapShapePlot />
</ChartsSurface>
<ChartsTooltip trigger="item" />
</ChartsGeoDataProviderPremium>
</Box>
);
}
컴포지션 (Composition)
프로바이더는 GeoJSON FeatureCollection과 d3-geo 프로젝션(이름 또는 GeoProjection 인스턴스)을 받아요. GeoDataPlot은 useGeoData와 useGeoPath 훅을 통해 이들을 소비하고, 프로젝션을 차트의 드로잉 영역에 맞추며, 피처(feature)마다 <path> 하나를 렌더링해요.
<Unstable_ChartsGeoDataProviderPremium
geoData={geoData}
projection="naturalEarth1"
height={360}
>
<ChartsSurface>
<GeoDataPlot />
</ChartsSurface>
</Unstable_ChartsGeoDataProviderPremium>
임의의 GeoJSON 도형 렌더링 (Rendering any GeoJSON shapes)
geoData는 임의의 GeoJSON FeatureCollection을 받아요. 피처가 국가 경계일 필요는 없어요. 행정 구역, 판매 영역, 유역(watershed) 또는 아래에 사용된 지각판(tectonic plate)도 같은 방식으로 렌더링돼요.
이 예시는 PB2002 판 모델을 국가 경계와 함께 하나의 geoData에 두 개의 mapShape 시리즈로 로드해요. MapShapePlot은 각 시리즈를 data-series 속성을 가진 그룹으로 감싸므로, 하나의 플롯이 두 레이어를 렌더링하고 CSS가 독립적으로 스타일을 적용할 수 있어요: 아래에는 색칠된 판, 위에는 방향 참조용 국가 윤곽. 평면 naturalEarth1 지도와 orthographic 지구본을 전환해보세요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import {
MapShapePlot,
Graticule,
D3NamedProjection,
} from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsTooltip } from '@mui/x-charts-premium/ChartsTooltip';
import {
type ExtendedFeature,
type ExtendedFeatureCollection,
} from '@mui/x-charts-vendor/d3-geo';
import tectonicPlates from '../dataset/tectonicPlates.json';
const plates = tectonicPlates as unknown as ExtendedFeatureCollection;
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
// Plates and countries share a few names (India, Australia, ...), so tag each
// feature with its layer and key on `layer:name` to keep the two series apart.
function tagLayer(collection: ExtendedFeatureCollection, layer: string) {
return collection.features.map((feature) => ({
...feature,
properties: { ...feature.properties, layer },
}));
}
const geoData: ExtendedFeatureCollection = {
type: 'FeatureCollection',
features: [...tagLayer(plates, 'plate'), ...tagLayer(countries, 'country')],
};
const geoFeatureKey = (feature: ExtendedFeature) =>
`${feature.properties?.layer}:${feature.properties?.name}`;
const plateNames = Array.from(
new Set(plates.features.map((feature) => String(feature.properties?.name))),
);
const plateData = plateNames.map((name, index) => ({
name: `plate:${name}`,
label: name,
color: `hsl(${Math.round((index / plateNames.length) * 360)}, 55%, 60%)`,
}));
const countryData = countries.features.map((feature) => ({
name: `country:${feature.properties?.name}`,
}));
export default function TectonicPlates() {
const [projection, setProjection] =
React.useState<D3NamedProjection>('naturalEarth1');
const isGlobe = projection === 'orthographic';
return (
<Stack spacing={1} sx={{ width: '100%', maxWidth: 760 }}>
<Stack
direction="row"
sx={{ alignItems: 'center', justifyContent: 'space-between' }}
>
<Typography variant="body2" component="h6">
The 54 tectonic plates of the Earth (PB2002 model)
</Typography>
<ToggleButtonGroup
color="primary"
size="small"
exclusive
value={projection}
onChange={(_, value: D3NamedProjection | null) =>
value && setProjection(value)
}
aria-label="projection"
>
<ToggleButton value="naturalEarth1">Map</ToggleButton>
<ToggleButton value="orthographic">Globe</ToggleButton>
</ToggleButtonGroup>
</Stack>
<Box
sx={{
width: '100%',
// Plates: colored fill with white boundaries.
'& [data-series="plates"] path': { stroke: '#fff', strokeWidth: 0.5 },
// Countries: outline only, drawn on top as non-interactive reference
// geography so plate tooltips still trigger underneath.
'& [data-series="countries"] path': {
fill: 'none',
stroke: '#263238',
strokeWidth: 0.4,
pointerEvents: 'none',
},
}}
>
<ChartsGeoDataProviderPremium
geoData={geoData}
geoFeatureKey={geoFeatureKey}
projection={projection}
{...(isGlobe && { rotate: [-160, -10] })}
height={420}
series={[
{
type: 'mapShape',
id: 'plates',
label: 'Tectonic plate',
data: plateData,
highlightScope: { highlight: 'item' },
valueFormatter: () => '',
},
{
type: 'mapShape',
id: 'countries',
label: 'Country',
data: countryData,
},
]}
>
<ChartsSurface>
<MapShapePlot />
<Graticule strokeWidth={0.4} opacity={0.1} />
</ChartsSurface>
<ChartsTooltip trigger="item" />
</ChartsGeoDataProviderPremium>
</Box>
</Stack>
);
}
GeoDataPlot으로 기본 지도 렌더링 (Rendering the base map with GeoDataPlot)
GeoDataPlot은 프로바이더에 등록된 모든 피처를 SVG 경로로 그려요. 데이터 시리즈 없이 지리 자체인 기본 지도를 렌더링하기 위한 것이에요. fill, stroke, strokeWidth props이 모든 피처에 균일하게 적용되므로 배경 레이어 스타일링에 사용해요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot } from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
export default function GeoDataPlotDemo() {
const [fill, setFill] = React.useState('#e3f2fd');
const [stroke, setStroke] = React.useState('#0d47a1');
const [strokeWidth, setStrokeWidth] = React.useState(0.5);
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={2}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1, maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={countries}
projection="naturalEarth1"
height={360}
>
<ChartsSurface>
<GeoDataPlot fill={fill} stroke={stroke} strokeWidth={strokeWidth} />
</ChartsSurface>
</ChartsGeoDataProviderPremium>
</Box>
<Stack spacing={2} sx={{ minWidth: 180 }}>
<TextField
label="fill"
type="color"
value={fill}
onChange={(event) => setFill(event.target.value)}
/>
<TextField
label="stroke"
type="color"
value={stroke}
onChange={(event) => setStroke(event.target.value)}
/>
<TextField
label="strokeWidth"
type="number"
slotProps={{ htmlInput: { min: 0, max: 5, step: 0.5 } }}
value={strokeWidth}
onChange={(event) => setStrokeWidth(Number(event.target.value))}
/>
</Stack>
</Stack>
);
}
MapImagePlot으로 기본 지도 래스터 추가 (Adding a base map raster with MapImagePlot)
MapImagePlot은 시리즈 아래에 위성 모자이크 같은 래스터 기본 지도를 그려요. 이미지는 차트의 projection에 맞게 재투영되므로, 투영이 지도를 곡선으로 만들 때에도 평평한 사각형으로 유지되지 않고 지리를 따라가요.
href prop으로 이미지 URL을 전달해요. 소스는 정방형(equirectangular)이며 전 지구를 덮는다고 가정해요. 더 작은 범위를 덮는 경우 imageBounds ([[west, south], [east, north]])를 사용해요.
<ChartsSurface>
<MapImagePlot href="/static/mars-viking.jpg" />
<MapShapePlot />
</ChartsSurface>
프로바이더는 지구에 한정되지 않아요 — geoData는 임의의 GeoJSON FeatureCollection을 받아요. 아래 데모는 평균 고도로 채색된 30개의 USGS Mars Chart 구역을 Viking 표면 모자이크 위에 매핑하고, 주목할 만한 랜드마크와 임무 지점, 그리고 프로젝션 토글을 포함해요.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { MapImagePlot, MapShapePlot } from '@mui/x-charts-premium/Map';
import { useGeoPath } from '@mui/x-charts-premium/hooks';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsTooltip } from '@mui/x-charts-premium/ChartsTooltip';
import { ContinuousColorLegend } from '@mui/x-charts-premium/ChartsLegend';
import { type GeoProjection } from '@mui/x-charts-vendor/d3-geo';
import { marsRegions, marsData, marsFeatures } from './marsRegions';
const MARS_IMAGE = '/static/x/charts/mars-viking-mdim21.jpg';
const FEATURE_COLORS = { landmark: '#ff7777', mission: '#4fc3f7' } as const;
// Returns a predicate telling whether a coordinate is hidden by the projection,
// by checking it survives the round-trip `coord === invert(project(coord))`.
// On a globe (e.g. orthographic) back-of-sphere coordinates project onto the disk
// but invert to a different, front-facing coordinate.
function createIsHidden(projection: GeoProjection) {
return (coordinate: [number, number]) => {
const point = projection(coordinate);
if (!point) {
return true;
}
const inverted = projection.invert?.(point);
return (
!inverted ||
Math.abs(inverted[0] - coordinate[0]) > 1 ||
Math.abs(inverted[1] - coordinate[1]) > 1
);
};
}
// Notable features projected as labeled markers.
function MarsFeatureMarkers() {
const path = useGeoPath();
const projection = path?.projection() as GeoProjection | null;
if (!projection) {
return null;
}
const isHidden = createIsHidden(projection);
return (
<g>
{marsFeatures.map((feature) => {
const coordinate: [number, number] = [feature.lon, feature.lat];
const point = projection(coordinate);
if (!point || isHidden(coordinate)) {
return null;
}
const [x, y] = point;
return (
<g key={feature.name}>
<title>{feature.name}</title>
<circle
cx={x}
cy={y}
r={3}
fill={FEATURE_COLORS[feature.kind]}
stroke="#1a1a1a"
strokeWidth={0.75}
/>
<text
x={x + 5}
y={y + 3}
fontSize={9}
fill="#fff"
stroke="rgba(0, 0, 0, 0.7)"
strokeWidth={0.5}
paintOrder="stroke"
>
{feature.name}
</text>
</g>
);
})}
</g>
);
}
type ProjectionName = 'orthographic' | 'equirectangular';
export default function MarsMap() {
const [projection, setProjection] = React.useState<ProjectionName>('orthographic');
return (
<Stack spacing={2} sx={{ width: '100%', maxWidth: 800 }}>
<ToggleButtonGroup
color="primary"
size="small"
exclusive
value={projection}
onChange={(_, value: ProjectionName | null) => value && setProjection(value)}
aria-label="projection"
>
<ToggleButton value="orthographic">orthographic</ToggleButton>
<ToggleButton value="equirectangular">equirectangular</ToggleButton>
</ToggleButtonGroup>
<ChartsGeoDataProviderPremium
key={projection} // Reset zoom when projection change.
geoData={marsRegions}
projection={projection}
initialView={{
zoomLevel: 1,
center: projection === 'orthographic' ? [160, -10] : [0, 0],
}}
zoom
height={360}
series={[
{
type: 'mapShape',
label: 'Elevation',
data: marsData,
highlightScope: { highlight: 'item' },
valueFormatter: (point) =>
point.colorValue == null
? 'No data'
: `${point.colorValue > 0 ? '+' : ''}${point.colorValue} km`,
},
]}
zAxis={[
{
colorMap: {
type: 'continuous',
min: -6,
max: 8,
color: ['#2c5d8a', '#d8b98c'],
},
},
]}
>
<ChartsSurface>
<MapImagePlot href={MARS_IMAGE} />
<g opacity={0.5}>
<MapShapePlot stroke="#fff" strokeWidth={0.4} />
</g>
<MarsFeatureMarkers />
</ChartsSurface>
<ChartsTooltip trigger="item" />
<ContinuousColorLegend
axisDirection="z"
sx={{ width: 150, mx: 'auto', alignSelf: 'center' }}
/>
</ChartsGeoDataProviderPremium>
</Stack>
);
}
:::warning 재투영은 캔버스에서 이미지 픽셀을 읽으므로, 소스는 same-origin이거나 CORS 헤더로 서빙되어야 해요. :::
프로젝션 수정 (Modifying the projection)
projection prop은 d3-geo 프로젝션 이름 또는 GeoProjection 인스턴스를 받아요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import ListSubheader from '@mui/material/ListSubheader';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import USATopology from 'us-atlas/states-10m.json';
import { useChartPremiumApiRef } from '@mui/x-charts-premium/hooks';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import {
D3NamedProjection,
GeoDataPlot,
Graticule,
} from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
const USAStates = topojsonFeature(
USATopology as any,
'states',
) as unknown as ExtendedFeatureCollection;
const projectionGroups: { label: string; projections: D3NamedProjection[] }[] = [
{
// https://d3js.org/d3-geo/azimuthal
label: 'Azimuthal',
projections: [
'azimuthalEqualArea',
'azimuthalEquidistant',
'gnomonic',
'orthographic',
'stereographic',
],
},
{
// https://d3js.org/d3-geo/conic
label: 'Conic',
projections: [
// For now commented because those are more difficult to handle
// 'conicConformal',
// 'conicEqualArea',
// 'conicEquidistant',
// 'albers',
'albersUsa', // Special composition for the USA with an edge case for Alaska and Hawaii.
],
},
{
// https://d3js.org/d3-geo/cylindrical
label: 'Cylindrical',
projections: [
'equirectangular',
'mercator',
'transverseMercator',
'equalEarth',
'naturalEarth1',
],
},
];
function isConicProjection(projection: D3NamedProjection) {
return (
projection === 'conicConformal' ||
projection === 'conicEqualArea' ||
projection === 'conicEquidistant' ||
projection === 'albers' ||
projection === 'albersUsa'
);
}
export default function ProjectionMapShape() {
const [projection, setProjection] =
React.useState<D3NamedProjection>('naturalEarth1');
const apiRef = useChartPremiumApiRef<'mapShape'>();
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={2}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1, maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={isConicProjection(projection) ? USAStates : countries}
projection={projection}
zoom
height={360}
apiRef={apiRef}
>
<ChartsSurface>
<Graticule stroke="#90caf9" strokeWidth={0.5} />
<GeoDataPlot fill="#e3f2fd" stroke="#a7a7a7" strokeWidth={0.5} />
</ChartsSurface>
</ChartsGeoDataProviderPremium>
</Box>
<Stack spacing={2} sx={{ minWidth: 200 }}>
<TextField
select
label="projection"
value={projection}
onChange={(event) => {
setProjection(event.target.value as D3NamedProjection);
apiRef.current?.resetZoom();
}}
>
{projectionGroups.flatMap(({ label, projections }) => [
<ListSubheader key={label}>{label}</ListSubheader>,
...projections.map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
)),
])}
</TextField>
</Stack>
</Stack>
);
}
원뿔 프로젝션 (Conic projections)
원뿔(conic) 프로젝션은 정의의 일부로 두 개의 표준 평행선(parallels)을 받아요. 지도 왜곡은 그 평행선을 따라 최소예요. 따라서 표시하려는 영역 가까이에 이 평행선을 유지하는 것이 좋아요.
여기서 다양한 국가를 시도하고 프로젝션과 평행선을 조작해 그 영향을 확인할 수 있어요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Slider from '@mui/material/Slider';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import ListSubheader from '@mui/material/ListSubheader';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import {
D3NamedProjection,
GeoDataPlot,
Graticule,
} from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
import { useGeoPath } from '@mui/x-charts-premium/hooks';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
function getCountry(name: string): ExtendedFeatureCollection {
return {
...countries,
features: countries.features.filter(
(feature) => feature.properties?.name === name,
),
};
}
type Land = 'Japan' | 'United Kingdom' | 'Australia';
const LANDS: Record<
Land,
{
geoData: ExtendedFeatureCollection;
center: [number, number];
parallels: [number, number];
}
> = {
Japan: {
geoData: getCountry('Japan'),
center: [138, 38],
parallels: [33, 45],
},
'United Kingdom': {
geoData: getCountry('United Kingdom'),
center: [-2.5, 54],
parallels: [50, 58],
},
Australia: {
geoData: getCountry('Australia'),
center: [134, -28],
parallels: [-36, -18],
},
};
const projectionGroups: { label: string; projections: D3NamedProjection[] }[] = [
{
// https://d3js.org/d3-geo/conic
label: 'Conic',
projections: ['conicConformal', 'conicEqualArea', 'conicEquidistant', 'albers'],
},
{
// https://d3js.org/d3-geo/cylindrical
label: 'Cylindrical',
projections: [
'equirectangular',
'mercator',
'transverseMercator',
'equalEarth',
'naturalEarth1',
],
},
{
// https://d3js.org/d3-geo/azimuthal
label: 'Azimuthal',
projections: [
'azimuthalEqualArea',
'azimuthalEquidistant',
'gnomonic',
'orthographic',
'stereographic',
],
},
];
const CONIC_PROJECTIONS: D3NamedProjection[] = [
'conicConformal',
'conicEqualArea',
'conicEquidistant',
'albers',
];
const CYLINDRICAL_PROJECTIONS: D3NamedProjection[] = [
'equirectangular',
'mercator',
'transverseMercator',
'equalEarth',
'naturalEarth1',
];
function isConicProjection(projection: D3NamedProjection) {
return CONIC_PROJECTIONS.includes(projection);
}
function isCylindricalProjection(projection: D3NamedProjection) {
return CYLINDRICAL_PROJECTIONS.includes(projection);
}
export default function CountryProjectionShape() {
const [land, setLand] = React.useState<Land>('Japan');
const [projection, setProjection] = React.useState<D3NamedProjection>('albers');
const [parallels, setParallels] = React.useState<[number, number]>(
LANDS.Japan.parallels,
);
const { geoData, center } = LANDS[land];
const conic = isConicProjection(projection);
const cylindrical = isCylindricalProjection(projection);
const handleLandChange = (nextLand: Land) => {
const config = LANDS[nextLand];
setLand(nextLand);
setProjection('albers');
setParallels(config.parallels);
};
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={2}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1, maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
// Remount when the land or projection changes so the view re-centers on the country.
key={`${land}-${projection}`}
geoData={geoData}
projection={projection}
parallels={conic ? parallels : undefined}
initialView={{
zoomLevel: 1,
center: cylindrical // if cylindrical do not rotate along latitude
? [center[0], 0]
: center,
}}
zoom={{ minZoomLevel: 0.1 }}
height={300}
>
<ChartsSurface>
<Graticule stroke="#90caf9" strokeWidth={0.5} />
{conic && <Parallels parallels={parallels} />}
<GeoDataPlot fill="#e3f2fd" stroke="#a7a7a7" strokeWidth={0.5} />
</ChartsSurface>
</ChartsGeoDataProviderPremium>
</Box>
<Stack spacing={2} sx={{ minWidth: 220 }}>
<TextField
select
label="Land"
value={land}
onChange={(event) => handleLandChange(event.target.value as Land)}
>
{(Object.keys(LANDS) as Land[]).map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
))}
</TextField>
<TextField
select
label="Projection"
value={projection}
onChange={(event) =>
setProjection(event.target.value as D3NamedProjection)
}
>
{projectionGroups.flatMap(({ label, projections }) => [
<ListSubheader key={label}>{label}</ListSubheader>,
...projections.map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
)),
])}
</TextField>
{conic && (
<div>
<Typography gutterBottom variant="body2">
Standard parallels
</Typography>
<Slider
value={parallels}
min={-90}
max={90}
valueLabelDisplay="auto"
marks={[
{ value: -90, label: '-90°' },
{ value: 0, label: '0°' },
{ value: 90, label: '90°' },
]}
onChange={(_, value) =>
setParallels((value as number[]).slice(0, 2) as [number, number])
}
/>
</div>
)}
</Stack>
</Stack>
);
}
const angles = new Array(37).fill(0).map((_, i) => i * 10 - 180);
function Parallels(props: { parallels: [number, number] }) {
const { parallels } = props;
const path = useGeoPath();
if (!path) {
return null;
}
const d = path({
type: 'MultiLineString',
coordinates: [
angles.map((p) => [p, parallels[0]]),
...(parallels[1] === parallels[0]
? []
: [angles.map((p) => [p, parallels[1]])]),
],
});
if (!d) {
return null;
}
return <path d={d} fill="none" stroke="red" strokeWidth={1} />;
}
MapShapePlot으로 시리즈 플로팅 (Plotting series with MapShapePlot)
MapShapePlot은 'mapShape' 타입의 모든 시리즈의 항목마다 경로 하나를 렌더링해요.
GeoDataPlot 위에 쌓는 것은 전체 지리 위에서 피처의 일부 하위 집합을 강조하는 데 유용해요.
import * as React from 'react';
import Box from '@mui/material/Box';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot, MapShapePlot } from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsTooltip } from '@mui/x-charts-premium/ChartsTooltip';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
import { EU_COUNTRIES, countryData } from '../dataset/countryData';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
export default function MapShapePlotDemo() {
return (
<Box sx={{ width: '100%', maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={countries}
projection="naturalEarth1"
height={360}
series={[
{
type: 'mapShape',
label: 'European Union',
color: '#1976d2',
data: EU_COUNTRIES.map((code) => ({ name: countryData[code].country })),
valueFormatter: (point) => point.name,
},
]}
>
<ChartsSurface>
<GeoDataPlot fill="#f5f5f5" stroke="#bdbdbd" />
<MapShapePlot />
</ChartsSurface>
<ChartsTooltip trigger="item" />
</ChartsGeoDataProviderPremium>
</Box>
);
}
geoFeatureKey로 피처 매칭 (Matching features with geoFeatureKey)
기본적으로 시리즈 항목은 피처의 name 속성(feature.properties.name)을 통해 GeoJSON 피처와 결합돼요. geoData가 다른 속성으로 피처를 식별하는 경우 geoFeatureKey prop을 사용해요. 문자열 또는 함수를 받아요:
-
문자열: 읽을 속성의 이름.
feature.properties[geoFeatureKey]가 키로 사용돼요.<Unstable_ChartsGeoDataProviderPremium geoData={geoData} geoFeatureKey="iso_a3"> {/* series items now match feature.properties.iso_a3 */} </Unstable_ChartsGeoDataProviderPremium> -
함수: 각 피처와 함께 호출되어 사용할 키를 반환해요 (또는 피처를 무시하려면
null). 여러 피처에 같은 키를 주어 단일 시리즈 항목이 모두를 대상으로 하게 하는 데 유용해요.<Unstable_ChartsGeoDataProviderPremium geoData={geoData} geoFeatureKey={(feature) => feature.properties?.name === 'Somaliland' ? 'Somalia' : (feature.properties?.name ?? null) } > {/* ... */} </Unstable_ChartsGeoDataProviderPremium>
해석된 키는 mapShape 시리즈 항목이 name 속성(또는 데이터셋/valueGetter의 name 필드)을 통해 매칭하는 대상이에요.
아래 데모에서 세계 지도집(atlas)은 소말리아(Somalia)와 소말릴란드(Somaliland)를 두 개의 별도 피처로 저장해요. 하지만 Our World in Data의 데이터는 이들을 병합해요. 두 피처에 'Somalia'를 반환하면 같은 키를 가지므로, 단일 { name: 'Somalia' } 시리즈 항목이 두 도형을 동시에 강조해요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot, MapShapePlot } from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsTooltip } from '@mui/x-charts-premium/ChartsTooltip';
import type {
ExtendedFeature,
ExtendedFeatureCollection,
} from '@mui/x-charts-vendor/d3-geo';
import { countryData } from '../dataset/countryData';
import { internetUsageByCountry } from '../dataset/internetUsageByCountry';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
// Treat the state of Somaliland as part of Somalia to match our World in data dataset.
const mergeSomaliland = (feature: ExtendedFeature) =>
feature.properties?.name === 'Somaliland'
? 'Somalia'
: (feature.properties?.name ?? null);
const data = Object.entries(countryData)
.filter(([, country]) => country.worldAtlasName)
.map(([code, country]) => ({
name: country.worldAtlasName,
label: country.country,
colorValue: internetUsageByCountry[code],
}));
export default function GeoFeatureKeyMapShape() {
return (
<Stack spacing={2} sx={{ width: '100%', maxWidth: 500 }}>
<Box sx={{ width: '100%' }}>
<ChartsGeoDataProviderPremium
geoData={countries}
geoFeatureKey={mergeSomaliland}
projection="naturalEarth1"
initialView={{ zoomLevel: 5, center: [46, 6], translation: [0, 0] }}
height={360}
series={[
{
type: 'mapShape',
label: 'Internet usage',
data,
highlightScope: { highlight: 'item', fade: 'global' },
valueFormatter: (point) =>
point.colorValue == null
? 'No data'
: `${point.colorValue.toFixed(1)}%`,
},
]}
zAxis={[
{
id: 'internet-usage',
colorMap: {
type: 'continuous',
min: 0,
max: 100,
color: ['#e3f2fd', '#0d47a1'],
},
},
]}
>
<ChartsSurface>
<GeoDataPlot fill="#f5f5f5" stroke="#bdbdbd" />
<MapShapePlot />
</ChartsSurface>
<ChartsTooltip trigger="item" />
</ChartsGeoDataProviderPremium>
</Box>
</Stack>
);
}
값을 색상에 매핑 (Mapping values to colors)
각 mapShape 데이터 포인트는 zAxis prop으로 정의된 색상 축을 통해 그 채우기를 계산하는 데 사용되는 colorValue 속성을 받아요. 축 colorMap 구성은 일반적인 'continuous', 'piecewise', 또는 'ordinal' 타입을 받아요.
colorValue가 제공되지 않으면 항목의 value가 폴백으로 사용돼요.
<Unstable_ChartsGeoDataProviderPremium
geoData={geoData}
series={[
{
type: 'mapShape',
data: countries.map((country) => ({
name: country.name,
colorValue: country.internetUsage,
})),
},
]}
zAxis={[
{
colorMap: {
type: 'continuous',
min: 0,
max: 100,
color: ['#e3f2fd', '#0d47a1'],
},
},
]}
>
{/* ... */}
</Unstable_ChartsGeoDataProviderPremium>
여러 zAxis가 정의된 경우 시리즈는 colorAxisId 속성으로 하나를 명시적으로 대상으로 지정할 수 있어요.
기본적으로 값을 알 수 없는 도형은 무시돼요. colorMap에서 unknownColor 속성을 지정하면 렌더링할 수 있어요.
:::info
GeoDataPlot을 배경으로 표시하는 대신 unknownColor를 사용하면 데이터가 없는 도형에 대해 툴팁을 활성화할 수 있어요.
:::
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import { interpolateBlues } from 'd3-scale-chromatic';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot, MapShapePlot } from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsTooltip } from '@mui/x-charts-premium/ChartsTooltip';
import {
ContinuousColorLegend,
PiecewiseColorLegend,
} from '@mui/x-charts-premium/ChartsLegend';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
import { internetUsageByCountry } from '../dataset/internetUsageByCountry';
import { withCountryCodeAsName, countryData } from '../dataset/countryData';
const countries = withCountryCodeAsName(
topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection,
);
const data = Object.keys(countryData).map((code) => ({
name: code,
label: countryData[code].country,
colorValue: internetUsageByCountry[code],
}));
type ColorMapType = 'continuous' | 'piecewise';
export default function ColorScaleMapShape() {
const [colorMap, setColorMap] = React.useState<ColorMapType>('continuous');
const [unknownShape, setUnknownShape] = React.useState<
'color' | 'geoData' | 'none'
>('color');
return (
<Stack spacing={2} sx={{ width: '100%', maxWidth: 800 }}>
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={{ xs: 1, md: 0 }}
sx={{ alignItems: 'center', justifyContent: 'space-between' }}
>
<ToggleButtonGroup
color="primary"
size="small"
exclusive
value={colorMap}
onChange={(_, value: ColorMapType | null) => value && setColorMap(value)}
aria-label="color map"
>
<ToggleButton value="continuous">continuous</ToggleButton>
<ToggleButton value="piecewise">piecewise</ToggleButton>
</ToggleButtonGroup>
<ToggleButtonGroup
color="primary"
size="small"
exclusive
value={unknownShape}
onChange={(_, value: 'color' | 'geoData' | 'none' | null) =>
value && setUnknownShape(value)
}
aria-label="unknown shape"
>
<ToggleButton value="color">unknown Color</ToggleButton>
<ToggleButton value="geoData">Geo Data</ToggleButton>
<ToggleButton value="none">none</ToggleButton>
</ToggleButtonGroup>
</Stack>
<Typography variant="body2" component="h6" sx={{ textAlign: 'end' }}>
Share of the population using the Internet in 2020
</Typography>
<Box sx={{ width: '100%' }}>
<ChartsGeoDataProviderPremium
geoData={countries}
projection="naturalEarth1"
height={360}
series={[
{
type: 'mapShape',
label: 'Internet usage',
data,
valueFormatter: (point) =>
point.colorValue == null
? 'No data'
: `${point.colorValue.toFixed(1)}%`,
},
]}
zAxis={[
{
id: 'internet-usage',
colorMap:
colorMap === 'continuous'
? {
type: 'continuous',
min: 0,
max: 100,
color: ['#e3f2fd', '#0d47a1'],
unknownColor: unknownShape === 'color' ? 'gray' : undefined,
}
: {
type: 'piecewise',
thresholds: [25, 50, 75],
colors: [0.25, 0.5, 0.75, 1].map(interpolateBlues),
unknownColor: unknownShape === 'color' ? 'gray' : undefined,
},
},
]}
>
<ChartsSurface>
{unknownShape === 'geoData' && (
<GeoDataPlot fill="#f5f5f5" stroke="#bdbdbd" />
)}
<MapShapePlot stroke="#fff" strokeWidth={0.3} />
</ChartsSurface>
<ChartsTooltip trigger="item" />
{colorMap === 'continuous' ? (
<ContinuousColorLegend axisDirection="z" sx={{ maxWidth: 150 }} />
) : (
<PiecewiseColorLegend axisDirection="z" direction="horizontal" />
)}
</ChartsGeoDataProviderPremium>
</Box>
</Stack>
);
}
데이터셋 사용 (Using a dataset)
데이터가 객체 배열에 저장되어 있다면 dataset prop으로 한 번 프로바이더에 전달하고 각 시리즈가 datasetKeys로 필드를 읽게 할 수 있어요. name 키는 각 항목을 GeoJSON 피처와 매칭하는 데 필요하며, label, value, colorValue는 선택적이에요.
<Unstable_ChartsGeoDataProviderPremium
geoData={geoData}
dataset={countries}
series={[
{
type: 'mapShape',
datasetKeys: {
name: 'code',
label: 'country',
colorValue: 'internetUsage',
},
},
]}
>
{/* ... */}
</Unstable_ChartsGeoDataProviderPremium>
데이터셋 값을 변환해야 하는 경우 datasetKeys 대신 valueGetter를 사용해요. 이는 데이터셋 항목을 받아 MapShapeValueType을 반환해야 해요.
series={[
{
type: 'mapShape',
valueGetter: (item) => ({
name: item.code,
label: item.country,
colorValue: item.internetUsage / 100,
}),
},
]}
자세한 내용은 Dataset 페이지를 참고하세요.
클릭 이벤트 (Click event)
MapShapePlot은 사용자가 도형을 클릭할 때 호출되는 onItemClick 콜백을 받아요. 클릭 이벤트와 seriesId 및 name을 통해 클릭된 항목을 식별하는 MapShapeItemIdentifier를 받아요.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import UndoOutlinedIcon from '@mui/icons-material/UndoOutlined';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot, MapShapePlot } from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsTooltip } from '@mui/x-charts-premium/ChartsTooltip';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import { type MapShapeItemIdentifier } from '@mui/x-charts-premium/models';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
import { EU_COUNTRIES, countryData } from '../dataset/countryData';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
export default function MapShapeClick() {
const [itemData, setItemData] = React.useState<MapShapeItemIdentifier>();
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={{ xs: 0, md: 4 }}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1, maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={countries}
projection="naturalEarth1"
height={240}
series={[
{
type: 'mapShape',
label: 'European Union',
color: '#1976d2',
data: EU_COUNTRIES.map((code) => ({
name: countryData[code].country,
})),
valueFormatter: (point) => point.name,
},
]}
>
<ChartsSurface>
<GeoDataPlot fill="#f5f5f5" stroke="#bdbdbd" />
<MapShapePlot
onItemClick={(event, identifier) => setItemData(identifier)}
/>
</ChartsSurface>
<ChartsTooltip trigger="item" />
</ChartsGeoDataProviderPremium>
</Box>
<Stack direction="column" sx={{ width: { xs: '100%', md: '40%' } }}>
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Typography>Click on a shape</Typography>
<IconButton
aria-label="reset"
size="small"
onClick={() => setItemData(undefined)}
>
<UndoOutlinedIcon fontSize="small" />
</IconButton>
</Box>
<HighlightedCode
code={`// Data from item click
${itemData ? JSON.stringify(itemData, null, 2) : '// The data will appear here'}
`}
language="json"
copyButtonHidden
/>
</Stack>
</Stack>
);
}
highlightScope로 강조 관리 (Managing the highlight with highlightScope)
각 mapShape 시리즈는 항목 위에 마우스를 올렸을 때 렌더링에 미치는 영향을 제어하는 highlightScope 속성을 받아요. highlight 옵션은 어떤 항목이 강조되는지 결정하고('item'은 마우스를 올린 도형만, 'series'는 같은 시리즈의 모든 도형), fade 옵션은 어떤 항목이 어두워지는지 결정해요('series'는 같은 시리즈의 나머지, 'global'은 모든 시리즈의 모든 도형).
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot, MapShapePlot } from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsTooltip } from '@mui/x-charts-premium/ChartsTooltip';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
import {
withCountryCodeAsName,
countriesInContinent,
countryData,
} from '../dataset/countryData';
type HighlightOptions = 'none' | 'item' | 'series';
type FadeOptions = 'none' | 'series' | 'global';
const countries = withCountryCodeAsName(
topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection,
);
const getContinentData = (continent: string) =>
countriesInContinent[continent].map((code) => ({
name: code,
label: countryData[code as keyof typeof countryData].country,
}));
const northAmerica = getContinentData('North America');
const southAmerica = getContinentData('South America');
const europe = getContinentData('Europe');
const asia = getContinentData('Asia');
const africa = getContinentData('Africa');
const oceania = getContinentData('Oceania');
export default function HighlightedMapShape() {
const [highlight, setHighlight] = React.useState<HighlightOptions>('item');
const [fade, setFade] = React.useState<FadeOptions>('global');
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={2}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1, maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={countries}
projection="naturalEarth1"
height={360}
series={[
{
type: 'mapShape',
label: 'North America',
color: '#fb8c00',
highlightScope: { highlight, fade },
valueFormatter: () => '',
data: northAmerica,
},
{
type: 'mapShape',
label: 'South America',
color: '#43a047',
highlightScope: { highlight, fade },
valueFormatter: () => '',
data: southAmerica,
},
{
type: 'mapShape',
label: 'Europe',
color: '#1e88e5',
highlightScope: { highlight, fade },
valueFormatter: () => '',
data: europe,
},
{
type: 'mapShape',
label: 'Asia',
color: '#e53935',
highlightScope: { highlight, fade },
valueFormatter: () => '',
data: asia,
},
{
type: 'mapShape',
label: 'Africa',
color: '#fdd835',
highlightScope: { highlight, fade },
valueFormatter: () => '',
data: africa,
},
{
type: 'mapShape',
label: 'Oceania',
color: '#8e24aa',
highlightScope: { highlight, fade },
valueFormatter: () => '',
data: oceania,
},
]}
>
<ChartsSurface>
<GeoDataPlot fill="#f5f5f5" stroke="#bdbdbd" />
<MapShapePlot />
</ChartsSurface>
<ChartsTooltip trigger="item" />
</ChartsGeoDataProviderPremium>
</Box>
<Stack spacing={2} sx={{ minWidth: 150 }}>
<TextField
select
label="highlight"
value={highlight}
onChange={(event) => setHighlight(event.target.value as HighlightOptions)}
>
<MenuItem value="none">none</MenuItem>
<MenuItem value="item">item</MenuItem>
<MenuItem value="series">series</MenuItem>
</TextField>
<TextField
select
label="fade"
value={fade}
onChange={(event) => setFade(event.target.value as FadeOptions)}
>
<MenuItem value="none">none</MenuItem>
<MenuItem value="series">series</MenuItem>
<MenuItem value="global">global</MenuItem>
</TextField>
</Stack>
</Stack>
);
}
줌 (Zoom)
상호작용 (Interaction)
zoom prop을 true로 설정해 줌 상호작용을 활성화해요. 이 prop은 구성 객체도 받아요.
줌 상호작용은 제스처 중 사용자 포인터가 같은 지리적 좌표 위에 머물도록 프로젝션 중심을 수정해요. 중심 수정이 성공하지 못하면 translation을 수정해요.
줌 객체에는 이 동작을 제한하는 두 가지 속성이 있어요:
rotationAllowed:'both' | 'both+roll' | 'longitude' | 'none'— 중심이 수정될 수 있는 범위를 제한해요.translationAllowed:'both' | 'x' | 'y' | 'none'— translation이 수정될 수 있는 범위를 제한해요.
:::info rotation(회전)은 2D 평면에 투영하기 전에 3D 구에 적용돼요.
translation(이동)은 투영 후에 적용돼요. 드래그할 수 있게 하지만 투영에는 영향을 주지 않아요.
rotation은 360도 회전이 사용자를 처음 지점으로 되돌리기 때문에 무한 드래그를 허용해요. 그러나 일부 프로젝션에서는 위도 또는 롤(roll) 각도에 따라 회전하는 것이 두 가지 영향을 줄 수 있어요:
- 원통형 프로젝션은 보통 위도/경도를 가로/세로 선으로 표현해요. 위도를 따라 회전하거나 롤을 사용하면 그 직선들이 곡선으로 변환돼요.
- 원통형 및 원뿔형 프로젝션은 위도/롤 각도에 따라 도형에 다른 왜곡을 적용해요. 따라서 지도를 드래그하는 동안 도형이 달라져요.
:::
기본적으로 둘 다 선택된 프로젝션에서 파생되므로 각 지도는 추가 구성 없이 예상대로 동작해요:
- azimuthal (지구본 같은) 프로젝션:
{ rotationAllowed: 'both', translationAllowed: 'none' } - cylindrical:
{ rotationAllowed: 'long', translationAllowed: 'y' } - conic:
{ rotationAllowed: 'none', translationAllowed: 'both' }
:::info
azimuthal 프로젝션에서는 rotationAllowed: 'both'를 'both+roll'로 바꿔 더 부드러운 드래그 상호작용을 얻을 수 있어요. 하지만 북/남 축이 더 쉽게 움직이게 돼요.
:::
다음으로 줌 결과를 수정할 수도 있어요:
minZoomLevel/maxZoomLevel:zoomLevel을 이 두 값 사이로 제한해요.maxEmptySpace: 지도를 드래그하는 동안 남겨질 수 있는 최대 빈 공간. 드로잉 영역 크기의 비율이에요. 예를 들어maxEmptySpace=0.2는 지도를 드래그할 때 드로잉 영역의 20% 이상을 비워둘 수 없다는 뜻이에요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import ListSubheader from '@mui/material/ListSubheader';
import Typography from '@mui/material/Typography';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import USATopology from 'us-atlas/states-10m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { useChartPremiumApiRef } from '@mui/x-charts-premium/hooks';
import {
D3NamedProjection,
GeoDataPlot,
Graticule,
} from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
const countriesWithoutAntarctica = {
...countries,
features: countries.features.filter(
(feature) => feature.properties?.name !== 'Antarctica',
),
};
const USAStates = topojsonFeature(
USATopology as any,
'states',
) as unknown as ExtendedFeatureCollection;
function getGeoDataForProjection(projection: D3NamedProjection) {
if (projection === 'albersUsa') {
return USAStates;
}
if (projection === 'conicConformal') {
return countriesWithoutAntarctica;
}
return countries;
}
const projectionGroups: { label: string; projections: D3NamedProjection[] }[] = [
{
// https://d3js.org/d3-geo/azimuthal
label: 'Azimuthal',
projections: [
'azimuthalEqualArea',
'azimuthalEquidistant',
'gnomonic',
'orthographic',
'stereographic',
],
},
{
// https://d3js.org/d3-geo/conic
label: 'Conic',
projections: [
// For now commented because those are more difficult to handle
'conicConformal',
'conicEqualArea',
'conicEquidistant',
'albers',
'albersUsa', // Special composition for the USA with an edge case for Alaska and Hawaii.
],
},
{
// https://d3js.org/d3-geo/cylindrical
label: 'Cylindrical',
projections: [
'equirectangular',
'mercator',
'transverseMercator',
'equalEarth',
'naturalEarth1',
],
},
];
function isConicProjection(projection: D3NamedProjection) {
return (
projection === 'conicConformal' ||
projection === 'conicEqualArea' ||
projection === 'conicEquidistant' ||
projection === 'albers' ||
projection === 'albersUsa'
);
}
function isCylindricalProjection(projection: D3NamedProjection) {
return (
projection === 'equirectangular' ||
projection === 'mercator' ||
projection === 'transverseMercator' ||
projection === 'equalEarth' ||
projection === 'naturalEarth1'
);
}
export default function MapZoomOptions() {
const [projection, setProjection] =
React.useState<D3NamedProjection>('naturalEarth1');
const apiRef = useChartPremiumApiRef<'mapShape'>();
const [rotationAllowed, setRotationAllowed] = React.useState<
'both' | 'both+roll' | 'longitude' | 'none'
>('longitude');
const [translationAllowed, setTranslationAllowed] = React.useState<
'both' | 'x' | 'y' | 'none'
>('y');
const [maxEmptySpace, setMaxEmptySpace] = React.useState(0);
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={2}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1, maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={getGeoDataForProjection(projection)}
projection={projection}
apiRef={apiRef}
zoom={{ rotationAllowed, translationAllowed, maxEmptySpace }}
height={360}
>
<ChartsSurface>
<Graticule stroke="#90caf9" strokeWidth={0.5} />
<GeoDataPlot fill="#e3f2fd" stroke="#a7a7a7" strokeWidth={0.5} />
</ChartsSurface>
</ChartsGeoDataProviderPremium>
</Box>
<Stack spacing={2} sx={{ minWidth: 200, maxWidth: 300 }}>
<TextField
select
label="projection"
value={projection}
onChange={(event) => {
const value = event.target.value as D3NamedProjection;
setProjection(value);
apiRef.current?.resetZoom();
if (value === 'albersUsa') {
setRotationAllowed('none');
setTranslationAllowed('both');
} else if (isConicProjection(value) || isCylindricalProjection(value)) {
setRotationAllowed('longitude');
setTranslationAllowed('y');
} else {
setRotationAllowed('both');
setTranslationAllowed('none');
}
}}
>
{projectionGroups.flatMap(({ label, projections }) => [
<ListSubheader key={label}>{label}</ListSubheader>,
...projections.map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
)),
])}
</TextField>
<div>
<Typography gutterBottom variant="caption">
Rotation
</Typography>
<div>
<ToggleButtonGroup
value={rotationAllowed}
exclusive
size="small"
onChange={(_, value) => {
if (value !== null) {
setRotationAllowed(value);
}
}}
>
<ToggleButton value="both">both</ToggleButton>
<ToggleButton value="both+roll">both+roll</ToggleButton>
<ToggleButton value="longitude">longitude</ToggleButton>
<ToggleButton value="none">none</ToggleButton>
</ToggleButtonGroup>
</div>
</div>
<div>
<Typography gutterBottom variant="caption">
Translation
</Typography>
<div>
<ToggleButtonGroup
value={translationAllowed}
exclusive
size="small"
onChange={(_, value) => {
if (value !== null) {
setTranslationAllowed(value);
}
}}
>
<ToggleButton value="both">both</ToggleButton>
<ToggleButton value="x">x</ToggleButton>
<ToggleButton value="y">y</ToggleButton>
<ToggleButton value="none">none</ToggleButton>
</ToggleButtonGroup>
</div>
</div>
<div>
<Typography gutterBottom variant="caption">
Max Empty Space
</Typography>
<div>
<ToggleButtonGroup
value={maxEmptySpace}
exclusive
size="small"
onChange={(_, value) => {
if (value !== null) {
setMaxEmptySpace(value);
}
}}
>
<ToggleButton value={0}>0</ToggleButton>
<ToggleButton value={0.5}>0.5</ToggleButton>
</ToggleButtonGroup>
</div>
</div>
<div>
<Button
onClick={() => {
apiRef.current?.resetZoom();
}}
size="small"
variant="outlined"
>
Reset zoom
</Button>
</div>
</Stack>
</Stack>
);
}
제어 (Control)
지도에는 줌을 제어할 수 있는 view와 onViewChange props가 있어요.
view는 세 가지 속성으로 구성돼요:
zoomLevel:number—1이 모든 객체가 드로잉 영역에 맞는 스케일에 해당하는 확대 비율.center:[number, number]— 프로젝션 중앙 지점의 경도/위도 좌표(도 단위).translation:[number, number]— 드로잉 영역의 비율로 표현된 지도의 이동.
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import ButtonGroup from '@mui/material/ButtonGroup';
import Slider from '@mui/material/Slider';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import ListSubheader from '@mui/material/ListSubheader';
import Typography from '@mui/material/Typography';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import USATopology from 'us-atlas/states-10m.json';
import {
Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium,
MapZoomView,
} from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { useChartPremiumApiRef } from '@mui/x-charts-premium/hooks';
import {
D3NamedProjection,
GeoDataPlot,
Graticule,
} from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
const countriesWithoutAntarctica = {
...countries,
features: countries.features.filter(
(feature) => feature.properties?.name !== 'Antarctica',
),
};
const USAStates = topojsonFeature(
USATopology as any,
'states',
) as unknown as ExtendedFeatureCollection;
const projectionGroups: { label: string; projections: D3NamedProjection[] }[] = [
{
// https://d3js.org/d3-geo/azimuthal
label: 'Azimuthal',
projections: [
'azimuthalEqualArea',
'azimuthalEquidistant',
'gnomonic',
'orthographic',
'stereographic',
],
},
{
// https://d3js.org/d3-geo/conic
label: 'Conic',
projections: [
// For now commented because those are more difficult to handle
'conicConformal',
'conicEqualArea',
'conicEquidistant',
'albers',
'albersUsa', // Special composition for the USA with an edge case for Alaska and Hawaii.
],
},
{
// https://d3js.org/d3-geo/cylindrical
label: 'Cylindrical',
projections: [
'equirectangular',
'mercator',
'transverseMercator',
'equalEarth',
'naturalEarth1',
],
},
];
const cities = [
// { name: 'New York', coordinates: [-74.006, 40.7128] },
{ name: 'Tokyo', coordinates: [139.6917, 35.6895] },
{ name: 'Sydney', coordinates: [151.2093, -33.8688] },
{ name: 'Rio', coordinates: [-43.1729, -22.9068] },
];
function getGeoDataForProjection(projection: D3NamedProjection) {
if (projection === 'albersUsa') {
return USAStates;
}
if (projection === 'conicConformal') {
return countriesWithoutAntarctica;
}
return countries;
}
export default function MapZoomControl() {
const [projection, setProjection] =
React.useState<D3NamedProjection>('naturalEarth1');
const apiRef = useChartPremiumApiRef<'mapShape'>();
const [view, setView] = React.useState<MapZoomView>({
zoomLevel: 1,
center: [0, 0],
translation: [0, 0],
roll: 0,
});
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={2}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1, maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={getGeoDataForProjection(projection)}
projection={projection}
apiRef={apiRef}
zoom
view={view}
onViewChange={(newView) => {
setView(newView);
}}
height={360}
>
<ChartsSurface>
<Graticule stroke="#90caf9" strokeWidth={0.5} />
<GeoDataPlot fill="#e3f2fd" stroke="#a7a7a7" strokeWidth={0.5} />
</ChartsSurface>
</ChartsGeoDataProviderPremium>
</Box>
<Stack spacing={2} sx={{ minWidth: 200, maxWidth: 300 }}>
<TextField
select
label="projection"
value={projection}
onChange={(event) => {
setProjection(event.target.value as D3NamedProjection);
}}
>
{projectionGroups.flatMap(({ label, projections }) => [
<ListSubheader key={label}>{label}</ListSubheader>,
...projections.map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
)),
])}
</TextField>
<div>
<Typography gutterBottom variant="caption">
Center (longitude, latitude)
</Typography>
<ButtonGroup
variant="outlined"
aria-label="outlined button group"
fullWidth
>
{cities.map(({ name, coordinates }) => (
<Button
size="small"
key={name}
onClick={() => {
return setView((prev) => ({
...prev,
center: coordinates as [number, number],
}));
}}
>
{name}
</Button>
))}
</ButtonGroup>
<Slider
value={view.center[0]}
min={-180}
max={180}
step={1}
size="small"
valueLabelDisplay="auto"
aria-label="center longitude"
onChange={(event, value) => {
setView((prev) => ({
...prev,
center: [value as number, prev.center[1]],
}));
}}
/>
<Slider
value={view.center[1]}
min={-90}
max={90}
step={1}
size="small"
valueLabelDisplay="auto"
aria-label="center latitude"
onChange={(event, value) => {
setView((prev) => ({
...prev,
center: [prev.center[0], value as number],
}));
}}
/>
{[
'azimuthalEqualArea',
'azimuthalEquidistant',
'gnomonic',
'orthographic',
'stereographic',
].includes(projection) && (
<Slider
value={view.roll}
min={-180}
max={180}
step={1}
size="small"
valueLabelDisplay="auto"
aria-label="map roll"
onChange={(event, value) => {
setView((prev) => ({
...prev,
roll: value as number,
}));
}}
/>
)}
</div>
<div>
<Typography gutterBottom variant="caption">
Translation (x, y as fraction of the drawing area)
</Typography>
<Slider
value={view.translation[0]}
min={-1}
max={1}
step={0.01}
size="small"
valueLabelDisplay="auto"
aria-label="translation x"
onChange={(event, value) => {
setView((prev) => ({
...prev,
translation: [value as number, prev.translation[1]],
}));
}}
/>
<Slider
value={view.translation[1]}
min={-1}
max={1}
step={0.01}
size="small"
valueLabelDisplay="auto"
aria-label="translation y"
onChange={(event, value) => {
setView((prev) => ({
...prev,
translation: [prev.translation[0], value as number],
}));
}}
/>
</div>
<div>
<Typography gutterBottom variant="caption">
Zoom Level
</Typography>
<Slider
value={view.zoomLevel}
min={0.1}
max={8}
step={0.2}
size="small"
valueLabelDisplay="auto"
aria-label="zoom level"
onChange={(event, value) => {
setView((prev) => ({ ...prev, zoomLevel: value as number }));
}}
/>
</div>
<div>
<Button
onClick={() => {
apiRef.current?.resetZoom();
}}
size="small"
variant="outlined"
>
Reset zoom
</Button>
</div>
</Stack>
</Stack>
);
}
범례에서 가시성 관리 (Managing visibility from the legend)
ChartsLegend에 toggleVisibilityOnClick이 설정되면 시리즈를 클릭하면 그 가시성이 토글돼요. 숨겨진 시리즈는 MapShapePlot에서 건너뛰므로 아래의 기본 지도가 계속 보여요.
import * as React from 'react';
import Box from '@mui/material/Box';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot, MapShapePlot } from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsLegend } from '@mui/x-charts-premium/ChartsLegend';
import { ChartsTooltip } from '@mui/x-charts-premium/ChartsTooltip';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
import {
withCountryCodeAsName,
countriesInContinent,
countryData,
} from '../dataset/countryData';
const countries = withCountryCodeAsName(
topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection,
);
const getContinentData = (continent: string) =>
countriesInContinent[continent].map((code) => ({
name: code,
label: countryData[code as keyof typeof countryData].country,
}));
const northAmerica = getContinentData('North America');
const southAmerica = getContinentData('South America');
const europe = getContinentData('Europe');
const asia = getContinentData('Asia');
const africa = getContinentData('Africa');
const oceania = getContinentData('Oceania');
export default function VisibleMapShape() {
return (
<Box sx={{ width: '100%', maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={countries}
projection="naturalEarth1"
height={360}
series={[
{
type: 'mapShape',
label: 'North America',
color: '#fb8c00',
valueFormatter: () => '',
data: northAmerica,
},
{
type: 'mapShape',
label: 'South America',
color: '#43a047',
valueFormatter: () => '',
data: southAmerica,
},
{
type: 'mapShape',
label: 'Europe',
color: '#1e88e5',
valueFormatter: () => '',
data: europe,
},
{
type: 'mapShape',
label: 'Asia',
color: '#e53935',
valueFormatter: () => '',
data: asia,
},
{
type: 'mapShape',
label: 'Africa',
color: '#fdd835',
valueFormatter: () => '',
data: africa,
},
{
type: 'mapShape',
label: 'Oceania',
color: '#8e24aa',
valueFormatter: () => '',
data: oceania,
},
]}
>
<ChartsLegend toggleVisibilityOnClick />
<ChartsSurface>
<GeoDataPlot fill="#f5f5f5" stroke="#bdbdbd" />
<MapShapePlot />
</ChartsSurface>
<ChartsTooltip trigger="item" />
</ChartsGeoDataProviderPremium>
</Box>
);
}
내보내기 (Exporting)
지도는 다른 차트와 마찬가지로 이미지 또는 PDF로 내보낼 수 있어요. 전체 문서는 Export 페이지를 참고하세요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import { interpolateBlues } from 'd3-scale-chromatic';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot } from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { useChartRootRef } from '@mui/x-charts/hooks';
import { useChartPremiumApiRef } from '@mui/x-charts-premium/hooks';
import { PiecewiseColorLegend } from '@mui/x-charts-premium/ChartsLegend';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
import { countryData } from '../dataset/countryData';
import { internetUsageByCountry } from '../dataset/internetUsageByCountry';
const countries = topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection;
const data = Object.keys(countryData).map((code) => ({
name: code,
label: countryData[code].country,
colorValue: internetUsageByCountry[code],
}));
function CustomChartWrapper({ children }: React.PropsWithChildren) {
const chartRootRef = useChartRootRef();
return <div ref={chartRootRef}>{children}</div>;
}
export default function ExportMap() {
const apiRef = useChartPremiumApiRef<'mapShape'>();
return (
<Box sx={{ width: '100%', maxWidth: 800 }}>
<Stack direction="row" spacing={1} sx={{ mb: 1 }}>
<Button
variant="contained"
onClick={() =>
apiRef.current?.exportAsImage({ type: 'image/png' }).catch((error) => {
console.error(error);
})
}
>
Export as PNG
</Button>
<Button
variant="outlined"
onClick={() =>
apiRef.current?.exportAsPrint().catch((error) => {
console.error(error);
})
}
>
Print / Export as PDF
</Button>
</Stack>
<ChartsGeoDataProviderPremium
apiRef={apiRef}
geoData={countries}
projection="naturalEarth1"
height={420}
series={[
{
type: 'mapShape',
label: 'World',
color: 'lightgray',
data,
},
]}
zAxis={[
{
id: 'internet-usage',
colorMap: {
type: 'piecewise',
thresholds: [25, 50, 75],
colors: [0.25, 0.5, 0.75, 1].map(interpolateBlues),
},
},
]}
>
<CustomChartWrapper>
<ChartsSurface>
<GeoDataPlot fill="#e3f2fd" stroke="#0d47a1" />
</ChartsSurface>
</CustomChartWrapper>
<PiecewiseColorLegend axisDirection="z" direction="horizontal" />
</ChartsGeoDataProviderPremium>
</Box>
);
}
일반적인 관행 (Common practice)
남극 제거 (Removing Antarctica)
세계 지도는 종종 남극에 대한 데이터가 없어요. 이를 제거하는 두 가지 방법이 있어요:
<GeoDataPlot />을 제거하고 시리즈의 국가만 렌더링.geoData에서 남극을 필터링.
import * as React from 'react';
import Box from '@mui/material/Box';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import MenuItem from '@mui/material/MenuItem';
import TextField from '@mui/material/TextField';
import { feature as topojsonFeature } from 'topojson-client';
import countriesTopology from 'visionscarto-world-atlas/world/110m.json';
import { Unstable_ChartsGeoDataProviderPremium as ChartsGeoDataProviderPremium } from '@mui/x-charts-premium/ChartsGeoDataProviderPremium';
import { GeoDataPlot, MapShapePlot } from '@mui/x-charts-premium/Map';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { type ExtendedFeatureCollection } from '@mui/x-charts-vendor/d3-geo';
import { type MapShapeValueType } from '@mui/x-charts-premium/models';
import { internetUsageByCountry } from '../dataset/internetUsageByCountry';
import { countryData, withCountryCodeAsName } from '../dataset/countryData';
const projections = [
'equirectangular',
'mercator',
'transverseMercator',
'equalEarth',
'naturalEarth1',
] as const;
type Projection = (typeof projections)[number];
const countries = withCountryCodeAsName(
topojsonFeature(
countriesTopology as any,
'countries',
) as unknown as ExtendedFeatureCollection,
);
const countriesWithoutAntarctica = {
...countries,
features: countries.features.filter(
(feature) => feature.properties?.name !== 'Antarctica',
),
};
export default function RemoveAntarctica() {
const [mode, setMode] = React.useState<
'with-antarctica' | 'geoDataFiltering' | 'seriesOnly'
>('geoDataFiltering');
const [projection, setProjection] = React.useState<Projection>('naturalEarth1');
return (
<Box sx={{ width: '100%' }}>
<ToggleButtonGroup
value={mode}
exclusive
onChange={(_, newMode) => {
if (newMode !== null) {
setMode(newMode);
}
}}
sx={{ mb: 2, mr: 2 }}
>
<ToggleButton value="with-antarctica">With Antarctica</ToggleButton>
<ToggleButton value="geoDataFiltering">geoData filtering</ToggleButton>
<ToggleButton value="seriesOnly">series only</ToggleButton>
</ToggleButtonGroup>
<TextField
select
label="Projection"
value={projection}
onChange={(event) => setProjection(event.target.value as Projection)}
sx={{ mb: 2, minWidth: 200 }}
>
{projections.map((name) => (
<MenuItem key={name} value={name}>
{name}
</MenuItem>
))}
</TextField>
<Box sx={{ width: '100%', maxWidth: 800 }}>
<ChartsGeoDataProviderPremium
geoData={
mode === 'geoDataFiltering' ? countriesWithoutAntarctica : countries
}
{...settings}
projection={projection}
>
<ChartsSurface>
{mode === 'seriesOnly' ? null : (
<GeoDataPlot fill="#f5f5f5" stroke="#bdbdbd" />
)}
<MapShapePlot />
</ChartsSurface>
</ChartsGeoDataProviderPremium>
</Box>
</Box>
);
}
const settings = {
zAxis: [
{
id: 'internet-usage',
colorMap: {
type: 'continuous',
min: 0,
max: 100,
color: ['#e3f2fd', '#0d47a1'],
unknownColor: 'gray',
},
},
],
height: 360,
series: [
{
type: 'mapShape',
label: 'Internet usage',
data: Object.keys(countryData).map((code) => ({
name: code,
label: countryData[code].country,
colorValue: internetUsageByCountry[code],
})),
valueFormatter: (point: MapShapeValueType) =>
point.colorValue == null ? 'No data' : `${point.colorValue.toFixed(1)}%`,
},
],
} as const;