Is there a way to create a bar chart that begins at the 0 point of the y-axis instead of starting from the base of the SVG?

Is there a way to start the bar chart from the 0 point of the y-axis instead of the very bottom of the svg? How can I achieve this?

 let url = "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json";

const padding = 50;
const height = 460;
const width = 900;

 var svg = d3.select('body')
    .append('svg')
    .attr('width', width)
    .attr('height', height);

var arr = [];
    d3.json(url, function(data) {
        for (let i = 0; i < data.data.length; i++) arr[i] = data.data[i]; 

    const yScale = d3.scaleLinear()
                     .domain([0, d3.max(arr, (d) => d[1])])
                     .range([height - padding, padding]);

    const yAxis = d3.axisLeft(yScale);

   svg.append('g')
      .attr('transform', 'translate(' + padding + ', 0)')
      .call(yAxis)

    svg.selectAll('rect')
        .data(arr)
        .enter()
        .append('rect')
        .attr('fill', 'blue')
        .attr('height', d => d[1] + padding)
        .attr('width', 2.909090909090909)
        .attr('x', (d, i) => padding + (3.2 * i))
        .attr('y', d => yScale(d[1]))
        .append('title')
        .text(d => d[1])

    });
    <script src="https://d3js.org/d3.v4.min.js"></script>

Answer №1

Your method of calculating the height of the rectangle is inaccurate and does not take into account your scale. Additionally, using padding in this way deviates from the usual D3 convention.

    svg.selectAll('rect')
        .data(dataArray)
        .enter()
        .append('rect')
        .attr('fill', 'green')
        .attr('height', d => totalHeight - padding - yScaleValue(d[1]))

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

What could be causing the issue with the exports field in package.json not functioning properly within

Recently, I created an npm package that includes three js files. Now, in my current project, I am aiming to import these js files using the following syntax: import MyButton from '@bslm/ui/MyButton' To achieve this, I made sure to specify the ex ...

Locating the JSON path within an object

Need help with checking if a specific path is present in a JSON object? var data = { "schemaOne": { "name": "abc", "Path": "i.abc", "count": 5347, "subFolders": [ ] }, "schemaTwo": { "name": "cde", "Path": "i.cde", " ...

The tooltips in the WordPress-Gulp-Starter-Kit running on Bootstrap 5 do not seem to be functioning properly

I'm having trouble with tooltips not working properly. The codebase I'm using is from this repository https://github.com/oguilleux/webpack-gulp-wordpress-starter-theme If you need more details, feel free to reach out. Here is my main.js file: ...

Exploring time differences in Javascript

I am trying to save a JSON AJAX response from the server in the browser's localStorage for a duration of one minute, along with a timestamp generated using new Date().getMinutes(). Upon triggering $(document).ready, I aim to check the stored timestam ...

Setting up redux with Next.js: a step-by-step guide

After setting up redux in this manner, everything is functioning properly. The _app.js file has been reorganized as follows : import App from 'next/app'; import { Provider } from 'react-redux'; import withRedux from 'next-redux-wr ...

Make sure to retain PHP includes/requires when dynamically loading a new page using AJAX

My website has a main page with a header, navbar, footer, and content is loaded using AJAX into a div: <div id="content" class="page-content"></div> I am wondering if it's feasible to load a page dynamically into the content div using AJA ...

Using jQuery to iterate through rendered HTML with the ForEach function

I am utilizing JS/jQuery code to extract the cell value of an ASP DetailsView control (rendered HTML), validate it against a condition, and hide a specific div based on the result. Specifically, the code is examining whether the cell value is formatted lik ...

Storing a jquery ajax response for faster retrieval in javascript/browser

Is there a way to implement caching for ajax responses in JavaScript or the browser? According to the jquery.ajax documentation: The default behavior is that requests are always issued, but the browser may serve results from its cache. To prevent the ...

Moving towards the target is a Three.js object

I'm struggling with an issue where the x position of my object moves quicker than the z position, or vice versa. How can I make my object slow down for the x position if the z position requires more time to move? This is the code in my animation func ...

Angular page not reflecting show/hide changes from checkbox

When the user clicks on the checkbox, I need to hide certain contents. Below is the code snippet: <input id="IsBlock" class="e-field e-input" type="checkbox" name="IsBlock" style="width: 100%" #check> To hide content based on the checkbo ...

Tips for setting up the image as the header background in HTML5 and CSS3

I am currently designing a website. I'm wondering if there is a way to create a div with a curved bottom using HTML5, CSS3 and JavaScript. It should resemble the design of the curved header bottom ...

Every time I try to stream this, I encounter a JSONDecodeError

Currently, I am utilizing the Python requests library to stream a URL. However, I keep encountering this recurring error: import json import requests s = requests.Session() payload = {'limit': 0} r = s.get('https://api.coinmarketcap.com/v1 ...

What could be causing my function to not register with my EventListener?

I'm attempting to perform an action when I click on an element. I have added an eventListener to change the value of a variable upon clicking on that element. However, the eventListener is not working as expected. When I debug the code, it seems like ...

Online application for saving a vast quantity of information on the user's device

Is there a way for a web application to store an extensive amount of data client-side, allowing for millions of records to be accessed offline by users exclusively on Chrome? I initially considered indexedDb, but I discovered it becomes almost unusable wi ...

Implementing a keypress function that can handle duplicate names

HTML <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="total" type="text" value="0" disabled="disabled"/> Javascript $('[name="pm"]' ...

Preventing jQuery slideToggle functionality from toggling multiple elements at once

I am currently working on a project where I have a series of images with captions that appear underneath each one. To show or hide the caption for each image, I am using slideToggle when the image is clicked. $('.imageholder').click(function() ...

What is the solution to the problem "How can you resolve the issue where 'Cannot set property 'ref' of undefined' occurs"?

My goal is quite simple - I just want to retrieve data from Cloud Firestore. Below is the code snippet I am using: import React from 'react'; import firebase from "react-native-firebase"; export default class newsFeed extends React.Component { ...

Activate the mouseenter event as soon as an animated element makes contact with the cursor

As I venture into the world of web development, I am currently working on creating a game where the main objective is to avoid touching moving circles with the cursor. My approach involved using a mouseenter event as shown in the JSFiddle example below: $ ...

Does anyone know how to disable JavaScript on a webpage specifically for a Blackberry 8300 browser?

I am facing an issue with my JavaScript on the BlackBerry 8300, where the page renders differently when JavaScript is disabled. I would like to find a way to make sure that the "JavaScript disabled" version of the page appears for users using BlackBerry 83 ...

Prop validation error: The property "title" must be a string with a value of **, but a number with a value of ** was provided

My Vue js code displays data from a JSON API in a modal. The issue is that the title should be dynamic, but it only works when clicked twice. On the first click, I get an error and the cancel button, which triggers the hidemodal() function, crashes. Can an ...