Bar
Categorical comparison on a shared quantitative baseline, with stacked, grouped and flipped layouts.
import { bar } from 'visdelta/bar';bar() compares categories through a shared quantitative baseline.
import { bar } from 'visdelta/bar';
import { transition } from 'visdelta/transition';
import 'visdelta/style.css';
const sales = [
{ region: 'North', channel: 'Online', revenue: 42 },
{ region: 'North', channel: 'Retail', revenue: 31 },
{ region: 'South', channel: 'Online', revenue: 28 },
{ region: 'South', channel: 'Retail', revenue: 36 },
{ region: 'East', channel: 'Online', revenue: 39 },
{ region: 'East', channel: 'Retail', revenue: 22 },
{ region: 'West', channel: 'Online', revenue: 47 },
{ region: 'West', channel: 'Retail', revenue: 26 },
];
const detailed = bar(sales)
.x('region', { label: 'Region' })
.y('revenue', { label: 'Revenue ($k)' })
.key(['region', 'channel'])
.breakdown('channel')
.color('channel');
const from = detailed.rollup();
const to = detailed;
const change = await transition(from, to, { target: '#chart' });
change.play({ duration: 800 }); // or change.progress(0.5)
Methods
| Method | Meaning |
|---|---|
.flip(options?) | Switch between vertical and horizontal bars |
.breakdown(field?, options?) | Split totals into detail segments |
.rollup(groupby?, options?) | Combine detail into totals |
.layout('simple' | 'grouped' | 'stacked' | 'diverging', options?) | Change the bar layout |
.breakdown() defaults to a stacked layout and the sum operator. It declares
detail, not colour; add .color(field) when the segments should be coloured.
It reuses the declared x category and y measure, preserving an explicit y label,
format, domain and scale.
const detailed = bar(sales)
.x('region')
.y('revenue')
.breakdown('channel')
.color('channel');
const totals = detailed.rollup();
const grouped = detailed.layout('grouped');
const horizontal = detailed.flip();Transition behaviour
- Baselines are preserved. Entering and exiting bars grow from and shrink to the baseline.
- Additive splits stay readable. For
sumandcount, a total splitting into grouped detail passes through a stacked stage that preserves the total. The merge reuses the same frames backward. - Reaggregation is composed. Regrouping the same records, for example from totals by year to totals by location, routes through their common grain.
- Focus and sorts are staged. A focused detail merges before the focus changes; detail merges before a sort by total.
- Orientation changes are coordinate transitions.
.flip()uses Bar's direct coordinate route. A flip combined with a Grain change is not split into planner stages.
Bar marks always use square corners, in every layout and throughout transitions.
Examples
Edit a Bar chart yourself in the playground: sort, split or regroup.
Limits
Bar's declaration planner supports one aggregate measure over inline rows, with a category and optional detail field. Wide folds, multiple aggregates, unresolved data, mismatched aliases or mark keys, and reorientation combined with a Grain change are outside it. Those pairs keep Bar's chart-authored route or its ordinary direct transition.
Inspect Bar layout and author complete grouped states
Import inspectBarSpec from visdelta/bar and pass a public/compiled spec
(for builders, call .toSpec()). This is a synchronous, DOM-free declaration
inspection backed by the same Bar semantic model used by rendering.
status: "known" reports layout (simple, stacked, grouped, diverging),
orientation, categoryField, measureField, segmentField, offsetChannel
and distribution. For distribution layouts, distribution is a detached
object containing the effective normalize (none or percent) and the declared
segment order or negative/neutral/positive policy. It is null for ordinary
layouts, so a stacked layout alone does not imply 100% normalization.
Missing axis types/fields, wrong-axis offsets, mismatched detail/offset fields or
contradictory layout metadata produce status: "unknown", null facts and
path-specific diagnostics. Supply an already parsed spec, not a JSON string.
It does not load/validate data, inspect pixels, promise transition support, or
expand view.capabilities().editMethods. Use normal render validation and the
browser receipt to establish what was actually applied.
A color legend alone does not mean grouped. In canonical compiled Bar JSON:
- Vertical grouped bars use
encoding.xOffseton the categorical x axis. - Horizontal grouped bars use
encoding.yOffseton the categorical y axis. - The offset field identifies the same segments as
encoding.detail. - A stacked declaration has no grouped offset; adding color does not change layout.
For an explicit grouped request, compare facts from the current accepted spec and the builder-produced candidate. Claim “already grouped” only when the facts are known and match the request. An unchanged revision alone proves no layout change; the model's prose is not evidence. Unknown requires clarification or validation, not a guessed no-op.
import { bar, inspectBarSpec } from 'visdelta/bar';
const grouped = bar(rows).x('measure')
.y('amount', { label: 'Revenue ($k)' })
.breakdown('product').color('product').layout('grouped');
inspectBarSpec(grouped.toSpec()); // known, grouped, vertical, xOffset
inspectBarSpec(grouped.flip().toSpec()); // known, grouped, horizontal, yOffsetThe following complete specs are generated by
examples/authoring/bar-layouts.mjs; they use four tidy source rows and preserve
the same $290k total. Generate states with the builder instead of hand-patching
offset fields, aggregate grain or derived keys.
Vertical grouped
{
"data": [
{
"measure": "revenue",
"product": "Atlas",
"amount": 84
},
{
"measure": "revenue",
"product": "Beacon",
"amount": 62
},
{
"measure": "revenue",
"product": "Comet",
"amount": 96
},
{
"measure": "revenue",
"product": "Drift",
"amount": 48
}
],
"mark": "bar",
"encoding": {
"x": {
"field": "measure",
"type": "nominal",
"label": "Measure"
},
"y": {
"field": "amount",
"type": "quantitative",
"label": "Revenue ($k)"
},
"color": {
"field": "product",
"type": "nominal"
},
"detail": {
"field": "product",
"type": "nominal"
},
"xOffset": {
"field": "product",
"type": "nominal"
}
},
"transform": [
{
"aggregate": {
"groupby": [
"measure",
"product"
],
"fields": [
{
"op": "sum",
"field": "amount",
"as": "amount"
}
]
}
}
],
"meta": {
"object": {
"key": [
"measure",
"product"
],
"semantic": {
"entity": [
{
"field": "measure"
},
{
"field": "product"
}
],
"measure": {
"value": "amount"
}
}
}
}
}Horizontal grouped
{
"data": [
{
"measure": "revenue",
"product": "Atlas",
"amount": 84
},
{
"measure": "revenue",
"product": "Beacon",
"amount": 62
},
{
"measure": "revenue",
"product": "Comet",
"amount": 96
},
{
"measure": "revenue",
"product": "Drift",
"amount": 48
}
],
"mark": "bar",
"encoding": {
"x": {
"field": "amount",
"type": "quantitative",
"label": "Revenue ($k)"
},
"y": {
"field": "measure",
"type": "nominal",
"label": "Measure"
},
"color": {
"field": "product",
"type": "nominal"
},
"detail": {
"field": "product",
"type": "nominal"
},
"yOffset": {
"field": "product",
"type": "nominal"
}
},
"transform": [
{
"aggregate": {
"groupby": [
"measure",
"product"
],
"fields": [
{
"op": "sum",
"field": "amount",
"as": "amount"
}
]
}
}
],
"meta": {
"object": {
"key": [
"measure",
"product"
],
"semantic": {
"entity": [
{
"field": "measure"
},
{
"field": "product"
}
],
"measure": {
"value": "amount"
}
}
}
}
}Semantic layout edits
Prefer .layout('grouped') and .layout('stacked'). On a persistent view, use
view.edit({ requestId, baseRevision, edits: [{ method: 'layout', args: ['grouped'] }] }).
The Bar compiler maintains offsets and preserves grouping through flip(), even
after canonical JSON is rehydrated with new BarState(spec).
previewEdit(message) validates support for the exact accepted state and returns
the candidate spec without consuming a revision or request ID. Use delta to
inspect the proposed semantic changes and the edit receipt to confirm acceptance.
Sequential presentation batches preserve a supported folded pipeline, including
layout, flip, color and attention edits. Agents should request semantic operations;
canonical offsets are inspection and advanced-authoring details.
Likert responses: 100% stacked or centered divergence
Start with tidy nonnegative counts: one row per question and response category, including explicit zeros. These examples are synthetic: Transit has 100 valid responses, Parks 200, and Services 80. Equal percentage widths do not imply equal sample sizes or statistical certainty. The Playground story and Gallery include both layouts; search for “Likert”.
Use centered divergence when the pattern of disagreement and agreement is the main question. Prefer 100% stacks for absolute shares, grouped bars or dots for comparing a specific response category, and 100% stacks on narrow screens. Datawrapper explains the comparability and space costs, and warns that splitting neutral visually can invite a false interpretation as half approval and half opposition. Read the critique.
import { transition } from 'visdelta/transition';
import 'visdelta/style.css';
// Shared executable example; no second copy of its data or declaration.
export {from,to} from '../../examples/authoring/likert.mjs';
const change = await transition(from, to, { target: '#chart' });
change.play({ duration: 800 }); // or change.progress(0.5)
Two views of the same responses
The example below starts from rows in likert-survey.csv.
The Bar compiler generates positions; no negative data, duplicated neutral rows,
manual offsets or percentage preparation are needed. The brown/teal palette uses
a gray neutral and explicit response labels rather than red/green alone.
import { bar } from 'visdelta/bar';
const base = bar(rows)
.x('question', { label: 'Synthetic survey · n = valid responses' })
.y('count')
.breakdown('response')
.color('response', {
domain: ['Strongly disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly agree'],
range: ['#a6611a', '#dfc27d', '#bdbdbd', '#80cdc1', '#018571']
})
.flip();
const percent = base.layout('stacked', {
normalize: 'percent',
segments: ['Strongly disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly agree']
});
const diverging = base.layout('diverging', {
normalize: 'percent',
negative: ['Strongly disagree', 'Disagree'],
neutral: 'Neutral',
positive: ['Agree', 'Strongly agree']
});The full runnable fixture, including all 15 input rows, is
examples/authoring/likert.mjs in the repository. Changing between these two
states emits layout.rearrange; .flip() preserves the distribution policy and
emits the existing coordinate change. Each mark keeps its question/response key.
Read the center correctly
negative is ordered from the outer edge toward the center. positive is
ordered from the center outward. In a horizontal chart the reading order is
negative → neutral → positive, left to right; after a flip it is bottom to top.
This explicit order does not depend on row order or the color palette.
neutral: 'Neutral' places one rectangle across zero. A 30% neutral response
occupies −15% through +15%, but it still represents 30% neutral, never 15%
agreement and 15% disagreement. The zero line is a geometric alignment guide.
The signed axis gives positions, not category shares or a net score. Hover
shows the original count, unsigned share of all responses, and the question total.
Use neutral: null only for a questionnaire with no neutral category. Separate
neutral columns and multiple neutral categories are not supported.
Options and validation
normalizedefaults to'none'(count units).'percent'divides by the sum of all declared categories for that question, neutral included; position units become fractions, displayed as percentages. Each full row has total segment width 1, even when its two endpoints differ from another row's.- Diverging requires nonempty
negativeandpositivestring arrays plus an explicitneutralstring ornull. Names must be unique and disjoint. - Normalized stacked uses
segmentsin full reading order. Do not supplysegmentstogether with diverging side declarations. - Missing values, unknown/missing response categories, duplicate input cells, zero totals, nonfinite values and actual negative counts reject. Supply zero rows for observed categories with no responses; do not silently omit them.
- This initial implementation accepts tidy counts and the normal
sumbreakdown at the same count field. Fold pipelines, facets, custom domains/nonlinear scales and transitions that also change grain or transforms are unsupported. Validation checks raw counts before aggregation and the rendered endpoint afterward.
Ordinary .layout('stacked') retains the existing signed-value stacking behavior:
real negative values go below/left of zero. That is different from Likert side
classification. The D3 example
uses category signs with stackOffsetDiverging; it does not demonstrate centered
neutral responses. Neither layout computes a net score.
Edit and inspect the accepted state
Prefer semantic edits; canonical JSON is for inspection and transport:
const message = {
requestId: 'center-responses', baseRevision: view.snapshot().revision,
edits: [{ method: 'layout', args: ['diverging', {
normalize: 'percent', negative: ['Strongly disagree', 'Disagree'],
neutral: 'Neutral', positive: ['Agree', 'Strongly agree']
}] }]
};
const candidate = await view.previewEdit(message);
const receipt = await view.edit(message);inspectBarSpec(candidate.spec).distribution reports the declared normalization
and side/order policy; null means ordinary layout. Preview validates this exact
state without consuming a revision. The receipt confirms acceptance; invalid
endpoints leave the accepted chart unchanged. Distribution states support layout, flip,
color, focus, highlight, sort, whole-question where, and same-field axis options,
including sequential batches. .layout('grouped') or .layout('stacked') without distribution options
clears normalization and side declarations. Serialized new BarState(spec) retains
them through flip().
Highlight distribution responses without filtering
Bar distribution layouts support highlight in individual or compound edits. This preserves every response row, the full percentage denominator, mark
identity, colors, distribution policy and any focus scope. Only highlight attention
changes; an unmatched selector still leaves every mark present.
const highlighted = percent.highlight({ response: 'Strongly agree' });
const cleared = highlighted.highlight(null); // Bar: clear the highlight scope
await view.edit({
requestId: 'highlight-agreement', baseRevision: view.snapshot().revision,
edits: [{ method: 'highlight', args: [{ response: 'Strongly agree' }] }]
});
await view.edit({
requestId: 'clear-highlight', baseRevision: view.snapshot().revision,
edits: [{ method: 'highlight', args: [null] }]
});previewEdit validates these exact operations without changing the accepted state.
Flip retains the highlight and clearing it restores ordinary opacity. Whole-selector
null explicitly clears Bar highlight; {response: null} and {} remain invalid
selectors. Non-null highlight calls retain the existing cumulative selector semantics.
A batch produces one validated destination and one revision. Clearing is not a filter,
an empty selection, or a select-all workaround.
Filtering aggregated counts
where appends a filter at the current pipeline stage. On a compiled breakdown
this is after aggregation; it does not move the predicate to the source rows.
where({question: "Parks"}) retains all response categories of Parks and its
original total. Percentages still use that question's full response total.
Removing a response category fails the complete-category invariant; it never
silently renormalizes the remaining answers. Use highlight for emphasis.
Source-only fields unavailable after aggregation produce MISSING_FIELD; author
pre-aggregate filters in a complete builder state when that is the intended query.
Same-field axis edits retain the existing type and options, including after a
flip: x("count", {label: "Responses"}) changes a horizontal measure label without
turning it into a categorical channel. Field remaps still require a valid final
grain and encoding. An invalid final batch leaves the accepted chart unchanged.