首页 > 解决方案 > d3.js如何绘制带有垂直x轴标签的折线图

问题描述

d3.js 如何绘制带有垂直x轴标签的折线图?

在此处输入图像描述

我的小提琴: https ://jsfiddle.net/nitinjs/p1r49qeg/

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .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 + ")");
//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/connectedscatter.csv",
  // When reading the csv, I must format variables:
  function(d){
    return { date : d3.timeParse("%Y-%m-%d")(d.date), value : d.value }
  },
  // Now I can use this dataset:
  function(data) {
    // Add X axis --> it is a date format
    var x = d3.scaleTime()
      .domain(d3.extent(data, function(d) { return d.date; }))
      .range([ 0, width ]);
    svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));
    // Add Y axis
    var y = d3.scaleLinear()
      .domain( [8000, 9200])
      .range([ height, 0 ]);
    svg.append("g")
      .call(d3.axisLeft(y));
    // Add the line
    svg.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", "#69b3a2")
      .attr("stroke-width", 1.5)
      .attr("d", d3.line()
        .x(function(d) { return x(d.date) })
        .y(function(d) { return y(d.value) })
        )
    // Add the points
    svg
      .append("g")
      .selectAll("dot")
      .data(data)
      .enter()
      .append("circle")
        .attr("cx", function(d) { return x(d.date) } )
        .attr("cy", function(d) { return y(d.value) } )
        .attr("r", 5)
        .attr("fill", "#69b3a2")
})

更新
我有几个问题,
1.如何使这个图在引导程序中响应,即。没有硬编码宽度和高度
2. 如何在按钮单击时更新此图
3. 如何从 0 开始 y 轴到任何值,例如 0 到 9100

标签: d3.js

解决方案


更新答案:要更改标签旋转只需选择所有文本元素并通过属性应用旋转,然后使用andtransform调整位置,如果您注意到我更改了变量中的填充底部值以便能够查看刻度文本,因为这将使它们通过旋转可以看到一半。dxdymargin

...
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x))
  .selectAll("text")    
    .style("text-anchor", "end")
    .attr("dx", "-.8em")
    .attr("dy", "-.5em")
    .attr("transform", "rotate(-90)");
...

或工作片段:

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 60, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom - 45;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .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 + ")");
//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/connectedscatter.csv",
  // When reading the csv, I must format variables:
  function(d){
    return { date : d3.timeParse("%Y-%m-%d")(d.date), value : d.value }
  },
  // Now I can use this dataset:
  function(data) {
    // Add X axis --> it is a date format
    var x = d3.scaleTime()
      .domain(d3.extent(data, function(d) { return d.date; }))
      .range([ 0, width ]);
    svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x))
      .selectAll("text")	
        .style("text-anchor", "end")
        .attr("dx", "-.8em")
        .attr("dy", "-.5em")
        .attr("transform", "rotate(-90)");
    // Add Y axis
    var y = d3.scaleLinear()
      .domain( [8000, 9200])
      .range([ height, 0 ]);
    svg.append("g")
      .call(d3.axisLeft(y))
      
      
    // Add the line
    svg.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", "#69b3a2")
      .attr("stroke-width", 1.5)
      .attr("d", d3.line()
        .x(function(d) { return x(d.date) })
        .y(function(d) { return y(d.value) })
        )
    // Add the points
    svg
      .append("g")
      .selectAll("dot")
      .data(data)
      .enter()
      .append("circle")
        .attr("cx", function(d) { return x(d.date) } )
        .attr("cy", function(d) { return y(d.value) } )
        .attr("r", 5)
        .attr("fill", "#69b3a2")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>

<div id="my_dataviz"></div>

更新的答案,我添加了对图表的响应并更改了左轴中第一个元素的标签,我会将数据更新留给您,还有一些注意事项,有更好的方法来制作响应式 d3 图表,其中一个是使用viewport 属性,但我自己没有测试,也是第一个从 0 开始的元素你,我希望我的改变能提供一些关于在哪里寻找的见解:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  </head>
  <body>
    <div id="my_dataviz"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
    <script>
    // set the dimensions and margins of the graph
      var margin = {top: 10, right: 30, bottom: 60, left: 60},
          width = 1280 - margin.left - margin.right,
          height = 650 - margin.top - margin.bottom - 45;
      // append the svg object to the body of the page
      var svg = d3.select("#my_dataviz")
        .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
        .append("g")
          .attr('class', 'main-container')
          .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");
      //Read the data
      d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/connectedscatter.csv",
        // When reading the csv, I must format variables:
        function(d){
          return { date : d3.timeParse("%Y-%m-%d")(d.date), value : d.value }
        },
        // Now I can use this dataset:
        function(data) {
          // Add X axis --> it is a date format
          var x = d3.scaleTime()
            .domain(d3.extent(data, function(d) { return d.date; }))
            .range([ 0, width ]);
          
          
          var axisBottom = svg.append("g")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x));

          d3.selectAll('.axis-left text').filter((d, i) => { return i === 0}).text('0,000');

          // Add Y axis
          var y = d3.scaleLinear()
            .domain( [8000, 9200])
            .range([ height, 0 ]);
          
          var axisLeft = svg.append("g")
            .call(d3.axisLeft(y));
            
          // Add the line
          var line = svg.append("path")
            .datum(data)
            .attr("fill", "none")
            .attr("stroke", "#69b3a2")
            .attr("stroke-width", 1.5)
            .attr("d", d3.line()
              .x(function(d) { return x(d.date) })
              .y(function(d) { return y(d.value) })
            )
          // Add the points
          var dots = svg
            .append("g")
            .attr('class', 'dots')
            .selectAll("dot")
            .data(data)
            .enter()
            .append("circle")
              .attr("cx", function(d) { return x(d.date) } )
              .attr("cy", function(d) { return y(d.value) } )
              .attr("r", 5)
              .attr("fill", "#69b3a2")

          function drawChart() {
            // reset the width
            width = parseInt(d3.select('body').style('width'), 10) - margin.left - margin.right;

            height = (width * 0.45) - margin.top - margin.bottom;

            d3.select("#my_dataviz svg")
                .attr("height", height + margin.top + margin.bottom)
                .attr("width", width + margin.left + margin.right)
                
              
              d3.select('.main-container')
                .attr("transform",
                      "translate(" + margin.left + "," + margin.top + ")");

            x = d3.scaleTime()
              .domain(d3.extent(data, function(d) { return d.date; }))
              .range([ 0, width ]);

            axisBottom.attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x))
            .attr('class', 'axis-bottom')
            .selectAll("text")
            .style("text-anchor", "end")
            .attr("dx", "-.8em")
            .attr("dy", "-.5em")
            .attr("transform", "rotate(-90)");

            // Add Y axis
            y = d3.scaleLinear()
              .domain( [8000, 9200])
              .range([ height, 0 ]);

            axisLeft.call(d3.axisLeft(y)).attr('class', 'axis-left');
            //this is shiit!! there must be a better way.
            d3.selectAll('.axis-left text').filter((d, i) => { return i === 0}).text('0,000');
              
            line.datum(data)
              .attr("fill", "none")
              .attr("stroke", "#69b3a2")
              .attr("stroke-width", 1.5)
              .attr("d", d3.line()
                .x(function(d) { return x(d.date) })
                .y(function(d) { return y(d.value) })
              );


          d3.select('.dots').remove();
          var dots = svg
            .append("g")
            .attr('class', 'dots')
            .selectAll("dot")
            .data(data)
            .enter()
            .append("circle")
              .attr("cx", function(d) { return x(d.date) } )
              .attr("cy", function(d) { return y(d.value) } )
              .attr("r", 5)
              .attr("fill", "#69b3a2");
          }

          // call this once to draw the chart initially
          drawChart();


          //////////////////////////////////////////////
          // Resizing //////////////////////////////////
          //////////////////////////////////////////////

          // redraw chart on resize
          window.addEventListener('resize', drawChart);



      })
    </script>
  </body>
</html>


推荐阅读