What's the reason behind the absence of the bar chart in this presentation?

I need help making a bar chart using d3 and Angular(in VSCode). The x-axis doesn't seem to work properly. Can anyone assist me with this issue? Currently, only the y-axis is displaying without any additional response. I've been stuck on this problem for a while now and despite trying different code tweaks, there hasn't been any progress.

Thank you!

//elect.tsv enter image description here

//template.component.ts

import {Component, ElementRef, OnInit, ViewChild, AfterViewInit} from '@angular/core';
import * as d3 from 'd3';

interface ILayoutInfo {
  marginTop: number;
  marginRight: number;
  marginBottom: number;
  marginLeft: number;
  height: number;
  width: number;
  boundedHeight?: number;
  boundedWidth?: number;
}

interface IData {
  idx : string;
  elect : string;
  fre : number;
  decrease : number;
  increase : number;
  nochange : number;
}

@Component({
  selector: 'app-template',
  templateUrl: './template.component.html',
  styleUrls: ['./template.component.scss']
})

export class TemplateComponent implements OnInit, AfterViewInit {
  layout: ILayoutInfo;

  @ViewChild('rootSvg') svgRoot!: ElementRef;
  constructor() {
    this.layout = {
      marginTop: 20, marginRight: 20, marginBottom: 30, marginLeft: 40,
      height: 500, width: 960
    };
  }

  ngOnInit(): void {
  }

  ngAfterViewInit() {
    d3.tsv('./assets/elect.tsv').then((d: any) => {
      d.decrease = +d.decrease;
      d.idx = +d.idx;
      return d;
    }).then((data: IData[]) => {
      this.render(data);
    });
  }

  render(data: IData[]): void {
    
    const svg = d3.select(this.svgRoot.nativeElement)
      .attr('width', this.layout.width)
      .attr('height', this.layout.height);

    const width = +svg.attr('width') - this.layout.marginLeft - this.layout.marginRight,
      height = +svg.attr('height') - this.layout.marginTop - this.layout.marginBottom;

    const x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
    const y = d3.scaleLinear().rangeRound([height, 0]);
    console.log(x);

    const g = svg.append('g')
      .attr('transform', 'translate(' + this.layout.marginLeft + ',' + this.layout.marginTop + ')');

    x.domain(data.map(d => d.idx));
    y.domain([0, d3.max(data, (d: IData) => d.decrease) as number]);

    g.append('g')
      .attr('class', 'axis axis--x')
      .attr('transform', 'translate(0,' + height + ')')
      .call(d3.axisBottom(x).ticks(10))
      .select('path')
      .style('display', 'none');

    g.append('g')
      .attr('class', 'axis axis--y')
      .call(d3.axisLeft(y).ticks(10))
      .append('text')
      .attr('transform', 'rotate(-90)')
      .attr('y', 6)
      .attr('dy', '0.71em')
      .attr('text-anchor', 'end')
      .text('Decrease');
      
    g.selectAll('bar')
      .data(data)
      .enter().append('rect')
      .attr('class', 'bar')
      .attr('x', (d: IData) => x(d.idx) as number)
      .attr('y', (d: IData) => y(d.decrease))
      .attr('width', x.bandwidth())
      .attr('height', function(d) { return height - y(d.decrease); })
      .attr('fill', 'steelblue')
      .on('mouseover', function (this) {
        d3.select(this).attr('fill', 'brown');
      })
      .on('mouseout', function (this) {
        d3.select(this).attr('fill', 'steelblue');
      });

  }
}
//template.component.html

<div class="container">
    <svg #rootSvg class="chart"></svg>
</div>

Answer №1

The x-axis on your chart is currently set to not display due to the display: none style attribute being applied.

To fix this issue, simply delete the following lines of code:
g.append('g')
      .attr('class', 'axis axis--x')
      .attr('transform', 'translate(0,' + height + ')')
      .call(d3.axisBottom(x).ticks(10))
      // remove the lines below --> 
      // .select('path')  
      // .style('display', 'none');

Once you have removed those lines, the x-axis should appear as expected. 👍

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

To work with Typescript, the 'unknown' type needs to be equipped with

I encountered an issue in vscode stating "Type 'unknown' must have a 'Symbol.iterator' method that returns an iterator." for the following line of code: bookmarks.push(...this.$auth.user?.bookmarks); let bookmarks = []; if(this.$au ...

Unexpected Behavior when Passing @Input() Data Between Parent and Child Components in Angular 2 Application

I am currently in the process of abstracting out a tabular-data display to transform it into a child component that can be loaded into different parent components. The main aim behind this transformation is to ensure that the overall application remains "d ...

Using AsyncPipe within an ngFor loop to display items

What is the best practice for using an AsyncPipe within an ngFor loop to handle asynchronous calls for items in a list? Scenario: Imagine I have an Order object with Products, and I need to display each product's manufacturer. However, the manufactur ...

Struggling with defining content and background scripts while using AngularJS2 CLI to build a Chrome extension

After creating a brand new AngularJS-2 application using the cli tool from github, I discovered that running ng build compiles my sources into a /dist folder. As I am developing a chrome extension, I need to specify the location of my content script (whi ...

Can I access the component attributes in Vuetify using Typescript?

For example, within a v-data-table component, the headers object contains a specific structure in the API: https://i.stack.imgur.com/4m8WA.png Is there a way to access this headers type in Typescript for reusability? Or do I have to define my own interfac ...

What steps can I take to resolve a dependency update causing issues in my code?

My program stopped working after updating one of the dependencies and kept throwing the same error. Usually, when I run 'ng serve' in my project everything works fine, but after updating Chartist, I encountered this error: An unhandled exception ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...

Leveraging the value within .forRoot() with the help of a Service

In my current setup with NX environment, I am effectively managing multiple projects. While there is no default method provided for working with environments in this environment, I have devised a service that effectively implements the necessary environmen ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

The inner HTML is malfunctioning: the function is not defined within the context of Angular

var table :HTMLTableElement = <HTMLTableElement> document.getElementById("test1"); var row = table.insertRow(1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); var cell5 = ...

Organizing a store in a hierarchical structure

I am currently facing an issue with creating a hierarchical store in Angular. My goal is to have multiple reducers that work on specific parts of the application. Here's the scenario: I am working on an HR application that has a talent (employee) mod ...

Tips for accurately implementing the onHoverIn TS type in the React Native Web Pressable component

I'm working with React Native Web and Typescript, and I want to integrate the React Native Web Pressable component into my project. However, I encountered an issue where VSCode is showing errors for React Native Web prop types like onHoverIn. The pro ...

Angular: Issue with FormArrays not iterating properly

Apologies for the lengthy post, but I needed to provide a detailed explanation of the issue I am facing. In my form, there is a control that contains an array of JSON data. I have created a reactive form based on this structure. Below are the JSON data an ...

A guide to implementing vue-i18n in Vue class components

Take a look at this code snippet: import Vue from 'vue' import Component from 'vue-class-component' @Component export default class SomeComponent extends Vue { public someText = this.$t('some.key') } An error is being thr ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

Tips for inserting a row component into a table using Angular 7

I am currently using the latest version of Angular (7.2.0). I have created a custom tr component as follows: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-table-row', templateUrl: './table- ...

Exploring ways to ensure robust typing for the body of NextApiRequest within a Next.js environment

Are you trying to figure out how to correctly define the body type of an API POST route in Next.js for better type safety? In NextApiRequest, the body is currently defined as "any" and NextApiRequest itself is not generic. I have tried forcefully assigni ...

Please indicate the generator title (for example, nx generate @nrwl/workspace:library) specifically for Angular

Currently, I am expanding my knowledge in web development. While working with Angular, I encountered an issue when trying to create a new component. The error message reads "Specify the generator name (e.g., nx generate @nrwl/workspace:library)" after exec ...

Showing a header 2 element just once using both *ngFor and *ngIf in Angular

I have an array of words with varying lengths. I am using ng-For to loop through the array and ng-if to display the words based on their lengths, but I am struggling to add titles to separate them. Expected Outcome: 2 letter words: to, am, as... 3 lette ...

Guide on dynamically applying a CSS rule to an HTML element using programming techniques

Currently working with Angular 6 and Typescript, I am facing a unique challenge. My task involves adding a specific CSS rule to the host of a component that I am currently developing. Unfortunately, applying this rule systematically is not an option. Inste ...