@data-ui/sparkline

中文文档
0.0.84发布于 2019/11/20MITESM + CJS近 30 天下载 1.3万

React + d3 library for creating sparklines

原始使用文档
文档目录5 节
  1. Example usage
  2. Components
  3. Series
  4. Tooltips
  5. Reference lines and bands

@data-ui/sparkline

A React + d3 library for creating sparklines 📈 implemented with vx.

npm install --save @data-ui/sparkline

Demo it live at williaster.github.io/data-ui.

Example usage

Sparklines are composable using the container <Sparkline /> component and different types of children including one or more <*Series /> components and reference lines or bands. Additionally, you can customize aesthetics using the exported <PatternLines /> and <LinearGradient/> components.

Note that the order of children passed to <Sparkline /> determines their rendering order, for example a <HorizontalReferenceLine /> passed after a <BarSeries /> will overlay the line on the bars.

import {
  Sparkline,
  LineSeries,
  HorizontalReferenceLine,
  BandLine,
  PatternLines,
  PointSeries } from '@data-ui/sparkline';
import { allColors } from '@data-ui/theme'; // open-color colors

const data = Array(25).fill().map(Math.random);

<Sparkline
      ariaLabel="A line graph of randomly-generated data"
      margin={{ top: 24, right: 64, bottom: 24, left: 64,}}
      width={500}
      height={100}
      data={data}
      valueAccessor={datum => datum}
    >
      {/* this creates a <defs> referenced for fill */}
      <PatternLines
        id="unique_pattern_id"
        height={6}
        width={6}
        stroke={allColors.grape[6]}
        strokeWidth={1}
        orientation={['diagonal']}
      />
      {/* display innerquartiles of the data */}
      <BandLine
        band="innerquartiles"
        fill="url(#unique_pattern_id)"
      />
      {/* display the median */}
      <HorizontalReferenceLine
        stroke={allColors.grape[8]}
        strokeWidth={1}
        strokeDasharray="4 4"
        reference="median"
      />
      {/* Series children are passed the data from the parent Sparkline */}
      <LineSeries
        showArea={false}
        stroke={allColors.grape[7]}
      />
      <PointSeries
        points={['min', 'max']}
        fill={allColors.grape[3]}
        size={5}
        stroke="#fff"
        renderLabel={val => val.toFixed(2)}
      />
    </Sparkline>

Components

Check out the example source code and PropTable tabs in the Storybook williaster.github.io/data-ui for more!

<Sparkline />

The Sparkline component renders an <svg /> and coordinates scales across all of it's child series and reference lines. It takes the following props:

NameTypeDefaultDescription
ariaLabelPropTypes.string.isRequired-Accessibility label for the svg
childrenPropTypes.node.isRequired-Child series, reference lines, defs, or other valid svg children
classNamePropTypes.string-Optional className to add to the svg
dataPropTypes.array[]an array of data that is shared across, items can be any shape or number
heightPropTypes.number.isRequired-Height of the svg including top/bottom margin
marginPropTypes.shape({ top: PropTypes.number, right: PropTypes.number, bottom: PropTypes.number, left: PropTypes.number }){ top: 16, right: 16, bottom: 16, left: 16 }chart margin, leave room for labels! note 0 may clip LineSeries and PointSeries. a partial { top/right/bottom/ left } object is filled with the other default values
maxPropTypes.number-Optionally set the maximum y-value of the chart (e.g., to coordinate axes across multiple Sparklines)
minPropTypes.number-Optionally set the minimum y-value of the chart (e.g., to coordinate axes across multiple Sparklines)
onMouseMovePropTypes.func-func({ data, datum, event, index, color }), passed to an invisible BarSeries that intercepts all mouse events (can pass to individual series for more control)
onMouseLeavePropTypes.func-func(), passed to an invisible BarSeries that intercepts all mouse events
stylesPropTypes.object-Optional styles to apply to the svg
widthPropTypes.number.isRequired-Width of the svg including left/right margin
valueAccessorPropTypes.funcd => dOptional accessor function that takes an item from the data array as input and returns the y value of the datum. This value is passed back in e.g., renderLabel functions.

Series

The following series components are available, they are passed the data and scales from the parent Sparkline component, and you may compose multiple to create the sparkline you want 😍:

  • <LineSeries />
  • <PointSeries />
  • <BarSeries />

<PointSeries /> and <BarSeries /> support labeling of specific data points.

<LineSeries />

This component can be used to create lines and or area sparklines with various curve types, and takes the following props:

NameTypeDefaultDescription
fillPropTypes.string@data-ui/themes color.defaultIf showArea=true, this sets the fill of the area path.
fillOpacityPropTypes.number0.3If showArea=true, this sets the fillOpacity of the area shape.
curvePropTypes.oneOf(['linear', 'cardinal', 'basis', 'monotoneX'])'cardinal'The type of curve interpolator to use.
onMouseMovePropTypes.func-func({ data, datum, event, index, color }) called on line mouse move for the closest datum
onMouseLeavePropTypes.func-func() called on line mouse leave
showAreaPropTypes.boolfalseBoolean indicating whether to render an Area path.
showLinePropTypes.booltrueBoolean indicating whether to render a Line path.
strokePropTypes.string@data-ui/themes color.defaultIf showLine=true, this sets the stroke of the line path.
strokeDasharrayPropTypes.string-If showLine=true, this sets the strokeDasharray attribute of the line path.
strokeLinecapPropTypes.oneOf(['butt', 'square', 'round', 'inherit'])'round'If showLine=true, this sets the strokeLinecap attribute of the line path.
strokeWidthPropTypes.number2If showLine=true, this sets the strokeWidth attribute of the line path.

<BarSeries />

This component can be used to bar-graph sparklines and takes the following props:

NameTypeDefaultDescription
fillPropTypes.oneOfType([PropTypes.func, PropTypes.string])@data-ui/themes color.defaultA single fill to use for all Bars or a function with the following signature (yVal, i) => fill called for each data point. If data objects have a fill property, it overrides this value.
fillOpacityPropTypes.oneOfType([PropTypes.func, PropTypes.number])0.7A single fillOpacity value (0 - 1) to use for all Bars or a function with the following signature (yVal, i) => opacity called for each data point. If data objects have a fillOpacity property, it overrides this value.
LabelComponentPropTypes.element@data-ui/sparkline's <Label /> componentComponent to use for labels, if relevant. This component is cloned with appropriate x, y, dx, and dy values for positioning.
labelOffsetPropTypes.number8(Absolute) pixel offset to use for positioning a label relative to a Bar. labelPosition is used to determine direction.
labelPositionPropTypes.oneOfType([PropTypes.func, PropTypes.oneOf(['top', 'right', 'bottom', 'left']), ])'top'A single string indicating how to position a label relative to the top point of a bar, or a function with the following signature (yVal, i) => position called for each data point. If the return value is not one of top, right, bottom, left, it is spread on the LabelComponent directly (e.g., { dx: -100, dy: 100 })
onMouseMovePropTypes.func-func({ data, datum, event, index, color }) called on bar mouse move
onMouseLeavePropTypes.func-func() called on bar mouse leave
renderLabelPropTypes.func-Optional function called for each datum, with the following signature (yVal, i) => node. If this is passed to the Series and returns a value, a label will be rendered for the passed point. This is used as the child of LabelComponent so any valid child of svg <text> elements can be returned.
strokePropTypes.oneOfType([PropTypes.func, PropTypes.string])whiteA single stroke to use for all Bars or a function with the following signature (yVal, i) => stroke. If data objects have a stroke property, it overrides this value.
strokeWidthPropTypes.oneOfType([PropTypes.func, PropTypes.number])1A single strokeWidth to use for all Bars or a function with the following signature (yVal, i) => stroke. If data objects have a strokeWidth property, it overrides this value.

<PointSeries />

This component can be used to render all or a subset of points for a sparkline and takes the following props:

NameTypeDefaultDescription
fillPropTypes.oneOfType([PropTypes.func, PropTypes.string])@data-ui/themes color.defaultA single fill to use for all Points or a function with the following signature (yVal, i) => fill called for each data point. If data objects have a fill property, it overrides this value.
fillOpacityPropTypes.oneOfType([PropTypes.func, PropTypes.number])1A single fillOpacity value (0 - 1) to use for all Points or a function with the following signature (yVal, i) => opacity called for each data point. If data objects have a fillOpacity property, it overrides this value.
LabelComponentPropTypes.element@data-ui/sparkline's <Label /> componentComponent to use for labels, if relevant. This component is cloned with appropriate x, y, dx, and dy values for positioning.
labelOffsetPropTypes.number12(Absolute) pixel offset to use for positioning a label relative to a Point. labelPosition is used to determine direction.
labelPositionPropTypes.oneOfType([PropTypes.func, PropTypes.oneOf(['auto', 'top', 'right', 'bottom', 'left']), ])'auto'A single string indicating how to position a label relative to the center of a point, or a function with the following signature (yVal, i) => position called for each data point. 'auto' attempts to position the label on top or bottom of a point depending on the surrounding data points. If the return value is not one of auto, top, right, bottom, left, it is spread on the LabelComponent directly (e.g., { dx: -100, dy: 100 })
onMouseMovePropTypes.func-func({ data, datum, event, index, color }) called on point mouse move
onMouseLeavePropTypes.func-func() called on point mouse leave
pointsPropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['all', 'min', 'max', 'first', 'last']), ]))['min', 'max']String(s) or index(s) indicating which point(s) to render. e.g., If all, all points are rendered, if ['min', 'max'], only the minimum and maximum points are rendered.
sizePropTypes.oneOfType([PropTypes.func, PropTypes.number])3A single size to use as the radius of all Pointss or a function with the following signature (yVal, i) => size called for each data point. If data objects have a size property, it overrides this value.
renderLabelPropTypes.func-Optional function called for each datum, with the following signature (yVal, i) => node. If this is passed to the Series and returns a value, a label will be rendered for the passed point. This is used as the child of LabelComponent so any valid child of svg <text> elements can be returned.
strokePropTypes.oneOfType([PropTypes.func, PropTypes.string])whiteA single stroke to use for all Points or a function with the following signature (yVal, i) => stroke. If data objects have a stroke property, it overrides this value.
strokeWidthPropTypes.oneOfType([PropTypes.func, PropTypes.number])1A single strokeWidth to use for all Points or a function with the following signature (yVal, i) => stroke. If data objects have a strokeWidth property, it overrides this value.

Tooltips

You can add tooltips to <Sparkline /> components by wrapping them with the higher-order <WithTooltip /> component. This component accepts a renderTooltip function whose output is rendered into a boundary-aware (html-based) tooltip. <WithTooltip /> handles tooltip visibility state and passes onMouseMove onMouseLeave and tooltipData props to its child. If these are passed to <Sparkline />, it will render a series of invisible Bars to intercept mouse events. If they are passed to individual series, mouse events will be handled on the series level.

See the storybook for example usage!

NameTypeDefaultDescription
childrenPropTypes.func or PropTypes.object-Child function (to call) or element (to clone) with onMouseMove, onMouseLeave, and tooltipData props/keys
classNamePropTypes.string-Class name to add to the <div> container wrapper
renderTooltipPropTypes.func.isRequired-Renders the contents of the tooltip, signature of ({ event, data, datum, color }) => node. If this function returns a falsy value, a tooltip will not be rendered.
stylesPropTypes.object{}Styles to add to the <div> container wrapper
TooltipComponentPropTypes.func or PropTypes.object@vx's TooltipWithBoundsComponent (not instance) to use as the tooltip container component. It is passed top and left numbers for positioning
tooltipPropsPropTypes.object-Props that are passed to TooltipComponent
tooltipTimeoutPropTypes.number200Timeout in ms for the tooltip to hide upon calling onMouseLeave

Reference lines and bands

The following reference line components are exported to support different types of annotations you may want:

  • <HorizontalReferenceLine />
  • <VerticalReferenceLine />
  • <BandLine />.

<HorizontalReferenceLine />

This component can be used to render a single horizontal reference line to call out a point of interest. It takes the following props:

NameTypeDefaultDescription
referencePropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['mean', 'median', 'min', 'max'] ]))meanWhat reference to create a line for. This may be a raw number to call out, or one of 'mean', 'median', 'min', 'max' which will compute the relevant y value.
LabelComponentPropTypes.element@data-ui/sparkline's <Label /> componentComponent to use for labels, if relevant. This component is cloned with appropriate x, y, dx, and dy values for positioning.
labelOffsetPropTypes.number8(Absolute) pixel offset to use for positioning a label relative to a Point. labelPosition is used to determine direction.
labelPositionPropTypes.oneOf(['top', 'right', 'bottom', 'left'])'right'A single string indicating how to position a label relative to the end of a reference line
renderLabelPropTypes.func-Optional function called for each datum, with the following signature (yVal) => node. If this is passed and returns a value, a label will be rendered. This is used as the child of LabelComponent so any valid child of svg <text> elements can be returned.
strokePropTypes.string@data-ui/themes color.defaultSets the stroke of the line path.
strokeDasharrayPropTypes.string-Sets the strokeDasharray attribute of the line path.
strokeLinecapPropTypes.oneOf(['butt', 'square', 'round', 'inherit'])'round'Sets the strokeLinecap attribute of the line path.
strokeWidthPropTypes.number2Sets the strokeWidth attribute of the line path.

<VerticalReferenceLine />

@TODO picture

This component can be used to render a single vertical reference line to call out a point of interest. It takes the following props:

NameTypeDefaultDescription
referencePropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['first', 'last', 'min', 'max'] ]))lastWhat reference to create a line for. This may be a raw number (x index) to call out, or one of 'first', 'last', 'min', 'max' which will compute the relevant x index value.
LabelComponentPropTypes.element@data-ui/sparkline's <Label /> componentComponent to use for labels, if relevant. This component is cloned with appropriate x, y, dx, and dy values for positioning.
labelOffsetPropTypes.number10(Absolute) pixel offset to use for positioning a label relative to a Point. labelPosition is used to determine direction.
labelPositionPropTypes.oneOf(['top', 'right', 'bottom', 'left'])'top'A single string indicating how to position a label relative to the top of a reference line
renderLabelPropTypes.func-Optional function called for each datum, with the following signature (xVal) => node. If this is passed and returns a value, a label will be rendered. This is used as the child of LabelComponent so any valid child of svg <text> elements can be returned.
strokePropTypes.string@data-ui/themes color.defaultSets the stroke of the line path.
strokeDasharrayPropTypes.string-Sets the strokeDasharray attribute of the line path.
strokeLinecapPropTypes.oneOf(['butt', 'square', 'round', 'inherit'])'round'Sets the strokeLinecap attribute of the line path.
strokeWidthPropTypes.number2Sets the strokeWidth attribute of the line path.

<BandLine />

This component can be used to render ranges of interest as opposed to single values. It may be used to create vertical or horizontal bands and takes the following props:

NameTypeDefaultDescription
bandPropTypes.oneOfType([PropTypes.oneOf([ 'innerQuartiles' ]), PropTypes.shape({ from: PropTypes.shape({ x: PropTypes.number, y: PropTypes.number }).isRequired, to: PropTypes.shape({ x: PropTypes.number, y: PropTypes.number }) ]).isRequired })'innerQuartiles'Specifies the band to render. May be innerQuartiles which computes the midspread of the data values, or an object with the keys { from: coords, to: coords } specifying a custom band. If an x or y value is missing in either the from or to key, the bounds (min, max) of the chart are used.
fillPropTypes.string@data-ui/themes color.lightGraySets the fill of the bar shape.
fillOpacityPropTypes.number0.5Sets the fillOpacity of the bar shape.
strokePropTypes.stringtransparentSets the stroke of the bar shape.
strokeWidthPropTypes.number0Sets the strokeWidth of the bar shape.

<PatternLines /> and <LinearGradient/>s

These components are exported for convenience from @vx to support customization of the aesthetics of your sparklines. They create <defs/> elements with the specified id, which are then referenced for fills or strokes in other components via url(#my_id). See example usage above and the Storybook for examples!

They take the following props:

<PatternLines />

NameTypeDefaultDescription
idPropTypes.string.isRequired-id for the <defs> that is created. When used as a fill in another component it can be referenced via url(#my_id).
widthPropTypes.number.isRequired-Width of the pattern (which is then repeated).
heightPropTypes.number.isRequired-Height of the pattern (which is then repeated).
strokePropTypes.string-Sets the stroke attribute of the pattern line.
strokeWidthPropTypes.number-Sets the strokeWidth attribute of the pattern line.
strokeDasharrayPropTypes.string-Sets the strokeDasharray attribute of the pattern line.
strokeLinecapPropTypes.string'square'Sets the strokeLinecap attribute of the pattern line.
shapeRenderingPropTypes.string'auto'Sets the shapeRendering attribute of the pattern line.
orientationPropTypes.arrayOf(PropTypes.oneOf(['vertical', 'horizontal', 'diagonal']))['vertical']Array of orientations for lines. If multiple are passed, one path is rendered for each.
backgroundPropTypes.string-Optional background fill for the pattern.
classNamePropTypes.string-Optional className added to the pattern path's.

<LinearGradient />

NameTypeDefaultDescription
idPropTypes.string.isRequired-id for the <defs> that is created. When used as a fill in another component it can be referenced via url(#my_id).
fromPropTypes.string-String used for the start color in the gradient.
toPropTypes.string-String used for the end color in the gradient.
fromOffsetPropTypes.string0%Sets the offset (as a %) of the from color.
fromOpacityPropTypes.number1Sets the opacity of the from color.
toOffsetPropTypes.string100%Sets the offset (as a %) of the to color
toOpacityPropTypes.number1Sets the opacity of the to color.
rotatePropTypes.oneOfType([PropTypes.string, PropTypes.number])-Sets the transform attribute of the gradient to rotate(<rotate>)
transformPropTypes.string-Sets the gradientTransform of the linearGradient element, overridden by rotate

版本与发布记录

@data-ui/sparkline 共发布 35 个版本,首次发布于 2017/08/21;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.0.84latest2019/11/206 年前
0.0.832019/11/206 年前
0.0.822019/11/057 年前
0.0.812019/09/247 年前
0.0.802019/07/257 年前
0.0.792019/06/157 年前

关于 @data-ui/sparkline 的常见问题

@data-ui/sparkline 是什么?

React + d3 library for creating sparklines

如何安装 @data-ui/sparkline?

在项目目录运行 npm install @data-ui/sparkline,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^15.0.0-0 || ^16.0.0-0)、react-dom(^15.0.0-0 || ^16.0.0-0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@data-ui/sparkline 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/data-ui__sparkline 是否存在。

@data-ui/sparkline 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@data-ui/sparkline 可以商用吗?

@data-ui/sparkline 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@data-ui/sparkline 的下载量有多少?

根据 npm 官方下载统计,@data-ui/sparkline 在 2026/10/12 – 2026/11/10 这 30 天内被下载 13,062 次,日均约 435 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@data-ui/sparkline 还在维护吗?

最新版本 0.0.84 发布于 2019/11/20(6 年前);至今共发布 35 个版本,其中过去 12 个月发布了 0 个;首次发布于 2017/08/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。