Skip to content

Commit

Permalink
feat(scales): add option to clamp linear scales (plouc#1342)
Browse files Browse the repository at this point in the history
Optional ability to tell a scale to clamp. use case e.g. setting bar
value below zero

fixes plouc#1188

Co-authored-by: Sam Jones <[email protected]>
  • Loading branch information
2 people authored and ddavydov committed Apr 8, 2021
1 parent b29b6a0 commit b65b667
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/scales/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ declare module '@nivo/scales' {
max?: 'auto' | number
stacked?: boolean
reverse?: boolean
clamp?: boolean
}

export interface PointScale {
Expand Down
4 changes: 3 additions & 1 deletion packages/scales/src/linearScale.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { scaleLinear } from 'd3-scale'
import PropTypes from 'prop-types'

export const linearScale = (
{ axis, min = 0, max = 'auto', stacked = false, reverse = false },
{ axis, min = 0, max = 'auto', stacked = false, reverse = false, clamp = false },
xy,
width,
height
Expand All @@ -34,6 +34,7 @@ export const linearScale = (

scale.type = 'linear'
scale.stacked = stacked
scale.clamp(clamp)

return scale
}
Expand All @@ -44,4 +45,5 @@ export const linearScalePropTypes = {
max: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number]),
stacked: PropTypes.bool,
reverse: PropTypes.bool,
clamp: PropTypes.bool,
}
14 changes: 14 additions & 0 deletions packages/scales/tests/linearScale.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,17 @@ it(`should allow to reverse domain`, () => {
expect(scale(0.5)).toBe(50)
expect(scale(1)).toBe(100)
})

it(`should allow to clamping`, () => {
const scale = linearScale(
{ axis: 'y', clamp: true, min: 0.5 },
{ y: { min: 0, max: 1 } },
100,
100
)

expect(scale.domain()[0]).toBe(0.5)
expect(scale(0)).toBe(100)
expect(scale(0.5)).toBe(100)
expect(scale(1)).toBe(0)
})

0 comments on commit b65b667

Please sign in to comment.