### Install Graphic Walker with npm Source: https://docs.kanaries.net/graphic-walker/index Install the Graphic Walker package from npm. ```bash npm install @kanaries/graphic-walker ``` -------------------------------- ### Install @kanaries/graphic-walker with npm, yarn, or pnpm Source: https://docs.kanaries.net/graphic-walker/getting-started Install the package using your preferred package manager. Choose one of the three commands. ```bash # npm npm install @kanaries/graphic-walker ``` ```bash # yarn yarn add @kanaries/graphic-walker ``` ```bash # pnpm pnpm add @kanaries/graphic-walker ``` -------------------------------- ### Svelte integration example Source: https://docs.kanaries.net/graphic-walker/api-reference/vanilla-js Mount GraphicWalker in a Svelte component using onMount and bind:this. ```svelte
``` -------------------------------- ### Install DuckDB WASM package Source: https://docs.kanaries.net/graphic-walker/guides/computation Install the optional @kanaries/graphic-walker-duckdb package to enable SQL-based aggregation in the browser for better client-side performance with larger datasets. ```bash npm install @kanaries/graphic-walker-duckdb ``` -------------------------------- ### Usage via CDN - UMD build example Source: https://docs.kanaries.net/graphic-walker/api-reference/vanilla-js Load Graphic Walker via CDN using the UMD build. The example includes an HTML page with a script tag and inline JavaScript that calls GraphicWalker.embedGraphicWalker. ```html Graphic Walker
``` -------------------------------- ### Basic Table Example Source: https://docs.kanaries.net/graphic-walker/api-reference/table-walker Renders a basic interactive table with client-side data and field definitions. The component is wrapped in a div with a fixed height. ```typescript import { TableWalker } from '@kanaries/graphic-walker'; function DataTable({ data, fields }) { return (
); } ``` -------------------------------- ### Vue 3 integration example Source: https://docs.kanaries.net/graphic-walker/api-reference/vanilla-js Mount GraphicWalker in a Vue 3 component using a template ref and onMounted lifecycle hook. ```html ``` -------------------------------- ### Usage with Bundlers - embedGraphicWalker example Source: https://docs.kanaries.net/graphic-walker/api-reference/vanilla-js Example of embedding GraphicWalker with data and fields using a bundler. The appearance option is set to 'media'. ```javascript import { embedGraphicWalker } from '@kanaries/graphic-walker'; const data = [ { city: 'New York', population: 8336817, area: 302.6 }, { city: 'Los Angeles', population: 3979576, area: 468.7 }, { city: 'Chicago', population: 2693976, area: 227.3 }, ]; const fields = [ { fid: 'city', name: 'City', semanticType: 'nominal', analyticType: 'dimension' }, { fid: 'population', name: 'Population', semanticType: 'quantitative', analyticType: 'measure' }, { fid: 'area', name: 'Area (sq mi)', semanticType: 'quantitative', analyticType: 'measure' }, ]; embedGraphicWalker(document.getElementById('app'), { data, fields, appearance: 'media', }); ``` -------------------------------- ### Built-in chart theme with vizThemeConfig Source: https://docs.kanaries.net/graphic-walker/guides/theming Use a built-in theme by passing its name to `vizThemeConfig`. Example uses 'streamlit' theme. ```jsx ``` -------------------------------- ### IChart configuration example for a line chart Source: https://docs.kanaries.net/graphic-walker/guides/chart-types Shows a complete IChart configuration for a line chart with encodings for rows, columns, color, and layout settings. Use as a template for defining charts in Graphic Walker, adjusting geoms, coordSystem, and encodings as needed. ```typescript const chart: IChart = { visId: 'example', name: 'Sales Trend', encodings: { dimensions: [], measures: [], rows: [{ fid: 'sales', name: 'Sales', analyticType: 'measure', semanticType: 'quantitative' }], columns: [{ fid: 'month', name: 'Month', analyticType: 'dimension', semanticType: 'temporal' }], color: [{ fid: 'region', name: 'Region', analyticType: 'dimension', semanticType: 'nominal' }], opacity: [], size: [], shape: [], theta: [], radius: [], longitude: [], latitude: [], geoId: [], details: [], filters: [], text: [], }, config: { defaultAggregated: true, geoms: ['line'], coordSystem: 'generic', limit: -1, }, layout: { showTableSummary: false, stack: 'none', showActions: false, interactiveScale: true, zeroScale: true, size: { mode: 'auto', width: 800, height: 400 }, format: {}, resolve: {}, }, }; ``` -------------------------------- ### Custom Vega config for chart themes Source: https://docs.kanaries.net/graphic-walker/guides/theming Pass a full Vega/Vega-Lite config object to `vizThemeConfig` for granular control over chart rendering. The example defines a customTheme object with colors for various chart elements. ```jsx const customTheme = { arc: { fill: '#4c78a8' }, area: { fill: '#4c78a8' }, bar: { fill: '#4c78a8' }, line: { stroke: '#4c78a8' }, point: { fill: '#4c78a8' }, axis: { domainColor: '#888888', gridColor: '#e0e0e0', tickColor: '#888888', }, }; ``` -------------------------------- ### Read-Only Table Example Source: https://docs.kanaries.net/graphic-walker/api-reference/table-walker Disables filtering, sorting, and column profiling, and sets the page size to 50 rows per page. ```typescript ``` -------------------------------- ### Sort step: sort descending by field Source: https://docs.kanaries.net/graphic-walker/guides/computation Sort step to sort results. This example sorts descending by the 'sum_revenue' field. ```json { "type": "sort", "sort": "descending", "by": ["sum_revenue"] } ``` -------------------------------- ### GraphicRenderer Example with Saved Charts Source: https://docs.kanaries.net/graphic-walker/api-reference/graphic-renderer Shows how to render saved charts with GraphicRenderer. Defines a savedCharts array of IChart objects and a Dashboard component that passes data, fields, chart, and appearance props. ```tsx import { GraphicRenderer } from '@kanaries/graphic-walker'; import type { IChart } from '@kanaries/graphic-walker'; const savedCharts: IChart[] = [ { visId: 'chart-1', name: 'Monthly Revenue', encodings: { dimensions: [], measures: [], rows: [{ fid: 'revenue', name: 'Revenue', analyticType: 'measure', semanticType: 'quantitative' }], columns: [{ fid: 'month', name: 'Month', analyticType: 'dimension', semanticType: 'temporal' }], color: [], opacity: [], size: [], shape: [], theta: [], radius: [], longitude: [], latitude: [], geoId: [], details: [], filters: [], text: [], }, config: { defaultAggregated: true, geoms: ['line'], coordSystem: 'generic', limit: -1, }, layout: { showTableSummary: false, stack: 'none', showActions: false, interactiveScale: true, zeroScale: true, size: { mode: 'auto', width: 800, height: 400 }, format: {}, resolve: {}, }, }, ]; function Dashboard() { return ( ); } ``` -------------------------------- ### Transform step: compute derived field with log10 Source: https://docs.kanaries.net/graphic-walker/guides/computation Transform step to compute derived fields. This example creates a new field 'log_revenue' using the log10 operator on the 'revenue' field. ```json { "type": "transform", "transform": [ { "key": "log_revenue", "expression": { "op": "log10", "params": [{ "type": "field", "value": "revenue" }], "as": "log_revenue" } } ] } ``` -------------------------------- ### Setup IGWHandler ref for GraphicWalker export Source: https://docs.kanaries.net/graphic-walker/guides/chart-export Sets up a React component that uses a ref to access the GraphicWalker export API. The ref is passed to the GraphicWalker component to enable programmatic chart export. ```jsx import { useRef } from 'react'; import { GraphicWalker } from '@kanaries/graphic-walker'; import type { IGWHandler } from '@kanaries/graphic-walker'; function App() { const gwRef = useRef(null); return ( ); } ``` -------------------------------- ### Remote Mode: PureRenderer with computation function Source: https://docs.kanaries.net/graphic-walker/api-reference/pure-renderer Use this snippet to embed a PureRenderer in remote mode, where data is fetched via a computation function. The computation function posts the payload to '/api/query' and returns the JSON response. Requires the visualState, visualConfig, and visualLayout objects defined in the local mode example. ```tsx import { PureRenderer } from '@kanaries/graphic-walker'; import type { IComputationFunction } from '@kanaries/graphic-walker'; const computation: IComputationFunction = async (payload) => { const res = await fetch('/api/query', { method: 'POST', body: JSON.stringify(payload), headers: { 'Content-Type': 'application/json' }, }); return res.json(); }; function RemoteChart() { return ( ); } ``` -------------------------------- ### Client-side computation with data prop Source: https://docs.kanaries.net/graphic-walker/guides/computation Pass the data prop to GraphicWalker to run all computations in a Web Worker on the client. This is the simplest setup with no backend required, but the dataset must fit in browser memory. ```jsx ``` -------------------------------- ### Load CSV data with Papa Parse and render GraphicWalker Source: https://docs.kanaries.net/graphic-walker/getting-started Use Papa Parse to fetch and parse a CSV file, auto-generate field definitions from column types, and render the GraphicWalker component once data is loaded. Requires installing @kanaries/graphic-walker and papaparse. ```jsx import { GraphicWalker } from '@kanaries/graphic-walker'; import Papa from 'papaparse'; import { useState, useEffect } from 'react'; function App() { const [data, setData] = useState([]); const [fields, setFields] = useState([]); useEffect(() => { Papa.parse('/data.csv', { download: true, header: true, dynamicTyping: true, complete(results) { setData(results.data); // Auto-generate field definitions from columns const cols = Object.keys(results.data[0] || {}); setFields( cols.map(col => ({ fid: col, name: col, semanticType: typeof results.data[0][col] === 'number' ? 'quantitative' : 'nominal', analyticType: typeof results.data[0][col] === 'number' ? 'measure' : 'dimension', })) ); }, }); }, []); if (!data.length) return
Loading...
; return ; } ``` -------------------------------- ### Fixed Size: PureRenderer with overrideSize Source: https://docs.kanaries.net/graphic-walker/api-reference/pure-renderer Use this snippet to render a PureRenderer with a fixed size, overriding the default size configuration. The overrideSize prop sets the mode to 'fixed' with width 400 and height 300. Requires the data, visualState, and visualConfig objects from the local mode example. ```tsx ``` -------------------------------- ### View step: aggregate, raw, fold, and bin queries Source: https://docs.kanaries.net/graphic-walker/guides/computation View step variants for aggregation or data selection. Includes aggregate query (sum and count), raw query (field selection), fold query (unpivot), and bin query (binning). The aggregate shows groupBy and measures, fold uses foldBy and new columns, and bin creates a bin column with binSize. ```json { "type": "view", "query": [{ "op": "aggregate", "groupBy": ["country", "product"], "measures": [ { "field": "revenue", "agg": "sum", "asFieldKey": "sum_revenue" }, { "field": "revenue", "agg": "count", "asFieldKey": "count_records" } ] }] } ``` ```json { "type": "view", "query": [{ "op": "raw", "fields": ["country", "product", "revenue", "date"] }] } ``` ```json { "type": "view", "query": [{ "op": "fold", "foldBy": ["q1_sales", "q2_sales", "q3_sales", "q4_sales"], "newFoldKeyCol": "quarter", "newFoldValueCol": "sales" }] } ``` ```json { "type": "view", "query": [{ "op": "bin", "binBy": "age", "newBinCol": "age_bin", "binSize": 10 }] } ``` -------------------------------- ### Using the geoList Prop for User-Selectable Geographic Datasets Source: https://docs.kanaries.net/graphic-walker/guides/geographic Provide a list of geographic datasets that users can choose from in the UI. Each item specifies the type (GeoJSON or TopoJSON), a name, and a URL to load the data. ```jsx ``` -------------------------------- ### TopoJSON Support with objectKey Source: https://docs.kanaries.net/graphic-walker/guides/geographic Use TopoJSON files, which are more compact than GeoJSON. Specify the objectKey to select which layer to use; it defaults to the first key in topology.objects. ```jsx ``` -------------------------------- ### View Step - Bin Query Source: https://docs.kanaries.net/graphic-walker/guides/computation Bins a numeric field into discrete intervals. The view step with op "bin". ```APIDOC ## View Step - Bin Query ### Description Bins a numeric field into discrete intervals. The workflow step type is "view" with query op "bin". ### Step Type `view` ### Query Operation `bin` ### Parameters - **binBy** (string) - Required - Field to bin. - **newBinCol** (string) - Required - Name of the new bin column. - **binSize** (number) - Required - Size of each bin. ### Example ```json { "type": "view", "query": [{ "op": "bin", "binBy": "age", "newBinCol": "age_bin", "binSize": 10 }] } ``` ``` -------------------------------- ### IUIThemeConfig Source: https://docs.kanaries.net/graphic-walker/api-reference/types Interface defining custom UI colors for light and dark modes. The IColorSet sub-interface specifies properties for background, foreground, primary colors, and optional overrides. ```APIDOC ```typescript interface IUIThemeConfig { light: IColorSet; dark: IColorSet; } interface IColorSet { background: string; foreground: string; primary: string; 'primary-foreground': string; muted: string; 'muted-foreground': string; border: string; ring: string; // Optional overrides card?: string; 'card-foreground'?: string; popover?: string; 'popover-foreground'?: string; secondary?: string; 'secondary-foreground'?: string; accent?: string; 'accent-foreground'?: string; destructive?: string; 'destructive-foreground'?: string; dimension?: string; measure?: string; input?: string; } ``` ``` -------------------------------- ### IVisualLayout interface Source: https://docs.kanaries.net/graphic-walker/api-reference/types Controls chart layout and appearance. Includes showTableSummary, format (number/time/normalized number formats), optional primaryColor and colorPalette, optional scale, resolve flags for shared scales, size mode ('auto'|'fixed'|'full') with width/height, optional useSvg, interactiveScale, stack mode, showActions, zeroScale, optional background, optional choropleth flags, optional renderer ('vega-lite'|'observable-plot'), optional geoMapTileUrl, optional geojson, optional geoKey, and optional geoUrl. ```typescript interface IVisualLayout { showTableSummary: boolean; format: { numberFormat?: string; timeFormat?: string; normalizedNumberFormat?: string; }; primaryColor?: string; colorPalette?: string; scale?: IConfigScaleSet; resolve: { x?: boolean; y?: boolean; color?: boolean; opacity?: boolean; shape?: boolean; size?: boolean; }; size: { mode: 'auto' | 'fixed' | 'full'; width: number; height: number; }; useSvg?: boolean; interactiveScale: boolean; stack: IStackMode; showActions: boolean; zeroScale: boolean; background?: string; scaleIncludeUnmatchedChoropleth?: boolean; showAllGeoshapeInChoropleth?: boolean; renderer?: 'vega-lite' | 'observable-plot'; geoMapTileUrl?: string; geojson?: FeatureCollection; geoKey?: string; geoUrl?: { type: 'GeoJSON' | 'TopoJSON'; url: string }; } ``` -------------------------------- ### Import PureRenderer Source: https://docs.kanaries.net/graphic-walker/api-reference/pure-renderer Import the PureRenderer component from the @kanaries/graphic-walker package. ```typescript import { PureRenderer } from '@kanaries/graphic-walker'; ``` -------------------------------- ### Set computation timeout to 30 seconds in GraphicWalker Source: https://docs.kanaries.net/graphic-walker/guides/computation Use the computationTimeout prop to set the maximum computation time in milliseconds. The example sets it to 30000 ms (30 seconds). This setting is supported in both client-side and server-side modes. ```jsx ``` -------------------------------- ### Basic Explorer: Render GraphicWalker with data and fields Source: https://docs.kanaries.net/graphic-walker/api-reference/graphic-walker Use this snippet to render the GraphicWalker component with your data and fields. It imports the component from '@kanaries/graphic-walker' and passes the required props. ```jsx import { GraphicWalker } from '@kanaries/graphic-walker'; function Explorer({ data, fields }) { return ; } ``` -------------------------------- ### IUIThemeConfig and IColorSet interfaces Source: https://docs.kanaries.net/graphic-walker/api-reference/types Defines custom UI colors for light and dark modes. IColorSet includes required and optional color properties for the UI theme. ```typescript interface IUIThemeConfig { light: IColorSet; dark: IColorSet; } interface IColorSet { background: string; foreground: string; primary: string; 'primary-foreground': string; muted: string; 'muted-foreground': string; border: string; ring: string; // Optional overrides card?: string; 'card-foreground'?: string; popover?: string; 'popover-foreground'?: string; secondary?: string; 'secondary-foreground'?: string; accent?: string; 'accent-foreground'?: string; destructive?: string; 'destructive-foreground'?: string; dimension?: string; measure?: string; input?: string; } ``` -------------------------------- ### Import embed* functions from @kanaries/graphic-walker Source: https://docs.kanaries.net/graphic-walker/api-reference/vanilla-js Import the embed functions needed to render Graphic Walker components without React. ```javascript import { embedGraphicWalker, embedGraphicRenderer, embedPureRenderer, embedTableWalker, } from '@kanaries/graphic-walker'; ``` -------------------------------- ### Render GraphicWalker with sample data and fields Source: https://docs.kanaries.net/graphic-walker/getting-started Imports the GraphicWalker component, defines sample data and field definitions, and renders the component in an App function. The fields array requires semanticType and analyticType annotations for each field. ```jsx import { GraphicWalker } from '@kanaries/graphic-walker'; const data = [ { date: '2024-01-01', product: 'A', sales: 120, profit: 40 }, { date: '2024-01-01', product: 'B', sales: 200, profit: 80 }, { date: '2024-02-01', product: 'A', sales: 150, profit: 55 }, { date: '2024-02-01', product: 'B', sales: 180, profit: 65 }, ]; const fields = [ { fid: 'date', name: 'Date', semanticType: 'temporal', analyticType: 'dimension' }, { fid: 'product', name: 'Product', semanticType: 'nominal', analyticType: 'dimension' }, { fid: 'sales', name: 'Sales', semanticType: 'quantitative', analyticType: 'measure' }, { fid: 'profit', name: 'Profit', semanticType: 'quantitative', analyticType: 'measure' }, ]; function App() { return ; } export default App; ``` -------------------------------- ### Dark mode with appearance prop Source: https://docs.kanaries.net/graphic-walker/guides/theming Control dark mode with the `appearance` prop. Options: 'media' (follows OS preference, default), 'light', and 'dark'. ```jsx // Follow user's OS preference (default) // Always light // Always dark ``` -------------------------------- ### Navigate to chart tab before export with openChart() Source: https://docs.kanaries.net/graphic-walker/guides/chart-export Switches to a specific chart tab using openChart() with a 0-indexed index, then waits for render and exports. Use this to export a chart that is not currently visible. ```javascript // Export the third chart gwRef.current.openChart(2); // 0-indexed // Wait for render, then export const result = await safeExport(); ``` -------------------------------- ### Next.js dynamic import with ssr: false Source: https://docs.kanaries.net/graphic-walker/faq Use this snippet in Next.js to load Graphic Walker only on the client side, avoiding server-side rendering issues. ```javascript import dynamic from 'next/dynamic'; const GraphicWalker = dynamic( () => import('@kanaries/graphic-walker').then(m => m.GraphicWalker), { ssr: false } ); ``` -------------------------------- ### Export charts using IGWHandler methods Source: https://docs.kanaries.net/graphic-walker/api-reference/graphic-walker Shows how to export the current chart as SVG and iterate over all charts using exportChartList. The exportChart method defaults to 'svg' mode. ```ts async function handleExport() { if (!gwRef.current) return; // Export current chart as SVG const result = await gwRef.current.exportChart('svg'); console.log(result.title, result.charts); // Export all charts for await (const item of gwRef.current.exportChartList('data-url')) { console.log(`Chart ${item.index + 1}/${item.total}:`, item.data.title); } } ``` -------------------------------- ### Set useSvg: true in defaultConfig Source: https://docs.kanaries.net/graphic-walker/faq Use this snippet to enable SVG rendering for sharper output, though it may be slower for large datasets. ```jsx ``` -------------------------------- ### Import GraphicRenderer Source: https://docs.kanaries.net/graphic-walker/api-reference/graphic-renderer Import the GraphicRenderer component from the @kanaries/graphic-walker package. ```typescript import { GraphicRenderer } from '@kanaries/graphic-walker'; ``` -------------------------------- ### Save and restore chart configurations Source: https://docs.kanaries.net/graphic-walker/faq Use this snippet to save chart configurations to localStorage and restore them by passing the saved array to the chart prop. ```javascript // Save const charts = storeRef.current?.exportAllCharts(); localStorage.setItem('gw-charts', JSON.stringify(charts)); // Restore const saved = JSON.parse(localStorage.getItem('gw-charts') || '[]'); ``` -------------------------------- ### Import GraphicWalker component Source: https://docs.kanaries.net/graphic-walker/api-reference/graphic-walker Import the GraphicWalker component from the @kanaries/graphic-walker package. This is the primary component for building an interactive data exploration interface. ```javascript import { GraphicWalker } from '@kanaries/graphic-walker'; ``` -------------------------------- ### IVisualConfigNew interface Source: https://docs.kanaries.net/graphic-walker/api-reference/types Controls visualization behavior. Includes defaultAggregated, geoms (geometry types), optional coordSystem ('generic' or 'geographic'), limit (row limit, -1 for no limit), optional folds, and optional timezoneDisplayOffset. ```typescript interface IVisualConfigNew { defaultAggregated: boolean; // Whether to aggregate measures by default geoms: string[]; // Geometry types: 'bar', 'line', 'area', 'point', 'circle', 'tick', 'rect', 'arc', 'boxplot', 'table', 'poi', 'choropleth' coordSystem?: 'generic' | 'geographic'; // Coordinate system limit: number; // Row limit (-1 for no limit) folds?: string[]; // Fields to fold/unpivot timezoneDisplayOffset?: number; // Timezone offset for display } ``` -------------------------------- ### View Step - Raw Query Source: https://docs.kanaries.net/graphic-walker/guides/computation Selects raw fields without aggregation. The view step with op "raw". ```APIDOC ## View Step - Raw Query ### Description Selects raw fields without any aggregation. The workflow step type is "view" with query op "raw". ### Step Type `view` ### Query Operation `raw` ### Parameters - **fields** (array of strings) - Required - List of field names to select. ### Example ```json { "type": "view", "query": [{ "op": "raw", "fields": ["country", "product", "revenue", "date"] }] } ``` ``` -------------------------------- ### Point Maps (POI) Data and Fields Source: https://docs.kanaries.net/graphic-walker/guides/geographic Define data with longitude and latitude fields for point maps. Set coordSystem to 'geographic' and geoms to ['poi'] in the chart config, then encode longitude and latitude fields in the corresponding channels. ```jsx const data = [ { city: 'New York', lng: -74.006, lat: 40.7128, population: 8336817 }, { city: 'Los Angeles', lng: -118.2437, lat: 34.0522, population: 3979576 }, ]; const fields = [ { fid: 'city', name: 'City', semanticType: 'nominal', analyticType: 'dimension' }, { fid: 'lng', name: 'Longitude', semanticType: 'quantitative', analyticType: 'dimension' }, { fid: 'lat', name: 'Latitude', semanticType: 'quantitative', analyticType: 'dimension' }, { fid: 'population', name: 'Population', semanticType: 'quantitative', analyticType: 'measure' }, ]; ``` -------------------------------- ### Filter step: apply row-level filters Source: https://docs.kanaries.net/graphic-walker/guides/computation Filter step to apply row-level filters before aggregation. Shows filters on 'country' (one of US/UK/DE) and 'revenue' (range with lower bound 1000 and no upper bound). ```json { "type": "filter", "filters": [ { "fid": "country", "rule": { "type": "one of", "value": ["US", "UK", "DE"] } }, { "fid": "revenue", "rule": { "type": "range", "value": [1000, null] } } ] } ``` -------------------------------- ### Import types from @kanaries/graphic-walker Source: https://docs.kanaries.net/graphic-walker/api-reference/types Import the core types for type-safe usage in your project. ```typescript import type { IMutField, IChart, DraggableFieldState, IVisualConfigNew, IVisualLayout, IFilterRule, IComputationFunction, IThemeKey, IDarkMode, IUIThemeConfig, IChannelScales, } from '@kanaries/graphic-walker'; ``` -------------------------------- ### View Step - Aggregate Query Source: https://docs.kanaries.net/graphic-walker/guides/computation Aggregates data by grouping and computing measures. The view step with op "aggregate". ```APIDOC ## View Step - Aggregate Query ### Description Aggregates data by grouping fields and computing measures. The workflow step type is "view" with query op "aggregate". ### Step Type `view` ### Query Operation `aggregate` ### Parameters - **groupBy** (array of strings) - Required - Fields to group by. - **measures** (array) - Required - List of measure objects. - **field** (string) - Required - Field to aggregate. - **agg** (string) - Required - Aggregation function (e.g., "sum", "count"). - **asFieldKey** (string) - Required - Output field key. ### Example ```json { "type": "view", "query": [{ "op": "aggregate", "groupBy": ["country", "product"], "measures": [ { "field": "revenue", "agg": "sum", "asFieldKey": "sum_revenue" }, { "field": "revenue", "agg": "count", "asFieldKey": "count_records" } ] }] } ``` ``` -------------------------------- ### Custom Map Tiles via geoMapTileUrl Source: https://docs.kanaries.net/graphic-walker/guides/geographic Customize the base map tile URL using the geoMapTileUrl property in IVisualLayout. Provide a tile URL template, such as OpenStreetMap. ```jsx ``` -------------------------------- ### Import TableWalker Source: https://docs.kanaries.net/graphic-walker/api-reference/table-walker Import the TableWalker component from the graphic-walker package. ```typescript import { TableWalker } from '@kanaries/graphic-walker'; ``` -------------------------------- ### Dark Mode and Theme: Set appearance and vizThemeConfig Source: https://docs.kanaries.net/graphic-walker/api-reference/graphic-walker Use this snippet to enable dark mode and apply a Streamlit theme. Set the 'appearance' prop to 'dark' and 'vizThemeConfig' to 'streamlit'. ```jsx ``` -------------------------------- ### Download export as SVG file Source: https://docs.kanaries.net/graphic-walker/guides/chart-export Downloads the current chart as an SVG file. Creates a Blob from the SVG data, triggers a download link, and revokes the object URL. ```typescript async function downloadSVG() { if (!gwRef.current) return; const result = await gwRef.current.exportChart('svg'); const svgData = result.charts[0]?.data; if (!svgData) return; const blob = new Blob([svgData], { type: 'image/svg+xml' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `${result.title || 'chart'}.svg`; link.click(); URL.revokeObjectURL(url); } ``` -------------------------------- ### IThemeKey type Source: https://docs.kanaries.net/graphic-walker/api-reference/types Defines the available theme keys for Graphic Walker visualizations. ```typescript type IThemeKey = 'vega' | 'g2' | 'streamlit'; ``` -------------------------------- ### IDataQueryPayload interface Source: https://docs.kanaries.net/graphic-walker/api-reference/types Defines the payload for data queries, containing a workflow of steps and optional pagination parameters. ```typescript interface IDataQueryPayload { workflow: IDataQueryWorkflowStep[]; // Processing pipeline limit?: number; offset?: number; } ``` -------------------------------- ### Local Mode: Embed PureRenderer with rawData Source: https://docs.kanaries.net/graphic-walker/api-reference/pure-renderer Use this snippet to embed a PureRenderer in local mode, where data is passed directly via the rawData prop. It defines the required visualState, visualConfig, and visualLayout objects with a bar chart configuration. The component renders with automatic sizing (width 600, height 400) and default aggregation enabled. ```tsx import { PureRenderer } from '@kanaries/graphic-walker'; import type { DraggableFieldState, IVisualConfigNew, IVisualLayout } from '@kanaries/graphic-walker'; const data = [ { category: 'A', value: 100 }, { category: 'B', value: 200 }, { category: 'C', value: 150 }, ]; const visualState: DraggableFieldState = { dimensions: [], measures: [], rows: [{ fid: 'value', name: 'Value', analyticType: 'measure', semanticType: 'quantitative' }], columns: [{ fid: 'category', name: 'Category', analyticType: 'dimension', semanticType: 'nominal' }], color: [], opacity: [], size: [], shape: [], theta: [], radius: [], longitude: [], latitude: [], geoId: [], details: [], filters: [], text: [], }; const visualConfig: IVisualConfigNew = { defaultAggregated: true, geoms: ['bar'], coordSystem: 'generic', limit: -1, }; const visualLayout: IVisualLayout = { showTableSummary: false, stack: 'stack', showActions: false, interactiveScale: false, zeroScale: true, size: { mode: 'auto', width: 600, height: 400 }, format: {}, resolve: {}, }; function ChartEmbed() { return ( ); } ``` -------------------------------- ### View Step - Fold Query Source: https://docs.kanaries.net/graphic-walker/guides/computation Unpivots columns into rows. The view step with op "fold". ```APIDOC ## View Step - Fold Query ### Description Unpivots multiple columns into key-value pairs. The workflow step type is "view" with query op "fold". ### Step Type `view` ### Query Operation `fold` ### Parameters - **foldBy** (array of strings) - Required - Columns to unpivot. - **newFoldKeyCol** (string) - Required - Name of the new key column. - **newFoldValueCol** (string) - Required - Name of the new value column. ### Example ```json { "type": "view", "query": [{ "op": "fold", "foldBy": ["q1_sales", "q2_sales", "q3_sales", "q4_sales"], "newFoldKeyCol": "quarter", "newFoldValueCol": "sales" }] } ``` ``` -------------------------------- ### IMutField Source: https://docs.kanaries.net/graphic-walker/api-reference/types The IMutField interface defines the structure for a mutable field configuration in Graphic Walker. ```APIDOC ## TypeScript Interface: IMutField ### Description Represents a mutable field configuration used to define how data fields are interpreted and displayed. ### Interface Definition ```typescript interface IMutField { fid: string; // Field ID — must match a key in your data objects name?: string; // Display name shown in the UI semanticType: ISemanticType; // Data type classification analyticType: IAnalyticType; // Analysis role basename?: string; // Base name for derived fields disable?: boolean; // Hide this field from the UI path?: string[]; // Path for nested data offset?: number; // Timezone offset for temporal fields } ``` ### Properties - **fid** (string) - Required - Field ID, must match a key in your data objects - **name** (string) - Optional - Display name shown in the UI - **semanticType** (ISemanticType) - Required - Data type classification - **analyticType** (IAnalyticType) - Required - Analysis role - **basename** (string) - Optional - Base name for derived fields - **disable** (boolean) - Optional - Hide this field from the UI - **path** (string[]) - Optional - Path for nested data - **offset** (number) - Optional - Timezone offset for temporal fields ``` -------------------------------- ### Download export as PNG data URL Source: https://docs.kanaries.net/graphic-walker/guides/chart-export Downloads the current chart as a PNG file using the data URL from exportChart('data-url'). Creates an anchor element and triggers a click. ```typescript async function downloadPNG() { if (!gwRef.current) return; const result = await gwRef.current.exportChart('data-url'); const dataUrl = result.charts[0]?.data; if (!dataUrl) return; const link = document.createElement('a'); link.href = dataUrl; link.download = `${result.title || 'chart'}.png`; link.click(); } ``` -------------------------------- ### Set fixed chart size in defaultConfig Source: https://docs.kanaries.net/graphic-walker/faq Use this snippet to set a fixed chart size with width and height in pixels. ```jsx ``` -------------------------------- ### IStackMode Source: https://docs.kanaries.net/graphic-walker/api-reference/types Type alias for stacking modes used in visualizations. ```APIDOC ```typescript type IStackMode = 'none' | 'stack' | 'normalize' | 'zero' | 'center'; ``` ``` -------------------------------- ### IComputationFunction Source: https://docs.kanaries.net/graphic-walker/guides/computation The main computation function signature that receives a data query payload and returns a promise of rows. ```APIDOC ## IComputationFunction ### Description Defines the function signature for a custom computation handler. It receives a data query payload and returns a promise of rows. ### Signature ```typescript type IComputationFunction = (payload: IDataQueryPayload) => Promise; ``` ### Parameters - **payload** (IDataQueryPayload) - Required - The data query payload containing the workflow steps and optional limit/offset. ### Returns - **Promise** - A promise that resolves to an array of rows. ### IDataQueryPayload ```typescript interface IDataQueryPayload { workflow: IDataQueryWorkflowStep[]; limit?: number; offset?: number; } ``` ### Workflow Steps - **filter** - Apply row-level filters before aggregation. - **transform** - Compute derived fields. - **view** - Aggregate or select data (supports aggregate, raw, fold, bin). - **sort** - Sort the results. ``` -------------------------------- ### IDarkMode Source: https://docs.kanaries.net/graphic-walker/api-reference/types Type alias for dark mode configuration options. ```APIDOC ```typescript type IDarkMode = 'media' | 'light' | 'dark'; ``` ``` -------------------------------- ### IThemeKey Source: https://docs.kanaries.net/graphic-walker/api-reference/types Type alias for available theme key identifiers. ```APIDOC ```typescript type IThemeKey = 'vega' | 'g2' | 'streamlit'; ``` ``` -------------------------------- ### Express.js endpoint for workflow-based SQL query Source: https://docs.kanaries.net/graphic-walker/guides/computation Defines a POST endpoint that processes a workflow to build and execute a SQL query. Supports filter, view (aggregate/raw), and sort steps, with optional limit and offset. Simplified for demonstration; use parameterized queries in production to prevent SQL injection. ```javascript app.post('/api/data/query', async (req, res) => { const { workflow, limit, offset } = req.body; let query = 'SELECT * FROM dataset'; const params = []; for (const step of workflow) { if (step.type === 'filter') { const conditions = step.filters.map(f => { if (f.rule.type === 'range') { const [min, max] = f.rule.value; if (min !== null && max !== null) return `${f.fid} BETWEEN ${min} AND ${max}`; if (min !== null) return `${f.fid} >= ${min}`; if (max !== null) return `${f.fid} <= ${max}`; } if (f.rule.type === 'one of') { return `${f.fid} IN (${f.rule.value.map(v => `'${v}'`).join(',')})`; } return '1=1'; }); query += ` WHERE ${conditions.join(' AND ')}`; } if (step.type === 'view') { for (const q of step.query) { if (q.op === 'aggregate') { const groupCols = q.groupBy.join(', '); const measureCols = q.measures.map(m => `${m.agg.toUpperCase()}(${m.field}) AS ${m.asFieldKey}` ).join(', '); query = `SELECT ${groupCols}, ${measureCols} FROM (${query}) t GROUP BY ${groupCols}`; } if (q.op === 'raw') { query = `SELECT ${q.fields.join(', ')} FROM (${query}) t`; } } } if (step.type === 'sort') { query += ` ORDER BY ${step.by.join(', ')} ${step.sort === 'ascending' ? 'ASC' : 'DESC'}`; } } if (limit) query += ` LIMIT ${limit}`; if (offset) query += ` OFFSET ${offset}`; const results = await db.query(query); res.json(results); }); ``` -------------------------------- ### Use appearance prop for dark mode Source: https://docs.kanaries.net/graphic-walker/faq Use this snippet to enable dark mode with the appearance prop instead of the deprecated dark prop. ```jsx ``` -------------------------------- ### IStackMode type Source: https://docs.kanaries.net/graphic-walker/api-reference/types Defines the stacking modes for chart series. ```typescript type IStackMode = 'none' | 'stack' | 'normalize' | 'zero' | 'center'; ```