Sachin Rajput
Sachin Rajput

Reputation: 248

labels on x axis in scale time d3.js

Im trying to have the only dates appear on the x axis currently when I do that I takes both the dates and some times as well bellow is the code that I'm using to get the current graph

**Problem: ** Im getting date with days rather I want dates with months **I want my axis axis to print labels proper I'm attaching another image fro the problem **

Code :

<!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>

Current output: enter image description here

Expected Output: enter image description here

2nd problem the x axis is cumbersome enter image description here

Any help or lead will be a great help

Updated the code to use the custom date parser

<!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>

it still didn't work

Upvotes: 0

Views: 1734

Answers (1)

Dan
Dan

Reputation: 1581

If you want one tick for each data point, then you could do

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);

If you want one tick per month, then you could change the xAxis to

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

Here's the full code

<!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>

Upvotes: 3

Related Questions