Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom)
I want to animate the bars from Bottom to Top Currently, I am using transition and duration for animation and setting svgHeight as the bar height. However, the animation ends up being displayed as shown in the [demo][1]. Any suggestions or assistance would be greatly appreciated. I have already tried adjusting the height and y attributes of the graph.


import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3';
import { transformAll } from '@angular/compiler/src/render3/r3_ast';

@Component({
  selector: 'app-scorebenchmarking',
  templateUrl: './scorebenchmarking.component.html',
  styleUrls: ['./scorebenchmarking.component.css'],
})
export class ScorebenchmarkingComponent implements OnInit {
  dataset = [3, 2, 2, 3, 1, 2, 1, 1, 1, 1];
  colors = [
    'green',
    'green',
    'green',
    'orange',
    'orange',
    'orange',
    'orange',
    'red',
    'red',
    'red'
  ];
  listcompanies = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  svgWidth = 900;
  svgHeight = 300;
  barPadding = 5;
  barWidth = this.svgWidth / this.dataset.length - 30;
  clickObject = 0;

  constructor() {}

  ngOnInit(): void {
    this.buildSvg();
  }

  buildSvg() {
    var svg = d3
      .select('svg')
      .attr('width', this.svgWidth)
      .attr('heigth', this.svgHeight);

    var yScale = d3
      .scaleLinear()
      .domain([0, d3.max(this.dataset)])
      .range([0, this.svgHeight - 30]);

    var barchart = svg
      .selectAll('rect')
      .data(this.dataset)
      .enter()
      .append('rect')
      .attr('class', (d: any, i: any) => {
        return 'rect' + (i + 1);
      })
      .attr('fill', (d: any, i: any) => {
        return this.colors[i];
      })
      .attr('y', (d: any) => {
        return this.svgHeight - yScale(d);
      })
      .attr('height', (d: any) => {
        return 0;
      })
      .attr('width', this.barWidth - this.barPadding)
      .attr('transform', (d: any, i: any) => {
        var translatenum = [this.barWidth * i, 0];
        return 'translate(' + translatenum + ')';
      })
      .on('click', (d: any) => {
        this.clickObject = d;
      })
      .on('mouseover', (d: any, i: any) => {
        d3.select('.rect' + (i + 1))
          .transition()
          .duration('600')
          .attr('opacity', '0.6');
      })
      .on('mouseout', (d: any, i: any) => {
        d3.selectAll('.rect' + (i + 1))
          .transition()
          .duration('600')
          .attr('opacity', '1');
      });

    var temp = d3
      .selectAll('rect')
      .transition()
      .duration(1500)
      .attr('height', (d: any) => {
        return yScale(d);
      });

    var text = svg
      .selectAll('text.no_of_companies')
      .data(this.dataset)
      .enter()
      .append('text')
      .text((d: any) => {
        return d;
      })
      .attr('y', (d: any, i: any) => {
        return this.svgHeight - yScale(d) - 6;
      })
      .attr('x', (d: any, i: any) => {
        return this.barWidth * i + 24;
      })
      .attr('fill', 'black');

    var sizeofaxis = (this.barWidth + this.barPadding) * 10 - 55;

    var line = svg
      .append('line')
      .attr('x1', 0)
      .attr('y1', this.svgHeight)
      .attr('x2', sizeofaxis)
      .attr('y2', this.svgHeight)
      .attr('stroke', 'black');

    var textforAxis = svg
      .selectAll('text.axis_labels')
      .data(this.listcompanies)
      .enter()
      .append('text')
      .text((d: any) => {
        return d;
      })
      .attr('y', (d: any, i: any) => {
        return this.svgHeight + 20;
      })
      .attr('x', (d: any, i: any) => {
        return this.barWidth * i + 24;
      })
      .attr('fill', 'black');
  }
}


>This is my code .
>Please Help


  [1]: https://i.sstatic.net/CSpO9.gif

Answer №1

Adjust the starting height to yScale(d) and the animated height to 0. When working with d3, keep in mind that (0,0) marks the top left corner.

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

angular trustAsHtml does not automatically insert content

Two divs are present on the page. Upon clicking button1, an iframe is loaded into div1. The same applies to button2 and div2. These iframes are loaded via ajax and trusted using $sce.trustAsHtml. This is how the HTML looks: <div ng-bind-html="video.tru ...

How to handle a POST request with an empty body in Node.js express routing, utilizing body-parser

I'm facing an issue where my submission form's post requests are returning an empty body, regardless of the body parser settings I apply. All my dependencies in package.json are up to date, and a previous application I created (using the deprecat ...

What is the most effective approach to handling dependencies for an AngularJs 1.x web application?

Right now, I have a bunch of script elements pointing to cdn/local files, which isn't ideal. I'm considering declaring all necessary packages using npm/yarn and serving cdn files with self-hosted fallback. Is this a good idea? Would it be bette ...

The issue of overwritten callbacks is occurring due to the use of multiple .use() functions on the

Utilizing a module known as consign, I am able to conveniently include multiple modules from a directory all at once, eliminating the need for numerous require statements. In my code, I have set the mount path for each endpoint at the beginning of the rout ...

How can JavaScript routes be used to apply specific code to multiple pages on a website?

Can you provide guidance on how to run the same code for multiple pages using routes? Below is an example I am currently exploring: var routeManager = { _routes: {}, // Collection of routes add: function(urls, action) { urls.forEach(fun ...

Pattern to prevent consecutive hyphens and identical digits next to one another in a series

Here is a regular expression that can validate all numbers not being the same even after a hyphen: ^(\d)(?!\1+$)\d{3}-\d{1}$ For example, in the pattern: 0000-0 would not be allowed (all digits are the same) 0000-1 would be allowed 111 ...

After reducing the size of the table, the data spills over

Hey there, amazing individuals of the internet! Hope you're all doing well today. I've encountered a rather perplexing issue that's got me stumped. So, here's the situation - I have this table full of data and I want it to initially be ...

Unable to pass an Array to the Controller

let formData = new FormData(); payloadData = JSON.stringify(payload.unitDoctors); for (var prop in payloadData) { formData.append(prop, payloadData[prop]); } axios({ method: "put", url: apiUrl + payload.id, data: formData }) .then(resp ...

How can we use JavaScript to close a dropdown menu when the user clicks outside of it?

I am facing an issue with my code. I want to close the dropdown menu when clicking outside of it or on the items within the dropdown. How can I achieve this? I attempted to use addEventListener('click', myFunction) on `document` but it did not w ...

Is there a native feature in Vue.js that allows for the addition of a duplicate of a constantly saved object to an array that is repeated

Having an issue with my Vue.js app where adding a newItem to a list of items results in the added object being bound to the input. Here's what I've tried so far: new Vue({ el: '#demo', data: { items: [ { start: & ...

Verify if the specified key is present in the type parameter and if it corresponds to the expected data type in the value parameter

I have a specific goal in mind: export interface GCLPluginConfig { [key: string]: string | number | boolean | Date | string[]; } export interface CorePluginConfig extends GCLPluginConfig { "core.lastUpdateCheck": Date; } export interface An ...

AngularJS: Modifying values in one div updates data in all other divs

The webpage appears as shown below: https://i.sstatic.net/IxcnK.png HTML <li class="list-group-item" ng-repeat="eachData in lstRepositoryData"> <div class="ember-view"> <div class="github-connection overflow-hidden shadow-oute ...

Is there a method to iterate through dynamically added nested arrays, similar to the Russian Matryoshka dolls?

I am facing a challenge in my Angular TypeScript class where I need to define a function that can loop through dynamically added nested arrays. The issue arises because my template displays a custom Kendo grid which requires me to traverse a type of "Matri ...

Preventing the addition of hash tags to the URL by the anything slider

Why does the Anything Slider add hash tags like #&panel1-1 to the end of the URL? I attempted using hashtags:false but it was unsuccessful. Are there alternative methods to prevent it from creating these hashtags? ...

What are the best practices for utilizing the Express router efficiently?

When building a TypeScript REST API, is there any difference between router.get(); router.post(); router.patch(); router.delete(); ---------------- app.use(); app.use(); app.set(); and router .get() .post() .patch() .delete(); ---------- ...

Facing issues with Handsontable opening within a jQuery UI dialog?

After implementing the Handsontable plugin in multiple tables, everything appears as expected on the parent page. However, when attempting to open a dialog containing a table, the tables do not display properly (only in IE). A demonstration of this issue c ...

One parent contains two identical components, but the first component takes precedence over the second

Within my component, I have two subcomponents that are identical: <!-- Some code ... --> <app-upload-button #idBook [accept]="'image/*'" (loadend)="onImageLoaded('#this-idbook-preview')" > </app-upload-button> ...

The data set in a setTimeout is not causing the Angular4 view to update as expected

I am currently working on updating a progress bar while importing data. To achieve this, I have implemented a delay of one second for each record during the import process. Although this may not be the most efficient method, it serves its purpose since thi ...

Issue: Unable to locate a matching object '[object Object]' of type 'object'. NgFor can solely bind to data structures like Arrays and Iterables

I am facing an error that says "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." I am trying to create a Notification list but I can't figure out w ...

Issue with Camera inversion not functioning properly in THREE.js with 1 Renderer and 2 Viewports

Check out this JSFiddle example In my project, I have a single scene with two cameras. Each camera is assigned to its viewport, and both viewports are placed side by side on the same renderer object. My goal is to have the second camera display a mirrore ...