【问题标题】:Implement discontinuous bar chart with D3.js使用 D3.js 实现不连续的条形图
【发布时间】:2020-03-06 20:12:25
【问题描述】:

我正在尝试创建一个如下所示的设计。我想知道是否可以使用 d3 将 x 轴作为时区并隐藏 y 轴并显示如下图所示的时隙。

TIA

【问题讨论】:

    标签: javascript jquery html css d3.js


    【解决方案1】:
    1. 使用 x 比例来确定矩形的 x 坐标和宽度。
    2. 使用 y 刻度来定位矩形的 y 坐标和高度。

    <!DOCTYPE html>
    <meta charset="utf-8">
    <style> /* set the CSS */
    
    .bar { fill: steelblue; }
    
    </style>
    <body>
    	
    <!-- load the d3.js library -->    	
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script>
    
    // set the dimensions and margins of the graph
    var margin = {top: 20, right: 20, bottom: 30, left: 40},
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;
    
    // set the ranges
    var x = d3.scaleLinear()
              .range([0, width]);
    var y = d3.scaleBand()
              .range([0, height])
              .padding(0.1);
              
    // append the svg object to the body of the page
    // append a 'group' element to 'svg'
    // moves the 'group' element to the top left margin
    var svg = d3.select("body").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 + ")");
    
    data = [
        {"name" : "Bob", "start" : 0, "end" : 5},
        {"name" : "Robin", "start" : 6, "end" : 7},
        {"name" : "Anne", "start" : 7, "end" : 9},
        {"name" : "Mark", "start" : 9, "end" : 14}
    ];
    
        x.domain([0, d3.max(data, function(d) { return d.end; })]);
        y.domain(data.map(function(d) { return d.name; }));
        
        svg.selectAll(".bar")
          .data(data)
        .enter().append("rect")
          .attr("class", "bar")
          .attr("x", function(d) { return x(d.start); })
          .attr("width", function(d) { 
            return x(d.end) - x(d.start) })
          .attr("y", function(d, i) { 
            return y(d.name); })
          .attr("height", function(d) { return y.bandwidth(); });
        
        svg.append("g")
          .call(d3.axisTop(x));
        svg.append("g")
          .call(d3.axisLeft(y));
    
    </script>
    </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      相关资源
      最近更新 更多