d3.histogram直方图

直方图

在这里插入图片描述
将离散的一组数据统计在多个不重叠的连续区间中,查看数据的分布情况。

api

histogram(data)

返回一个分箱数组,每个分箱中包含部分data中的数据,还包含三个额外的属性:length: 数据的个数 x0:分箱的最小值 x1:分箱的最大值

const histogram = d3.histogram()
    .domain([ 0, 100 ])
const bins = histogram( [
    8, 11, 32, 24, 66, 88, 58, 99
] )
console.log(bins)
// [
//     { 0: 8, 1: 11, x0: 0, x1: 20, length: 2 },
//     { 0: 32, 1: 24, x0: 20, x1: 40, length: 2 },
//     ...
// ]

histogram.value

指定值访问器。

const data = [ { price: 22 } ]
const bins = d3.histogram()
    .value(d => d.price)(data)

histogram.domain

设置数据的输入区间范围,区间外的值会被过滤。默认为输入数据的最小最大值:[min, max]

histogram.thresholds

设置阀值生成器,可以是数字 数组返回数字和数组的函数。通过阀值,可以设置每个分箱的左右边界。

1.数字,代表生成的分箱个数,这是一个近似值。

2.数组:[ x0, x1, ... ],小于x0的值放入第一个分箱中,小于x1并且大于等于x0的值放入第二个分箱中,以此类推。分箱数等于array.length + 1。

3.函数。自己实现的阀值生成器会传入三个参数:values:输入的数据,min、max:输入域(domain)的左右边界

同时,d3内置有3个分箱生成器函数:d3.thresholdFreedmanDiaconis,d3.thresholdScott,d3.thresholdSturgesd3.thresholdSturges也是默认的阀值生成器函数。

DEMO

LIVE DEMO
源码

<div id="chart-wrapper"></div>

<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
    const width = 600
    const height = 400
    const margin = {
        top: 10,
        bottom: 30,
        left: 60,
        right: 60
    }

    const svg = d3.select('#chart-wrapper')
        .append('svg')
        .attr('width', width + margin.left + margin.right)
        .attr('height', height + margin.top + margin.bottom)
        .append('g')
        .attr('transform', `translate(${ margin.left }, ${ margin.top })`)

    d3.csv('./mock/histogram.csv')
        .then(data => {
            const max = 1000
            const histogram = d3.histogram()
                .value(d => +d.price)
                .domain([ 0, max ])
            const bins = histogram( data )

            const x = d3.scaleLinear()
                .domain([0, max ])
                .range([0, width])
            
            const y = d3.scaleLinear()
                .domain([0, d3.max(bins, d => d.length)])
                .range([height, 0])

            svg.append('g')
                .attr('transform', `translate(0, ${ height })`)
                .call(d3.axisBottom(x))

            svg.append('g')
                .call(d3.axisLeft(y))

            svg.append('g')
                .selectAll('rect')
                .data(bins)
                .enter()
                .append('g')
                .append('rect')
                .attr('x', d => x(d.x0) + 1 )
                .attr('y', d => y(d.length) )
                .attr('width', d => x(d.x1) - x(d.x0) - 1)
                .attr('height', d => height - y(d.length))
                .attr('fill', '#69b3a2')
        })
</script>
发布了78 篇原创文章 · 获赞 31 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/juzipidemimi/article/details/103694173
今日推荐