第二十三篇 - d3绘制直方图

发布时间 2023-11-15 20:40:23作者: o云淡风轻o

当下探讨用d3制作简单横向直方图

效果图:

一、下载d3【npm install d3

二、导入d3【import * as d3 from "d3";

二、画直方图

参考链接:https://www.cnblogs.com/xuepei/p/7527082.html

1. 准备表格数据

rectlist:[
        {
          week: "星期一",
          product: 8,
        },
        {
          week: "星期二",
          product: 16,
        },
        {
          week: "星期三",
          product: 3,
        },
        {
          week: "星期四",
          product: 12,
        },
        {
          week: "星期五",
          product: 5,
        },
        {
          week: "星期六",
          product: 13,
        },
        {
          week: "星期天",
          product: 18,
        },
      ]

 

2. 处理表格数据

// 求和计算total的值
let sum = 0
for(let i=0;i<this.rectlist.length;i++){
   sum = sum + this.rectlist[i].product
}
// 得到纵轴描述列表
const nameArr = this.rectlist.map((item)=> { return item.week});
// 得到横轴数值列表即每个矩形的长度
const valueArr = this.rectlist.map((item)=> { return item.product});

 

3. 画横纵坐标轴

      //指定容器的宽高
      let padding = {top: 100, right: 20, bottom: 20, left: 20},
          width = 600 - padding.right - padding.left,
          height = 470 - padding.bottom - padding.top;

      //x,y轴比例尺
      let xscale = d3.scaleLinear().domain([0,d3.max(valueArr) + 3]).rangeRound([0,width-10]);
      let yscale = d3.scaleBand().domain(nameArr).rangeRound([height,0]).padding(0.5);

      //创建svg
      const svg = d3.select('#bar-chart-container').append('svg')
          .attr('width',width + padding.left + padding.right)
          .attr('height',height + padding.top + padding.bottom);
      //添加g标签
      const g = svg.append('g')
          .attr('transform',`translate(${padding.top}, ${padding.left})`)

      //像svg添加x轴
      g.append('g')
          .attr('class','axis')
          .attr('transform',`translate(0, ${height})`)
          .call(d3.axisBottom(xscale))
          .attr('font-weight','blod')
      //像svg添加y轴
      g.append('g')
          .attr('class','axis')
          .call(d3.axisLeft(yscale))

 1111