BarGroupChart

This example demonstrates how to create grouped bars in a BarChart by using the positionBy property to segment bars by a secondary dimension (e.g., "color") and foregroundStyleBy to apply distinct colors to each group. This pattern is useful when comparing subcategories within a larger category.

Example Scenario

The dataset includes different object types (Cube, Sphere, Pyramid) grouped by color (Green, Purple, Pink, Yellow). The chart displays the count of each shape per color, with grouped and color-coded bars.

Key Concepts

positionBy

1positionBy: {
2  value: item.color,
3  axis: 'horizontal',
4}
  • Groups bars by the specified value (e.g., color).

  • The axis indicates how the bars are positioned:

    • 'horizontal': groups by Y-axis (stacked vertically within each color group).
    • 'vertical': groups by X-axis (used for transposed layouts).

foregroundStyleBy

1foregroundStyleBy: item.color
  • Applies a unique foreground color to each bar based on the color group.
  • This helps visually distinguish between grouped items.

Code Summary

1const data = [
2  { color: "Green", type: "Cube", count: 2 },
3  { color: "Purple", type: "Sphere", count: 1 },
4  ...
5]
6
7const list = data.map(item => ({
8  label: item.type,              // Primary label (e.g., Cube, Sphere)
9  value: item.count,             // Numeric value
10  positionBy: {
11    value: item.color,           // Grouping key
12    axis: 'horizontal',
13  },
14  foregroundStyleBy: item.color, // Color grouping
15  cornerRadius: 8,
16}))

Full Example

1<Chart frame={{ height: 400 }}>
2  <BarChart marks={list} />
3</Chart>

This chart will render vertical groups of bars by color (e.g., Green, Purple...), and each group will contain the respective shapes (Cube, Sphere, Pyramid) with the appropriate height and color.

Use Cases

This grouped bar layout is ideal for:

  • Comparing subcategories within grouped categories (e.g., survey responses by demographic).
  • Visualizing segmented data distributions.
  • Highlighting clusters of related values in a compact chart.