Graphical representation showing the bar graph extending below the y-axis implemented through D3

I'm having trouble with my elements bleeding into the bottom padding and it's messing up my layout. I've tried adjusting the height and scales, but nothing seems to work. It's frustrating because it seems like such a simple issue. Here's the link to the project on Codepen: https://codepen.io/critchey/pen/YzEXPrP

Here is a screenshot of what I mean: https://i.sstatic.net/rNCm7.png

In case you're wondering, here's the javascript code:

//Mapping dataset to its x and y axes
const xData = dataset.map(d => {
  let date = new Date(d[0]);
  return date;
});

const xDates = xData.map(d => {
  let dateFormatted = d.toLocaleString("default", {month: "short"}) + ' ' + d.getDate() + ', ' + d.getFullYear()
  return dateFormatted;
});

const yData = dataset.map(d => d[1]);
//Variable for use inside D3
const h = 400;
const w = 800;
const pad = 40;

//Scales for the SVG element
const xDateScale = d3.scaleTime()
              .domain([0, w])
              .range([pad, w - pad]);
const xScale = d3.scaleLinear()
              .domain([0, yData.length])
              .range([pad, w - pad]);
const yScale = d3.scaleLinear()
              .domain([0, d3.max(yData, (d) => d)])
              .range([h - pad, pad]);

//Declaring the SVG element
const svg = d3.select('#svg-container')
              .append('svg')
              .attr('width', w)
              .attr('height', h)

//Declaring each bar
svg.selectAll('rect')
    .data(yData)
    .enter()
    .append('rect')
    .attr('x', (d, i) => xScale(i))
    .attr('y', (d, i) => yScale(d))
    .attr("width", w / (yData.length - pad * 2))
    .attr("height", (d, i) => d)
    .attr("class", "bar")
    .append('title')
    .text((d, i) => `GDP: ${d} | Date: ${xDates[i]}`)

//Axes Declarations
const xAxis = d3.axisBottom(xDateScale);
const yAxis = d3.axisLeft(yScale);

svg.append("g")
    .attr("transform", `translate(0,${h - pad / 2})`)
    .call(xAxis);
svg.append("g")
    .attr("transform", `translate(${pad},0)`)
    .call(yAxis)

Answer №1

It seems like the issue lies in not properly utilizing the appropriate value for the height attribute when dealing with your rect elements.

To rectify this, consider implementing the following adjustment:

.attr("height", (d, i) => yScale(0) - yScale(d))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to use onclick event in an anchor tag to send post values through Ajax!

Can I send post values via AJAX using an onclick event on an anchor tag? I've tried the following code but I'm not receiving any post values. How can I make it work? ............................................................................. ...

Is there a way to implement a one-second delay before displaying a drop-down hover menu?

I've been trying to use the setTimeout function, but so far I haven't been able to figure out the correct way to do it. Any ideas on what I might be missing? JSFIDDLE $('.drop-down').click(function() { $(this).hide(); }); $(&apo ...

Not entirely certain about how to execute this concept using AJAX

While pondering the development of an instant messaging application, I aimed to decrease the frequency of AJAX requests (currently one every .2s). This led me to devise a unique approach: Initiate an AJAX request from the user side to the server. Wait ...

Adding React components dynamically through code

My journey with React is just beginning, and I am faced with a challenge of adding new components to an existing setup. However, I'm unsure of the process. Here is my current scenario: I have a list of Seances along with a button to add more: Seanc ...

React JS simple validator package not functioning properly with post-property date

I am currently utilizing the simple react validator package for form validation in my react JS project. For those interested, you can find the package at this link: https://www.npmjs.com/package/simple-react-validator However, I have encountered an issue w ...

jQuery struggles to properly interpret JSON data retrieved from a PHP file

I have successfully encoded WordPress data as JSON for a store locator page, however, I am encountering an issue where the page fails to parse the returned JSON. Even though the file is present and it indeed returns the correct JSON data, I receive a 404 N ...

Click Action on CanJS Table

I am currently developing a canJS application and have been able to successfully handle the click event for an HTML table using the code below. 'table td click':function(el,event){ console.log('clicked ',el.text()); } ...

Executing a sibling component's function in React – the ultimate guide!

I am relatively new to the front-end development world and struggling with triggering a function from a sibling component. Let's consider that I have 2 components in App.js. The layout is shown below: https://i.sstatic.net/3C4Av.png function App() { ...

Certain mobile devices experiencing issues with AngularJS filters

Currently, I am attempting to filter an AngularJS array by utilizing custom filters within a controller. The filters are functioning correctly on certain mobile devices, yet they are not working on others. Here is the code snippet that I am using: var a ...

Having npm start is causing an error to be displayed

I am encountering an issue when I try to start 'npm' on my mean.js application. The error message is related to a missing file called '.csslintrc'. Below, I have included the terminal output as well as the snippet of code where the erro ...

Errors encountered while running the Bower install command

Hey there, I'm having trouble with the Bower install command. It keeps trying to resolve ngTour and I can't seem to figure out what's going on! Here's a screenshot of the output from my CMD: https://i.sstatic.net/VJyS7.png Here's ...

Connection point for linking offspring records to their guardian without returning any results

I am currently using mongoose and express to generate a collection of blog categories with their respective blog posts based on the category_id. My approach involves retrieving all categories, looping through them using underscore, and for each category, ...

Loading data onto a page using jQuery in ASP.NET after a postback

Currently experimenting with a jQuery plugin called jQuery Autocomplete Tokenizer. I'm facing an issue where I need to reload the values back into the textbox after the page is posted back, retaining whatever items were previously entered. Here' ...

Achieve a scrolling DIV that moves with the page's content without relying on the pos

I'm facing an issue where I have a div on the left-hand side of my page that needs to scroll along with the page. Using position:fixed works, but when I resize the browser window, the div ends up overlapping other elements on the page. This is clearly ...

Show users who liked a post from 2 different collections in Meteor

How do I retrieve a list of users who have "liked" this post from a collection and display it in a template? Collections: likes: { "_id": 1234, "userId": "1dsaf8sd2", "postId": "123445" }, { "_id": 1235, "userId": "23f4g4e4", "pos ...

Guide on incorporating both a relational (PostgreSQL) and a non-relational (MongoDB) database into a Node.js application

I'm currently working on a Node Js project that requires me to utilize two databases within a single application - specifically MongoDb and postgreSql. Up until now, I've only worked with one database per project, so I'm curious: is it possi ...

A helpful guide on using workbox to effectively cache all URLs that follow the /page/id pattern, where id is a

Looking at this code snippet from my nodejs server: router.get('/page/:id', async function (req, res, next) { var id = req.params.id; if ( typeof req.params.id === "number"){id = parseInt(id);} res.render('page.ejs' , { vara:a , va ...

Do form validations affect the values assigned to ng-model objects?

If a form has the structure below: <form> <input type="text" required ng-model='myValue' ng-maxlength='5'></input> {{myValue}} {{myValue.length}} </form> Is there a way to prevent the model from b ...

Unable to create follow/unfollow feature with jquery ajax

Issue: While the database part for following and unfollowing actions is functioning correctly, there seems to be a problem with the jQuery and Ajax section. The follow button changes to unfollow (with some CSS styling) only after refreshing the page, rathe ...

The issue of `Console.log` displaying as undefined arises after subscribing to a provider in Ionic3

In the process of implementing the Spotify api into my Ionic 3 app, I encountered an issue where the data retrieved appears as undefined when attempting to log it. Let me share some code and delve deeper into the problem. Here is the function getData() tha ...