Visualization

Spark Chart

Small graph capable of visualizing data in a simplified form..

Installation

  1. 1

    Install dependencies:

    npm i recharts
  2. 2

    Add component:

    Copy and paste the code into your project’s component directory. Do not forget to update the import paths. If you have not added the required chartUtils.ts, check out the add utilities and helpers section in installation.
    // Tremor Raw Spark Chart [v0.1.1]
    "use client"
    import React from "react"import {  Area,  Bar,  Line,  AreaChart as RechartsAreaChart,  BarChart as RechartsBarChart,  LineChart as RechartsLineChart,  ResponsiveContainer,  XAxis,  YAxis,} from "recharts"import { AxisDomain } from "recharts/types/util/types"
    import {  AvailableChartColors,  AvailableChartColorsKeys,  constructCategoryColors,  getColorClassName,  getYAxisDomain,} from "@/lib/chartUtils"import { cx } from "@/lib/utils"
    //#region SparkAreaChart
    interface SparkAreaChartProps extends React.HTMLAttributes<HTMLDivElement> {  data: Record<string, any>[]  categories: string[]  index: string  colors?: AvailableChartColorsKeys[]  autoMinValue?: boolean  minValue?: number  maxValue?: number  connectNulls?: boolean  type?: "default" | "stacked" | "percent"  fill?: "gradient" | "solid" | "none"}
    const SparkAreaChart = React.forwardRef<HTMLDivElement, SparkAreaChartProps>(  (props, forwardedRef) => {    const {      data = [],      categories = [],      index,      colors = AvailableChartColors,      autoMinValue = false,      minValue,      maxValue,      connectNulls = false,      type = "default",      className,      fill = "gradient",      ...other    } = props
        const categoryColors = constructCategoryColors(categories, colors)    const yAxisDomain = getYAxisDomain(autoMinValue, minValue, maxValue)    const stacked = type === "stacked" || type === "percent"    const areaId = React.useId()
        const getFillContent = (fillType: SparkAreaChartProps["fill"]) => {      switch (fillType) {        case "none":          return <stop stopColor="currentColor" stopOpacity={0} />        case "gradient":          return (            <>              <stop offset="5%" stopColor="currentColor" stopOpacity={0.4} />              <stop offset="95%" stopColor="currentColor" stopOpacity={0} />            </>          )        case "solid":          return <stop stopColor="currentColor" stopOpacity={0.3} />        default:          return <stop stopColor="currentColor" stopOpacity={0.3} />      }    }
        return (      <div ref={forwardedRef} className={cx("h-12 w-28", className)} {...other}>        <ResponsiveContainer>          <RechartsAreaChart            data={data}            margin={{              bottom: 1,              left: 1,              right: 1,              top: 1,            }}            stackOffset={type === "percent" ? "expand" : undefined}          >            <XAxis hide dataKey={index} />            <YAxis hide={true} domain={yAxisDomain as AxisDomain} />
                {categories.map((category) => {              const categoryId = `${areaId}-${category.replace(/[^a-zA-Z0-9]/g, "")}`              return (                <React.Fragment key={category}>                  <defs>                    <linearGradient                      key={category}                      className={cx(                        getColorClassName(                          categoryColors.get(                            category,                          ) as AvailableChartColorsKeys,                          "text",                        ),                      )}                      id={categoryId}                      x1="0"                      y1="0"                      x2="0"                      y2="1"                    >                      {getFillContent(fill)}                    </linearGradient>                  </defs>                  <Area                    className={cx(                      getColorClassName(                        categoryColors.get(                          category,                        ) as AvailableChartColorsKeys,                        "stroke",                      ),                    )}                    dot={false}                    strokeOpacity={1}                    name={category}                    type="linear"                    dataKey={category}                    stroke=""                    strokeWidth={2}                    strokeLinejoin="round"                    strokeLinecap="round"                    isAnimationActive={false}                    connectNulls={connectNulls}                    stackId={stacked ? "stack" : undefined}                    fill={`url(#${categoryId})`}                  />                </React.Fragment>              )            })}          </RechartsAreaChart>        </ResponsiveContainer>      </div>    )  },)
    SparkAreaChart.displayName = "SparkAreaChart"
    //#region SparkLineChart
    interface SparkLineChartProps extends React.HTMLAttributes<HTMLDivElement> {  data: Record<string, any>[]  categories: string[]  index: string  colors?: AvailableChartColorsKeys[]  autoMinValue?: boolean  minValue?: number  maxValue?: number  connectNulls?: boolean}
    const SparkLineChart = React.forwardRef<HTMLDivElement, SparkLineChartProps>(  (props, forwardedRef) => {    const {      data = [],      categories = [],      index,      colors = AvailableChartColors,      autoMinValue = false,      minValue,      maxValue,      connectNulls = false,      className,      ...other    } = props
        const categoryColors = constructCategoryColors(categories, colors)    const yAxisDomain = getYAxisDomain(autoMinValue, minValue, maxValue)
        return (      <div ref={forwardedRef} className={cx("h-12 w-28", className)} {...other}>        <ResponsiveContainer>          <RechartsLineChart            data={data}            margin={{              bottom: 1,              left: 1,              right: 1,              top: 1,            }}          >            <XAxis hide dataKey={index} />            <YAxis hide={true} domain={yAxisDomain as AxisDomain} />            {categories.map((category) => (              <Line                className={cx(                  getColorClassName(                    categoryColors.get(category) as AvailableChartColorsKeys,                    "stroke",                  ),                )}                dot={false}                strokeOpacity={1}                key={category}                name={category}                type="linear"                dataKey={category}                stroke=""                strokeWidth={2}                strokeLinejoin="round"                strokeLinecap="round"                isAnimationActive={false}                connectNulls={connectNulls}              />            ))}          </RechartsLineChart>        </ResponsiveContainer>      </div>    )  },)
    SparkLineChart.displayName = "SparkLineChart"
    //#region SparkBarChart
    interface BarChartProps extends React.HTMLAttributes<HTMLDivElement> {  data: Record<string, any>[]  index: string  categories: string[]  colors?: AvailableChartColorsKeys[]  autoMinValue?: boolean  minValue?: number  maxValue?: number  barCategoryGap?: string | number  type?: "default" | "stacked" | "percent"}
    const SparkBarChart = React.forwardRef<HTMLDivElement, BarChartProps>(  (props, forwardedRef) => {    const {      data = [],      categories = [],      index,      colors = AvailableChartColors,      autoMinValue = false,      minValue,      maxValue,      barCategoryGap,      type = "default",      className,      ...other    } = props
        const categoryColors = constructCategoryColors(categories, colors)
        const yAxisDomain = getYAxisDomain(autoMinValue, minValue, maxValue)    const stacked = type === "stacked" || type === "percent"
        return (      <div ref={forwardedRef} className={cx("h-12 w-28", className)} {...other}>        <ResponsiveContainer>          <RechartsBarChart            data={data}            margin={{              bottom: 1,              left: 1,              right: 1,              top: 1,            }}            stackOffset={type === "percent" ? "expand" : undefined}            barCategoryGap={barCategoryGap}          >            <XAxis hide dataKey={index} />            <YAxis hide={true} domain={yAxisDomain as AxisDomain} />
                {categories.map((category) => (              <Bar                className={cx(                  getColorClassName(                    categoryColors.get(category) as AvailableChartColorsKeys,                    "fill",                  ),                )}                key={category}                name={category}                type="linear"                dataKey={category}                stackId={stacked ? "stack" : undefined}                isAnimationActive={false}                fill=""              />            ))}          </RechartsBarChart>        </ResponsiveContainer>      </div>    )  },)
    SparkBarChart.displayName = "SparkBarChart"
    export { SparkAreaChart, SparkLineChart, SparkBarChart }
    

Example with context

APPL

Apple Inc.
179.26+1.72%

Example of SparkAreaChart with different fill types

gradient (default)

solid

none

API Reference: SparkAreaChart, SparkLineChart, and SparkBarChart

data
Required
Record<string, any>[]
Data used to display the chart.
index
Required
string[]
Key of the data object to map the data to the x axis.

Default: []

categories
Required
string[]
Select the categories from your data. Also used to populate the legend and toolip.

Default: []

colors
AvailableChartColorsKeys[]
Change the colors of the categories. To add, update, or remove the colors, edit the 'chartColors' array in your chartUtils.ts file. The AvailableChartColorsKeys will be automatically updated.

Default: AvailableChartColors, which are by default: 'blue' | 'emerald' | 'violet' | 'amber' | 'gray' | 'cyan' | 'pink'

type
'default' | 'stacked' | 'percent'
(SparkAreaChart Only!) Select how chart areas are positioned relative to each other.

Default: 'default'

fill
'gradient' | 'solid' | 'none'
Select the fill variant of the area.

Default: 'gradient'

autoMinValue
boolean
Adjusts the minimum value in relation to the magnitude of the data.

Default: false

minValue
number
Sets the minimum value of the shown chart data.
maxValue
number
Sets the maximum value of the shown chart data.
connectNulls
boolean
Connects datapoints that have null values between them.

Default: false

barCategoryGap
Percentage | number
(SparkBarChart Only!) The gap between two bar categories, which can be a percent value (string) or a fixed value.

Default: 10%