Skip to content

shadcn.io is an independent project built on shadcn/ui

Free

Bar chart

Compare categories side by side, grouped or stacked, vertical or horizontal. Values can sit inside the bars, and the hovered bar dims the rest.

On this page19 sections

Preview

Preview width

Installation

The command adds the example above to components/charts/ and, the first time, the chart kit to components/ui/charts/. Both are source files in your project from then on: read them, change them, delete what you don't use.

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

Usage

Rows hold a category under xDataKey and a number for each series.

import {
  Bar,
  BarChart,
  BarXAxis,
  ChartTooltip,
  Grid,
} from "@/components/ui/charts";

const data = [
  { month: "Jan", revenue: 12000 },
  { month: "Feb", revenue: 15500 },
  { month: "Mar", revenue: 11000 },
  { month: "Apr", revenue: 18500 },
];

export const RevenueChart = () => (
  <BarChart ariaLabel="Monthly revenue" data={data} xDataKey="month">
    <Grid horizontal />
    <Bar dataKey="revenue" label="Revenue" />
    <BarXAxis />
    <ChartTooltip />
  </BarChart>
);

Anatomy

The same building blocks as the line chart, with a category axis instead of a time axis.

<BarChart data={data} xDataKey="month">
  <Grid horizontal />
  <Bar dataKey="desktop" label="Desktop" />
  <Bar dataKey="mobile" fill="var(--chart-2)" label="Mobile" />
  <BarXAxis />
  <BarYAxis />
  <ChartTooltip />
</BarChart>
  • BarChart: Holds the rows and lays out one band per category.
  • Grid: Guide lines behind the bars.
  • Bar: One series. Several are grouped side by side, or stacked with stacked.
  • BarXAxis: Category labels, thinned to fit the width.
  • BarYAxis: Value labels, or the categories on a horizontal chart.
  • ChartTooltip: The hovered category's values and the dots on each bar.

Grouped and stacked

Every <Bar> is a series, and the series sit side by side in each category. groupGap on the first <Bar> sets the space between them (4 px). Add stacked to the chart to stack them instead, and stackGap for a gap between the segments.

Preview width

Horizontal bars

Set orientation="horizontal" and the categories move to the y axis. Use <BarYAxis /> for their labels and widen margin.left to fit long names.

Preview width

Values in the bars

showValue writes each value inside its bar. Labels that don't fit are hidden, and the check runs again on resize, so a narrow chart shows fewer. Format them with valueLabelFormatter and place them with valueLabelPosition.

Preview width

Negative values

Negative values grow down from zero with no extra props. Pass highlightRowValues={[0]} to the <Grid> to draw the baseline heavier than the other rows.

Preview width

Squares

<BarSquares> draws each bar as a column of rounded squares, with an optional gradient across them. <BarColumnTrack /> fills the rest of each column with a faint track.

Preview width

3D bars

Wrap a <Bar> in <BarDepthProvider> with <BarDepthBack> and <BarDepthFront> for a side face, a top face and a glass front. <BarPulse> marks one bar, such as the current month.

Preview width

Linked charts

Bar charts take syncId like line charts. Two charts with the same id highlight the same category together, and activeIndex focuses one from outside.

Preview width

Customization

The kit is in your project, in components/ui/charts/: your framework's components over a shared core/. Change a default there and every chart picks it up.

className goes on the chart's container, so size and spacing are utility classes.

rows on <ChartTooltip> formats each value without rebuilding the panel, as below. On the bars themselves, fadedOpacity sets how far the others dim while one is hovered (0.3), and lineCap rounds or squares their ends.

<ChartTooltip
  rows={(point) => [
    {
      color: "var(--chart-1)",
      label: "Revenue",
      value: `$${Number(point.revenue).toLocaleString()}`,
    },
  ]}
/>

Where a part renders content of its own, you pass it in. In React:

  • ChartTooltip: content={({ point, index }) => …}

Loading state

With status="loading" the bars are replaced by a shimmering skeleton and the pointer is ignored. On "ready" the real bars grow in from it. The skeleton takes the first bar's color unless you set loadingFill.

With no data yet, render <BarChartLoading /> in the chart's place.

Preview width

Animation

Bars grow from the baseline one after another, the stagger spread over 40% of animationDuration (1100 ms). Set staggerDelay on a <Bar> to space them yourself, or animationType="fade" to fade them in at full height.

animate={false} on a <Bar> draws it at its value from the first frame. Reduced motion skips the entrance.

Theming

Every color in the kit is one of your theme's tokens or a mix of them, except --chart-positive, a fixed green. A preset or the .dark class restyles the chart, and overriding a token in your CSS changes it everywhere.

Each <Bar> takes its color as fill, which can also be url(#id) for a gradient or pattern defined inside the chart. A bar with no fill uses --chart-line-primary.

TokenDefaultPaints
--chart-1your theme'sthe first series
--chart-2your theme'sthe second series
--chart-3your theme'sthe third series
--chart-line-primary--chart-1a series with no color of its own
--chart-grid--bordergrid lines
--chart-label--muted-foregroundtick labels
--chart-tooltip-background--popoverthe tooltip panel
--chart-date-pill-background--primarythe date pill on hover
globals.css
:root {
  --chart-line-primary: var(--chart-3);
  --chart-grid: var(--muted);
}

Accessibility

The chart is an image named by ariaLabel ("Bar chart" by default), with ariaDescription for anything the bars alone don't say.

Tab
Moves focus to the chart.
Arrow Right
Moves to the next category. ArrowDown does the same.
Arrow Left
Moves to the previous category. ArrowUp does the same.
Home
Jumps to the first category.
End
Jumps to the last category.

FAQ

When should I use a bar chart instead of a line or pie chart?

Use a bar chart to compare amounts across separate categories, such as months, plans or traffic sources. Every bar starts at zero, so its length is the value and two bars compare at a glance.

Pick a line chart when the x axis is continuous time and the trend matters more than each value, a pie chart for a few parts of one whole, and a histogram to see how a single measure is distributed.

What data does the bar chart need?

An array of rows, one per category. Each row holds the category's label under xDataKey, which is name unless you pass another key, and one number for each series.

A <Bar> reads its series with dataKey. Bars are drawn in row order, so sort the array yourself when the chart should run from the largest value to the smallest.

How do I make a grouped or stacked bar chart?

Add one <Bar> per series. They sit side by side in each category by default, groupGap pixels apart (4), a value read from the first <Bar>.

Set stacked on <BarChart> to pile the series into one bar per category, and stackGap for a gap in pixels between the segments.

barGap sets the space between categories as a fraction of the band (0.2), and barWidth fixes the bars' thickness in pixels.

How do I make a horizontal bar chart?

Set orientation="horizontal" on <BarChart>. The categories move to the y axis and the bars grow to the right.

Use <BarYAxis /> for the category labels and widen the left margin so long names fit, for example margin={{ left: 64 }}. It shows every category by default, which suits a ranking with long labels.

How do I show the value on each bar of a bar chart?

Set showValue on the <Bar> and each value is written inside its bar. A label that doesn't fit is hidden, and the fit is checked again on resize, so a narrow chart shows fewer.

valueLabelFormatter formats the number, valueLabelPosition places it at the "top", "center" or "bottom" of the bar, and valueLabelOrientation forces horizontal or vertical text.

Can a bar chart show negative values?

Yes, with no extra props. The value axis always includes zero, so positive bars grow up from it and negative ones grow down.

To make the baseline stand out, pass highlightRowValues={[0]} to the <Grid>. It draws the zero line as a solid rule, where the other rows are dashed.

Why are some category labels missing on my bar chart's x axis?

<BarXAxis> thins the labels so they don't run into each other. It shows at most maxLabels of them (12), evenly spaced, and fewer when that many would not fit the plot's width.

Raise maxLabels, or give it a count per breakpoint such as { base: 4, md: 12 }. showAllLabels prints every label even where they overlap, and with long names a horizontal chart usually reads better.

Can I add a line or a second y axis to a bar chart?

<BarChart> has a single value scale, and a <Bar> ignores yAxisId. For bars with a line over them, or for series in different units, use the composed chart.

There a <SeriesBar> and a <Line> share one time axis, and any series with its own yAxisId gets its own scale. Its rows hold a Date in place of a category label.

Which frameworks does the bar chart support?

React, Vue, Svelte and Solid. One core on TanStack Charts draws the bar chart in each, so the components and props on this page are the same everywhere, and switching framework at the top of the page changes the preview, the code and the install command.

Only the spelling follows the framework: class for className outside React, scoped slots for render props in Vue and snippets in Svelte.

How do I add the bar chart to my project?

Sign in, then copy the command under Installation: npx shadcn@latest add with the chart's URL. It adds the example at the top of this page as components/charts/chart-bar-default, the chart kit to components/ui/charts the first time you install a chart, and @tanstack/charts.

Both are source files in your project from then on. Swap the sample rows for your own data and change whatever you need.

Is the bar chart free?

Yes. The bar chart and every example of it are free to use in personal and commercial projects. Seeing the code and installing it takes a free account, one tap with Google or GitHub.

The charts are bklit's (bklit-ui, MIT), rebuilt on TanStack Charts and drawn in your shadcn/ui theme's tokens.

API reference

BarChart

PropType
dataRow[]

The rows to plot. Each row holds a category label under xDataKey and one number per series under that series' dataKey.

xDataKey?string

Key of the category label in each row.

Default
"name"
animationDuration?number

Duration of the entrance in milliseconds. Bars are staggered across 40% of this duration.

Default
1100
margin?Partial<ChartMargin>

Space around the plot area in pixels, for axis labels and the tooltip. Missing sides use the default.

Type
Partial<ChartMargin>
Default
{ top: 40, right: 40, bottom: 40, left: 40 }
aspectRatio?string

CSS aspect ratio of the chart, as "width / height".

Default
"2 / 1"
className?string

Extra CSS class name for the chart container.

style?CSSProperties

Inline styles for the chart container. Set aspectRatio: "unset" to let the chart fill the height of its parent.

barGap?number

Gap between bar groups as a fraction of the band width (0 to 1).

Default
0.2
barWidth?number

Fixed bar thickness in px, centred in its slot. When unset, the bars fill their band (barGap sets the gap).

orientation?BarOrientation

Direction the bars grow. "horizontal" puts the categories on the y axis.

Default
"vertical"
stacked?boolean

Stack the series on top of each other instead of grouping them side by side.

Default
false
stackGap?number

Gap between stacked segments in px.

Default
0
squareSnap?{ squareGap: number; groupGap?: number; fit?: boolean }

Snap the tooltip dots of grouped vertical bars onto the centre of the top square of a squareGap column (fit redistributes the gap); groupGap sets the ring dot's slot gap.

Type
{ squareGap: number; groupGap?: number; fit?: boolean }
children?ReactNode

The layers to draw: Bar, BarSquares, Grid, BarXAxis, BarYAxis, ChartTooltip and the other chart children. Optional for a status="loading" skeleton.

ariaLabel?string

Accessible name of the chart.

Default
"Bar chart"
ariaDescription?string

Longer accessible description of the chart, exposed as aria-description.

status?ChartStatus

"loading" replaces the bars with a shimmering skeleton and ignores the pointer; switching to "ready" grows the real bars.

Default
"ready"
loadingFill?string

Fill color of the loading skeleton's bars. Defaults to the first Bar's stroke, else its fill.

syncId?string

Charts with the same syncId move together: hovering or keyboard-focusing one shows the crosshair, dots and date pill at the same date on the others (the same category, for bar charts), and a ChartBrush or ChartZoom in a time chart zooms the time charts of the group to its window.

syncY?boolean

With syncId: every chart of the group draws on one y scale (the union of their data), so small multiples compare at a glance. Read by LineChart and AreaChart.

Default
false
activeIndex?number | null

Index into data of the row to focus (crosshair, dots and tooltip), for example the row a table has under the pointer. null clears it.

Type
number | null
onActiveIndexChange?(index: number | null) => void

Called with the index into data of the row the pointer or keyboard focuses, and with null when the focus leaves.

Type
(index: number | null) => void

Bar

PropType
dataKeystring

Key of the data field that holds this series' values.

label?string

Name of the series in the default tooltip row. Defaults to dataKey.

fill?string

Fill color of the bars. Can be a color or a url(#id) reference to a gradient or pattern child.

Default
"var(--chart-line-primary)"
lineCap?BarLineCap

Bar end style: "round" rounds the outer corners, "butt" leaves them square. A number is treated like "round".

Default
"round"
animate?boolean

Grow this series' bars in on entrance. false draws them at their value from the first frame.

Default
true
animationType?BarAnimationType

Entrance of this series' bars: "grow" from the baseline, or "fade" in from a soft blur at their full height, staggered the same way.

Default
"grow"
fadedOpacity?number

Opacity of the bars that are not hovered while another bar is hovered. Read from the first Bar.

Default
0.3
staggerDelay?number

Delay in seconds between the entrances of consecutive bars of this series. Defaults to 40% of animationDuration spread across the categories.

groupGap?number

Gap in px between the bars of a group. Read from the first Bar.

Default
4
showValue?boolean

Show each bar's formatted value inside the bar, where it fits. The fit is checked again on every resize, so narrow charts show fewer labels.

Default
false
valueLabelFormatter?(value: number) => string

Formats a value shown inside a bar. Defaults to English integers, for example 12,000.

Type
(value: number) => string
valueLabelColor?string

Text color of the values shown inside the bars.

Default
"white"
valueLabelOrientation?BarValueLabelOrientation

Direction of the value text: "auto" uses horizontal text, rotated when only vertical text fits; "horizontal" or "vertical" require that direction and hide labels that do not fit it.

Default
"auto"
valueLabelPosition?BarValueLabelPosition

Where the value sits inside the bar. On horizontal bars "top" is the value end (right) and "bottom" the base (left).

Default
"center"
valueLabelClassName?string

Extra CSS class name for the value labels.

Grid

PropType
horizontal?boolean

Show horizontal grid lines.

Default
true
vertical?boolean

Show vertical grid lines.

Default
false
numTicksRows?number

Number of horizontal grid lines. Ignored when rowTickValues is set.

Default
5
numTicksColumns?number

Number of vertical grid lines.

Default
10
rowTickValues?number[]

Explicit y values for the horizontal grid lines. Overrides numTicksRows.

stroke?string

Color of the grid lines.

Default
"var(--chart-grid)"
loadingStroke?string

Grid color while the chart is loading. Falls back to stroke.

strokeOpacity?number

Opacity of the grid lines.

Default
1
strokeWidth?number

Width of the grid lines in px.

Default
1
strokeDasharray?string

Dash pattern of the grid lines.

Default
"4,4"
highlightRowValues?number[]

Y values of horizontal lines drawn with the highlight styling, for example a zero baseline.

highlightRowStroke?string

Color of the highlighted rows.

Default
"var(--chart-foreground-muted)"
highlightRowStrokeOpacity?number

Opacity of the highlighted rows.

Default
1
highlightRowStrokeWidth?number

Width of the highlighted rows in px.

Default
1
highlightRowStrokeDasharray?string

Dash pattern of the highlighted rows.

Default
"0"
fadeHorizontal?boolean

Fade the horizontal lines toward transparent at the left and right edges.

Default
true
fadeVertical?boolean

Fade the vertical lines toward transparent at the top and bottom edges.

Default
false
hideHorizontalEdgeLines?boolean

Drop the first and last horizontal line (kept when two or fewer remain).

Default
false
hideVerticalEdgeLines?boolean

Drop the first and last vertical line (kept when two or fewer remain).

Default
false
shimmer?boolean

While the chart is loading, sweep a bright band across the grid.

Default
false
shimmerStroke?string

Color of the shimmer band.

Default
"color-mix(in oklch, var(--bkm-foreground) 68%, transparent)"
shimmerSpeed?number

Speed multiplier of the shimmer sweep. 2 is twice as fast.

Default
1

BarXAxis

PropType
tickerHalfWidth?number

Half-width in px of the zone around the date pill inside which tick labels are hidden.

Default
50
showAllLabels?boolean

Show every category label, even where they overlap, instead of thinning them to maxLabels and to the plot width.

Default
false
maxLabels?BarLabelCount

Maximum number of category labels when showAllLabels is off. Fewer are shown, evenly spaced, when that many would not fit the plot width. Pass { base, sm, md, lg, xl } to vary it with the chart's width (640, 768, 1024 and 1280 px and up).

Default
12

BarYAxis

PropType
showAllLabels?boolean

Horizontal charts: show every category label instead of thinning to maxLabels.

Default
true
maxLabels?number

Horizontal charts: maximum number of category labels when showAllLabels is off.

Default
20
numTicks?number

Vertical charts: target number of value ticks. Grid settings take precedence.

Default
5
formatLargeNumbers?boolean

Vertical charts: abbreviate values of 1000 and above as thousands, for example 2k.

Default
true
formatValue?(value: number) => string

Vertical charts: formats a value tick into its label. Overrides formatLargeNumbers.

Type
(value: number) => string

ChartTooltip

PropType
showDatePill?boolean

Show the date pill that rides along the bottom of the plot.

Default
true
showCrosshair?boolean

Show the vertical crosshair line. Bar charts leave it off unless this is true (the dots and the category pill mark the bar).

Default
true
showDots?boolean

Show a dot on every series at the hovered position.

Default
true
dotVariant?"dot" | "ring"

Dot style: a filled "dot" or a transparent "ring" square. Read by BarChart only.

Type
"dot" | "ring"
Default
"dot"
dotSize?number

Dot radius in px.

Default
5
dotRadiusFraction?number

Corner radius of the "ring" variant as a fraction of its side (0 is square, 0.5 is a circle). Read by BarChart only.

Default
0.25
dotScale?number

Multiplier applied to the dot or ring size. Read by BarChart and LiveLineChart.

Default
1
dotStrokeWidth?number

Stroke width of the dots in px.

Default
2
indicatorColor?string | ((point: Record<string, unknown>) => string)

Color of the crosshair. Only a string is applied; the function form that bklit-ui accepts is ignored and the default is used.

Type
string | ((point: Record<string, unknown>) => string)
Default
"var(--chart-crosshair)"
content?(props: { point: Record<string, unknown>; index: number; pinned?: boolean; dismiss?: () => void }) => ReactNode

Replaces the default tooltip panel body. Receives the hovered data row and its index; with pinnable, also whether the panel is pinned and a dismiss that unpins it (for a close button in a pinned panel's detail).

Type
(props: { point: Record<string, unknown>; index: number; pinned?: boolean; dismiss?: () => void }) => ReactNode
pinnable?boolean

A click (or Enter, or Space) on the chart pins the tooltip where it is: the panel takes the pointer, so its content can grow into detail and hold controls, until another click, Escape or dismiss lets it go.

Default
false
rows?(point: Record<string, unknown>) => { readonly color: string; readonly label: string; readonly value: string | number }[]

Replaces the default rows (one per series) with your own list of { color, label, value }.

Type
(point: Record<string, unknown>) => { readonly color: string; readonly label: string; readonly value: string | number }[]
dotColor?string | ((point: Record<string, unknown>, line: ChartLineConfig) => string)

Fill of the tooltip dots. A function receives the hovered row and the series config, and is called again each time the hovered row changes. Defaults to each series' color; a ProfitLossLine's dot takes the color of the hovered value's sign.

Type
string | ((point: Record<string, unknown>, line: ChartLineConfig) => string)
children?ReactNode

Extra content rendered below the rows in the default panel, for example marker details. Without it, a chart with ChartMarkers lists the markers on the hovered date there.

className?string

Extra class name for the tooltip panel.

springConfig?SpringConfig

Spring for the floating panel when matchCrosshair is on. Defaults to the chart's tooltip spring.

matchCrosshair?boolean

Make the floating panel follow the pointer with the same spring as the crosshair instead of damping.

Default
false
damping?number

Spring damping for the floating panel when matchCrosshair is off, on bklit's 0 to 100 scale: lower is bouncier, higher slower, 0 moves the panel instantly. The default, 20, is the snappy hover spring (stiffness 3600, damping 120); every other value is bklit's spring for it played six times faster.

Default
20
indicatorDasharray?string

Dash pattern of the crosshair. Omit for a solid line.

indicatorFadeEdges?IndicatorFadeEdges

Vertical fade of the crosshair: both ends, the top, the bottom, or none (solid).

Default
"both"
indicatorFadeLength?number

Size of the crosshair's fade, as a percentage of its height (2 to 40).

Default
10
indicatorEndColor?string

Bottom colour of the crosshair: it ramps from indicatorColor at the top to this at the bottom (composes with the fade).

indicatorEnd?"plot" | "point"

How far down the crosshair reaches: the whole plot, or down to the hovered point of the first series.

Type
"plot" | "point"
Default
"plot"
dotHaloBlur?number

Blur in px on the dots' halo, for a soft glow.

Default
0
topOffset?number

Extra gap in px between the top of the plot and the tooltip panel.

Default
0
dateLabels?readonly string[]

The date pill's text for each data row, in row order (pair it with XAxis labels).

boxSpringConfig?SpringConfig

Spring for the floating panel. Takes priority over matchCrosshair and damping.

indicatorWidth?IndicatorWidth

Thickness of the crosshair: a width in px, or "line" (1px), "thin" (2px), "medium" (4px) or "thick" (8px).

Default
"line"

BarChartLoading

PropType
margin?Partial<Readonly<ChartMargin>>

Space around the plot area in pixels. Missing sides use the default.

Type
Partial<Readonly<ChartMargin>>
Default
{ top: 40, right: 40, bottom: 40, left: 40 }
aspectRatio?string

CSS aspect ratio of the placeholder, as "width / height".

Default
"2 / 1"
className?string

Extra CSS class name for the placeholder container.

Default
""
loadingFill?string

Fill color of the skeleton's bars. Defaults to the chart's foreground.