D3js v4版本 画散点图

前一段时间在学习D3js,网上很多的例子都是针对v3版本的例子,其实和v4版本的差异还是挺大的。把之前做的一些列子分享出来,大家一起学习进步。
本次画的是基本的散点图,效果图、代码如下,就不过多的介绍了,应该看代码就明白了


image.png
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <style>
        #container{
            margin: 20px;
            /* background: black; */
        }
        .title{
            stroke: blueviolet;
        }
        svg{
            background: #000;
        }
        .axis path,
        .axis line {
        fill: none;
        stroke: #fff;
        shape-rendering: crispEdges;
        }
    
        .axis text {
        font-family: 'Microsoft YaHei';
        font-size: 12px;
        fill:#fff;
        }
    </style>
</head>
<body>
    <div id="container"></div>
</body>
</html>
<script>
     // 数据点
     var dataset = [
      [0, 0], [65.66, 420], [540, 260], [360, 320], [200, 200],
      [130, 623], [652, 52], [333, 666], [729, 656], [134, 352],
      [120, 56], [905, 177], [777, 888], [550, 680]
    ];
    let width=800
    let height=400
    let padding=60

    //创建画布
    let svg=d3.select("#container")
    .append("svg")
    .attr("width",width)
    .attr("height",height)
    
    //添加标题
    svg.append("text")
    .attr("x",width/2-120)
    .attr("y",30)
    .attr("class","title")
    .text("d3散点图")

    //x轴标尺
    let xScale=d3.scaleLinear()
    .domain([0,d3.max(dataset,(d)=>d[0])])
    .range([padding,width-padding*2])

     //y轴标尺
    let yScale=d3.scaleLinear()
    .domain([0,d3.max(dataset,(d)=>d[1])])
    .range([height-padding,padding])

     //原点的标尺
    var rScale = d3.scaleLinear()
      .domain([0, d3.max(dataset, function(d) {
        return d[1];
      })]).range([2, 4]);

      //画出各个点点并添加到画布中
      svg.selectAll("circle")
      .data(dataset)
      .enter()
      .append("circle")
      .attr("cx",(d)=>{
          return xScale(d[0])
      })
      .attr("cy",(d)=>{
          return yScale(d[1])
      })
      .attr("r",(d)=>{
          return rScale(d[1])
      })
      .attr("fill","red")

     
       //x坐标轴
      let xAxis=d3.axisBottom()
      .scale(xScale)
      .ticks(7)

      //y坐标轴
      let yAxis=d3.axisLeft()
      .scale(yScale)
      .ticks(7)

      //把坐标轴添加到画布中
      svg.append("g")
      .attr("class","axis")
      .attr("transform","translate(0,"+(height-padding)+")")
      .call(xAxis)
      svg.append("g")
      .attr("class","axis")
      .attr("transform","translate("+padding+",0)")
      .call(yAxis)
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容