@data-ui/histogram

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

React + d3 library for creating histograms

原始使用文档
文档目录10 节
  1. Example usage
  2. Components
  3. <Histogram />
  4. <*Series />
  5. <BarSeries />
  6. <DensitySeries />
  7. <XAxis /> and <YAxis />
  8. Tooltips
  9. Theme
  10. Development

@data-ui/histogram

A React + d3 library for creating histograms. Vertical or horizontal, raw data or binned data, numeric or categorical bins, counts or densities, cumulative or not.

npm install --save @data-ui/histogram

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

Example usage

Similar to the @data-ui/xy-chart package, this @data-ui/histogram package exports a parent <Histogram /> container component that renders an svg and coordinates scales across its children. You can pass the parent container optionally-animated <BarSeries /> and/or <DensitySeries /> as well as <XAxis /> and <YAxis />.

import { Histogram, DensitySeries, BarSeries, withParentSize, XAxis, YAxis } from '@data-ui/histogram';

const ResponsiveHistogram = withParentSize(({ parentWidth, parentHeight, ...rest}) => (
  <Histogram
    width={parentWidth}
    height={parentHeight}
    {...rest}
  />
);

const rawData = Array(100).fill().map(Math.random);

...
  render () {
    return (
      <ResponsiveHistogram
        ariaLabel="My histogram of ..."
        orientation="vertical"
        cumulative={false}
        normalized={true}
        binCount={25}
        valueAccessor={datum => datum}
        binType="numeric"
        renderTooltip={({ event, datum, data, color }) => (
          <div>
            <strong style={{ color }}>{datum.bin0} to {datum.bin1}</strong>
            <div><strong>count </strong>{datum.count}</div>
            <div><strong>cumulative </strong>{datum.cumulative}</div>
            <div><strong>density </strong>{datum.density}</div>
          </div>
        )}
      >
        <BarSeries
          animated
          rawData={rawData /* or binnedData={...} */}
        />
        <XAxis />
        <YAxis />
      </ResponsiveHistogram>
    );
  }

Demo with the Histogram playground.

Components

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

<Histogram />

NameTypeDefaultDescription
ariaLabelPropTypes.string.isRequired-Accessibility label
binValuesPropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string]))nullBin thresholds, overrides binCount
binCountPropTypes.number10an approximate number of bins to use (if data is not already binned)
binTypePropTypes.oneOf(['numeric', 'categorical'])'numeric'Specify whether to bins are categorical or numeric
childrenPropTypes.node.isRequired-Child Series, Axis, or other
cumulativePropTypes.boolfalsewhether to show a cumulative histogram
heightPropTypes.number.isRequired-height of the visualization
horizontalPropTypes.boolfalsewhether the histograms is oriented vertically or horizontally
limitsPropTypes.arraynullvalues outside the limits are ignored
marginPropTypes.shape({ top: PropTypes.number, right: PropTypes.number, bottom: PropTypes.number, left: PropTypes.number }){ top: 32, right: 32, bottom: 64, left: 64 }chart margin, leave room for axes and labels!
normalizedPropTypes.boolfalsewhether the value axis is normalized as fraction of total
themePropTypes.object{}chart theme object, see theme below.
widthPropTypes.number.isRequired-width of the svg
valueAccessorPropTypes.funcd => dfor raw data, how to access the bin value

<*Series />

<BarSeries /> and <DensitySeries /> components accept either rawData or binnnedData. Raw data can be in any format as long as the value of each datum can be accessed with the Histogram valueAccessor function. Binned data should have the following shapes:

export const numericBinnedDatumShape = PropTypes.shape({
  id: PropTypes.string.isRequired,
  bin0: PropTypes.number.isRequired,
  bin1: PropTypes.number.isRequired,
  count: PropTypes.number.isRequired,
});

export const categoricalBinnedDatumShape = PropTypes.shape({
  id: PropTypes.string.isRequired,
  bin: PropTypes.string.isRequired,
  count: PropTypes.number.isRequired,
});

If both rawData and binnnedData are provided, rawData is ignored.

<BarSeries />

NameTypeDefaultDescription
animatedPropTypes.booltruewhether to animate updates to the data in the series
rawDataPropTypes.array[]raw datum
binnedDatabinnedDataShape[]binned data
fillPropTypes.oneOfType([PropTypes.func, PropTypes.string])@data-ui/theme.color.defaultdetermines bar fill color
fillOpacityPropTypes.oneOfType([PropTypes.func, PropTypes.number])0.7opacity of bar fill
strokePropTypes.oneOfType([PropTypes.func, PropTypes.string])'white'determines bar stroke color
strokeWidthPropTypes.oneOfType([PropTypes.func, PropTypes.number])1determines width of bar outline
onClickPropTypes.func--Called on bar click with a signature of ({ event, data, datum, color, index })

<DensitySeries />

For raw data that is numeric, the <DensitySeries /> plots an estimates of the probability density function, i.e., a kernel density estimate. If pre-aggregated and/or categorical data is passed to the Series, it plots an Area graph of values based on the data counts.

NameTypeDefaultDescription
animatedPropTypes.booltruewhether to animate updates to the data in the series
rawDataPropTypes.array[]raw datum
binnedDatabinnedDataShape[]binned data
fillPropTypes.oneOfType([PropTypes.func, PropTypes.string])@data-ui/theme.color.defaultdetermines bar fill color
kernelPropTypes.oneOf(['gaussian', 'parabolic'])'gaussian'kernel function type, parabolic = epanechnikov kernel
showAreaPropTypes.booltruewhether to show density area fill
showLinePropTypes.booltruewhether to show density line path
smoothingPropTypes.number1smoothing constant for parabolic / epanechinikov kernel function
fillOpacityPropTypes.oneOfType([PropTypes.func, PropTypes.number])0.7opacity of area fill if shown
strokePropTypes.oneOfType([PropTypes.func, PropTypes.string])'white'determines line color if shown
strokeWidthPropTypes.oneOfType([PropTypes.func, PropTypes.number])2determines width of line path if shown
strokeDasharrayPropTypes.oneOfType([PropTypes.func, PropTypes.string])''determines dash pattern of line if shown
strokeLinecapPropTypes.oneOf(['butt', 'square', 'round', 'inherit'])'round'style of line path stroke
useEntireScalePropTypes.boolfalseif true, density plots will scale to fill the entire y-range of the plot. if false, the maximum value is scaled to the count of the series

<XAxis /> and <YAxis />

NameTypeDefaultDescription
axisStylesaxisStylesShape{}config object for axis and axis label styles, see theme below
labelPropTypes.oneOfType([PropTypes.string, PropTypes.element])<text {...axisStyles.label[orientation]} />string or component for axis labels
numTicksPropTypes.numbernullapproximate number of ticks
orientationXAxis PropTypes.oneOf(['bottom', 'top']) or YAxis PropTypes.oneOf(['left', 'right'])bottom, leftorientation of axis
tickStylestickStylesShape{}config object for styling ticks and tick labels, see theme below
tickLabelComponentPropTypes.element<text {...tickStyles.label[orientation]} />component to use for tick labels
tickFormatPropTypes.funcnull(tick, tickIndex) => formatted tick
tickValuesPropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string]))nullcustom tick values

Tooltips

Tooltips are supported for histogram BarSeries. The easiest way to use tooltips out of the box is by passing a renderTooltip function to <Histogram /> as shown in the above example. This function takes an object with the shape { event, datum, data, color } as input and should return the inner contents of the tooltip (not the tooltip container!) as shown above. datum corresponds to the binned data point, see the above-specified shapes which depend on whether your bins are categorical or numeric. color represents the bar fill. If this function returns a falsy value, a tooltip will not be rendered.

Under the covers this will wrap the <Histogram /> component in the exported <WithTooltip /> HOC, which wraps the svg in a <div /> and handles the positioning and rendering of an HTML-based tooltip with the contents returned by renderTooltip(). This tooltip is aware of the bounds of its container and should position itself "smartly".

If you'd like more customizability over tooltip rendering you can do either of the following:

  1. Roll your own tooltip positioning logic and pass onMouseMove and onMouseLeave functions to Histogram. These functions are passed to the <BarSeries /> children and are called with the signature onMouseMove({ data, datum, event, color }) and onMouseLeave() upon appropriate trigger.

  2. Wrap <Histogram /> in <WithTooltip /> yourself, which accepts props for additional customization:

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, index }) => 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

Theme

A theme object with the following shape can be passed to <Histogram /> to style the chart, axes, and series. Alternatively, keys (eg xAxisStyles) can be passed directly to the axes components.

See @data-ui/theme for an example.

export const themeShape = PropTypes.shape({
  gridStyles: PropTypes.shape({
    stroke: PropTypes.string,
    strokeWidth: PropTypes.number,
  }),
  xAxisStyles: PropTypes.shape({
    stroke: PropTypes.string,
    strokeWidth: PropTypes.number,
    label: PropTypes.shape({
      bottom: PropTypes.object,
      top: PropTypes.object,
    }),
  }),
  yAxisStyles: PropTypes.shape({
    stroke: PropTypes.string,
    strokeWidth: PropTypes.number,
    label: PropTypes.shape({
      left: PropTypes.object,
      right: PropTypes.object,
    }),
  })
  xTickStyles: PropTypes.shape({
    stroke: PropTypes.string,
    tickLength: PropTypes.number,
    label: PropTypes.shape({
      bottom: PropTypes.object,
      top: PropTypes.object,
    }),
  }),
  yTickStyles: PropTypes.shape({
    stroke: PropTypes.string,
    tickLength: PropTypes.number,
    label: PropTypes.shape({
      left: PropTypes.object,
      right: PropTypes.object,
    }),
  }),
});

Development

npm install
yarn run dev # or 'build'

版本与发布记录

@data-ui/histogram 共发布 40 个版本,首次发布于 2017/08/04;过去 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/histogram 的常见问题

@data-ui/histogram 是什么?

React + d3 library for creating histograms

如何安装 @data-ui/histogram?

在项目目录运行 npm install @data-ui/histogram,或使用 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/histogram 支持 TypeScript 吗?

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

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

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

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

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

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

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

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

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