Home > front end >  X and Y axis are not together
X and Y axis are not together

Time:01-06

Here is an image of what my axis looks like

Axis

As you can see, they are widely separated and I don't know why. Here is the code I've used to create them:


        margin = ({top: 40, right: 20, bottom: 40, left: 50});
        height = 500 - margin.top - margin.bottom;
        width = 600 - margin.left - margin.right;

        // Crear el svg
        var svg = d3.select("body")
            .append("svg")
            .attr("width", width)
            .attr("height", height);
        
        // Cálculo de ejes
        x = d3.scaleTime()
            .domain([2015, 2021]).nice()
            .range([margin.left, width - margin.right]);

        y = d3.scaleLinear()
            .domain([0,
                13]).nice()
            .range([height - margin.bottom, margin.top]);
        svg.append("g")
            .attr("transform", `translate( ${margin.left}, ${height - 
            margin.bottom})`)
            .call(d3.axisBottom(x).tickFormat(d3.format("d")));
        svg.append("g")
            .attr("transform", `translate(${margin.left}, 0)`)
            .call(d3.axisLeft(y))

My goal is to stick 0 and 2015 but I don't know how to do it

CodePudding user response:

The reason of this shift is the horizontal translation added by you in below code line, here the first parameter specifying the horizontal translation of x-axis due to which both axes are not intersecting with each other.

.attr("transform", `translate( ${margin.left}, ${height - margin.bottom})`)

Just change it to zero and it will resolve the issue. I have added the snippet for this below

margin = ({
  top: 40,
  right: 20,
  bottom: 40,
  left: 50
});
height = 500 - margin.top - margin.bottom;
width = 600 - margin.left - margin.right;

// Crear el svg
var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

// Cálculo de ejes
x = d3.scaleTime()
  .domain([2015, 2021]).nice()
  .range([margin.left, width - margin.right]);

y = d3.scaleLinear()
  .domain([0,
    13
  ]).nice()
  .range([height - margin.bottom, margin.top]);

svg.append("g")
  .attr("transform", `translate( 0, ${height - 
            margin.bottom})`)
  .call(d3.axisBottom(x).tickFormat(d3.format("d")));

svg.append("g")
  .attr("transform", `translate(${margin.left}, 0)`)
  .call(d3.axisLeft(y))
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

  •  Tags:  
  • Related