天天看点

使用d3.js - 直方图

以前做可视化是直接使用echarts的组件的,现在使用d3试试

下载d3

vue

项目中使用

d3.js

只需要

npm install d3

即可

粗糙版的直方图

使用d3.js - 直方图

分析

生成直方图分为以下几个步骤:

  • 生成矩形
  • 根据svg大小进行缩放
  • 生成坐标轴
  • 生成文字标签

直方图代码

import * as d3 from 'd3'
export default {
  name: 'Visualization',
  mounted () {
    const width = 500
    const height = 500
    const barHeight = 50
    const barAndMarginHeight = 60
    const widthScale = d3.scaleLinear().domain([0, Math.max.apply(null, this.data)]).range([0, width - 80]) //留出80的空间用来放文字
    const colorScale = d3.scaleLinear().domain([0, Math.max.apply(null, this.data)]).range(['red', 'blue'])

    const axis = d3.axisBottom(widthScale).ticks(20, 's') // 坐标轴
    const canvas = d3.select('#container')
      .append('svg')
      .attr('width', width)
      .attr('height', height)

    canvas.append('g').selectAll('rect').data(this.data)
      .enter()
      .append('rect')
      .attr('width', d => widthScale(d))
      .attr('height', barHeight)
      .attr('y', (d, i) => i * barAndMarginHeight)
      .attr('fill', d => colorScale(d))

    canvas.append('g').attr('transform', `translate(0,${this.data.length * barAndMarginHeight})`).call(axis) //调用坐标轴

    canvas.append('g').selectAll('text').data(this.data)
      .enter()
      .append('text')
      .attr('fill', 'black')
      .style('font-size', '16px')
      .attr('x', d => widthScale(d) + 10)
      .attr('y', (d, i) => i * barAndMarginHeight + barHeight / 2)
      .text(d => d) //生成文字
  },
  data () {
    return {
      data: [30, 80, 160, 50, 70, 80]
    }
  }
}