刻度时间 x 轴上的标签 d3.js

labels on x axis in scale time d3.js

我试图让当前唯一的日期出现在 x 轴上,当我这样做时,我同时获取了日期和一些时间,下面是我用来获取当前图表的代码

**问题:** 我想要有天的约会,我想要有月的约会 **我希望我的 axis 轴正确打印标签我正在附加另一张图片来解决这个问题 **

代码:

<!DOCTYPE html>
<meta charset="utf-8">
          
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v6.js"></script>
          
<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<script>
// set the dimensions and margins of the graph
const margin = {top: 10, right: 30, bottom: 30, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
// append the svg object to the body of the page
const 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
    var data=[
        {
            date: "2018-04-14",
            value: "0"
        },
        {   date: "2018-04-15",
            value: "0.1"
        },
        {
        date: "2018-04-16",
        value: "0.2"
        },
        {
        date: "2018-04-17",
        value: "0.3"
        },
        {
        date: "2018-04-17",
        value: "0.4"
        }
    ]
    for (i=0;i<data.length;i++){
        data[i]["date"]=d3.timeParse("%Y-%m-%d")(data[i]["date"])
    }
    console.log("data:--",data)
    // Add X axis --> it is a date format
    const x = d3.scaleTime()
      .domain(d3.extent(data, d => d.date))
      .range([ 0, width ]);
    svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));
    // Add Y axis
    var formatPercent = d3.format(".0%");
    const y = d3.scaleLinear()
      .domain( [0, 1])
      .range([ height, 0 ]);
    svg.append("g")
      .call(d3.axisLeft(y)
      .tickFormat(formatPercent)
      );
    // Add the line
    svg.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", "#69b3a2")
      .attr("stroke-width", 1.5)
      .attr("d", d3.line()
        .x(d => x(d.date))
        .y(d => y(d.value))
        )
    // Add the points
    svg
      .append("g")
      .selectAll("dot")
      .data(data)
      .join("circle")
        .attr("cx", d => x(d.date))
        .attr("cy", d => y(d.value))
        .attr("r", 5)
        .attr("fill", "#69b3a2")

</script>

当前输出:

预期输出:

第二个问题x轴比较麻烦

任何帮助或引导都是很大的帮助

更新了代码以使用自定义日期解析器

<!DOCTYPE html>
<meta charset="utf-8">
          
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v6.js"></script>
          
<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<script>
var myFormat = d3.timeFormat("%Y-%m-%d"); 
var parseDate = d3.timeParse(myFormat);
// set the dimensions and margins of the graph
const margin = {top: 10, right: 30, bottom: 30, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
// append the svg object to the body of the page
const 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
    var data=[
        {
            date: "2018-04-14",
            value: "0"
        },
        {   date: "2018-05-15",
            value: "0.1"
        },
        {
        date: "2018-06-16",
        value: "0.2"
        },
        {
        date: "2018-07-17",
        value: "0.3"
        },
        {
        date: "2018-08-17",
        value: "0.4"
        }
    ]
    for (i=0;i<data.length;i++){
        data[i]["date"]=parseDate(data[i]["date"])
    }
    console.log("data:--",data)
    // Add X axis --> it is a date format
    const x = d3.scaleTime()
      .domain(d3.extent(data, d => d.date))
      .range([ 0, width ]);
    svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));
    // Add Y axis
    var formatPercent = d3.format(".0%");
    const y = d3.scaleLinear()
      .domain( [0, 1])
      .range([ height, 0 ]);
    svg.append("g")
      .call(d3.axisLeft(y)
      .tickFormat(formatPercent)
      );
    // Add the line
    svg.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", "#69b3a2")
      .attr("stroke-width", 1.5)
      .attr("d", d3.line()
        .x(d => x(d.date))
        .y(d => y(d.value))
        )
    // Add the points
    svg
      .append("g")
      .selectAll("dot")
      .data(data)
      .join("circle")
        .attr("cx", d => x(d.date))
        .attr("cy", d => y(d.value))
        .attr("r", 5)
        .attr("fill", "#69b3a2")

</script>

还是不行

如果你想为每个数据点一个刻度,那么你可以这样做

const formatDate = d3.timeFormat("%d %b");

const xAxis = d3.axisBottom(x)
    .tickValues(data.map(d => d.date))
    .tickFormat(formatDate);

svg.append("g")
    .attr("transform", `translate(0,${height})`)
    .call(xAxis);

如果您想要每月一次报价,那么您可以将 xAxis 更改为

const xAxis = d3.axisBottom(x)
    .ticks(d3.timeMonth, formatDate);

这是完整的代码

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <script src="https://d3js.org/d3.v7.js"></script>
</head>

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

  <script>
    // set the dimensions and margins of the graph
    const 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
    const 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
    const parseDate = d3.timeParse("%Y-%m-%d");

    const data = [
      {
        date: "2018-04-14",
        value: "0"
      },
      {
        date: "2018-05-15",
        value: "0.1"
      },
      {
        date: "2018-06-16",
        value: "0.2"
      },
      {
        date: "2018-07-17",
        value: "0.3"
      },
      {
        date: "2018-08-17",
        value: "0.4"
      }
    ].map(({date, value}) => ({
      date: parseDate(date),
      value
    }));

    // x scale and axis

    const x = d3.scaleTime()
        .domain(d3.extent(data, d => d.date))
        .range([0, width]);

    const formatDate = d3.timeFormat("%d %b");

    // tick every month:
    // const xAxis = d3.axisBottom(x)
    //     .ticks(d3.timeMonth, formatDate);

    // tick every data point:
    const xAxis = d3.axisBottom(x)
        .tickValues(data.map(d => d.date))
        .tickFormat(formatDate);

    svg.append("g")
        .attr("transform", `translate(0,${height})`)
        .call(xAxis);

    // y scale and axis

    const y = d3.scaleLinear()
        .domain([0, 1])
        .range([height, 0]);

    const formatPercent = d3.format(".0%");

    const yAxis = d3.axisLeft(y)
        .tickFormat(formatPercent);

    svg.append("g")
        .call(yAxis);

    // Add the line

    const line = d3.line()
        .x(d => x(d.date))
        .y(d => y(d.value));

    svg.append("path")
        .datum(data)
        .attr("fill", "none")
        .attr("stroke", "#69b3a2")
        .attr("stroke-width", 1.5)
        .attr("d", line);

    // Add the points
    svg.append("g")
      .selectAll("dot")
      .data(data)
      .join("circle")
        .attr("cx", d => x(d.date))
        .attr("cy", d => y(d.value))
        .attr("r", 5)
        .attr("fill", "#69b3a2");
  </script>
</body>
</html>