Diverging Bar Chart
Positive and negative bar chart card for weekly change: a diverging column chart of week-on-week variance by day, bars rising and falling from a zero line with signed percentage labels.
"use client"
import {
Bar,
BarChart,
CartesianGrid,
LabelList,
ReferenceLine,
XAxis,
} from "recharts"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
type ChartConfig,
} from "@/components/ui/chart"
// The copy: change text here, not in the markup.
const COPY = {
title: "Listening time",
description: "Change on last week, by day",
} as const
const CHANGE = [
{ day: "Monday", change: 12 },
{ day: "Tuesday", change: -8 },
{ day: "Wednesday", change: 5 },
{ day: "Thursday", change: -14 },
{ day: "Friday", change: 9 },
{ day: "Saturday", change: 18 },
{ day: "Sunday", change: -3 },
]
const CHART_CONFIG = {
change: { label: "Change", color: "var(--chart-3)" },
} satisfies ChartConfig
const formatChange = (value: unknown) => {
const change = Number(value)
return `${change > 0 ? "+" : ""}${change}%`
}
export default function SignedColumnChart() {
return (
<Card className="mx-auto w-full max-w-md">
<CardHeader>
<CardTitle>
<h2>{COPY.title}</h2>
</CardTitle>
<CardDescription>{COPY.description}</CardDescription>
</CardHeader>
<CardContent>
<ChartContainer config={CHART_CONFIG}>
<BarChart
accessibilityLayer
data={CHANGE}
margin={{ top: 24, bottom: 8 }}
>
<CartesianGrid vertical={false} />
{/* Stock ChartContainer's label color misses recharts 3's label layer. */}
<XAxis
tick={{ fill: "var(--muted-foreground)" }}
dataKey="day"
tickLine={false}
axisLine={false}
tickMargin={10}
tickFormatter={(value: string) => value.slice(0, 3)}
/>
<ReferenceLine y={0} stroke="var(--border)" />
<ChartTooltip
cursor={false}
content={
<ChartTooltipContent
hideLabel
formatter={(value) => formatChange(value)}
/>
}
/>
{/* Rise and fall read by direction and the printed value. */}
<Bar
dataKey="change"
fill="var(--color-change)"
radius={2}
maxBarSize={16}
>
<LabelList
dataKey="change"
position="top"
offset={8}
className="fill-foreground"
fontSize={12}
formatter={formatChange}
/>
</Bar>
</BarChart>
</ChartContainer>
</CardContent>
</Card>
)
}
Installation
npx shadcn@latest add @01orbital/signed-column-chartMake it yours
- Its words are in
COPYat the top ofcomponents/blocks/charts/signed-column-chart/index.tsx: change them there, not in the markup. CHANGEandCHART_CONFIG, also at the top of the file, hold its lists and settings.
Built from
npm: recharts@3.8.0. The CLI installs it for you.
Built from these parts. The CLI adds each one that is missing and won't replace a file you already have unless you choose to:
The shadcn parts here are their Base UI versions, and this piece uses Base UI's API. A Radix version you already have won't work with it.
Last updated on