"Adjusting the size of a circle to zero in a D3 SVG using Angular 2

Trying to create a basic line graph using d3 in Angular 2 typescript. Below is the code snippet:

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

@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1><div class="chart" #chart></div>`,
})
export class AppComponent implements OnInit { 
 @ViewChild('chart') private chartContainer: ElementRef;
 @Input() private data: Array<any>;
 private margin: any = { top: 20, bottom: 20, left: 20, right: 20};
 private chart: any;
 private width: number;
 private height: number;
 private xScale: any;
 private yScale: any;
 private colors: any;
 private xAxis: any;
 private yAxis: any;  
 name = 'Angular';

ngOnInit() {
 this.generateData();
 this.createChart();
 if (this.data) {
     this.updateChart();
 }
}

Random data generation:

generateData() {
  this.data = [];
  for (let i = 0; i < (8 + Math.floor(Math.random() * 10)); i++) {
      this.data.push([
          `Index ${i}`,
          Math.floor(Math.random() * 100)
      ]);
  }
}

X and Y axis creation:

 createChart() {

   let element = this.chartContainer.nativeElement;
   let svg = d3.select(element).append('svg');

   svg.attr('width', element.offsetWidth)
   .attr('height', element.offsetHeight);

  this.width = this.chartContainer.nativeElement.offsetWidth - 
  this.margin.left - this.margin.right;
  this.height = this.chartContainer.nativeElement.offsetHeight - 
  this.margin.top - this.margin.bottom;

  // plot area settings
  this.chart = svg;

  // defining X & Y domains
  let xDomain = this.data.map(d => d[0]);
  let yDomain = [0, d3.max(this.data, (d: any) => {return d[1]})];

 // creating scales
 this.xScale = d3.scaleBand().padding(0.1).domain(xDomain).rangeRound([0, this.width]);
 this.yScale = d3.scaleLinear().domain(yDomain).range([this.height, 0]);

// bar color scale
 this.colors = d3.scaleLinear().domain([0, this.data.length]).range(<any[]>['red', 'blue']);

// setting up x & y axis
 this.xAxis = svg.append('g')
    .attr('class', 'axis axis-x')
    .attr('transform', `translate(${this.margin.left}, ${this.margin.top + this.height})`)
    .call(d3.axisBottom(this.xScale));
this.yAxis = svg.append('g')
    .attr('class', 'axis axis-y')
    .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
    .call(d3.axisLeft(this.yScale));
}

Adding plots to the graph:

    updateChart() {

        this.chart = this.chart.append('g')
        .attr('class', 'dots')
        .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);

        
        this.xScale.domain(this.data.map(d => d[0]));
        this.yScale.domain([0, d3.max(this.data, (d:any) => {return d[1]})]);
        this.colors.domain([0, this.data.length]);
        this.xAxis.transition().call(d3.axisBottom(this.xScale));
        this.yAxis.transition().call(d3.axisLeft(this.yScale));

        let update = this.chart.selectAll('.dot')
            .data(this.data);

        update.exit().remove();

        update
            .enter()
            .append('circle')
            .attr('class', 'dot')
            .attr('cx', (d : any) => {return this.xScale(d[0])})
            .attr('cy', (d:any) =>{return this.yScale(d[1])})
            .style('fill', (d:any, i:any) => { console.log(d); return this.colors(i)});
    }

If 'rect' elements are placed instead of 'circle' with specific dimensions, they appear correctly on the UI. There seems to be an issue with styling or missing elements for 'circle'. Looking for suggestions or fixes.

https://i.sstatic.net/c25Dg.png

Answer №1

Make sure to define the radii for the circles, as it will default to zero (or rather, null):

update.enter()
    .append('circle')
    .attr('class', 'dot')
    .attr("r", someValue)//specify the radius here
    .attr('cx', (d : any) => {return this.xScale(d[0])})
    .attr('cy', (d:any) =>{return this.yScale(d[1])})
    .style('fill', (d:any, i:any) => { console.log(d); return this.colors(i)});

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

Issue with event.preventDefault() in Jquery not functioning as expected

My goal is to have the menu display and hide list items on click, with them being hidden by default. However, the issue I am facing is that the menu is generated in the admin section, so it automatically assigns a URL to each item. If I set the URL field o ...

Switch between classes when hovering over / exiting ngFor elements

Displayed below is an element created using ngFor <span *ngFor="let picture of pictures; let i = index"> <a target="_blank" href="{{picture.image}}" class="thumbnail-display image-overlay"> <span class="overlay-icon hide"> ...

Modifying data types within complex nested object structures

I am looking to traverse the data structure recursively and create a custom type with specific fields changed to a different type based on a condition. Using the example structure below, I aim to generate a type (Result) where all instances of A are repla ...

Mastering the art of carousel div creation with Bootstrap

Is there a way to create a carousel in Bootstrap 3 where only one div slides at a time, instead of three? I attempted to use divs instead of images in the traditional carousel structure, but it's not functioning as expected. I'm looking for some ...

Regular Expressions: Strategies for ensuring a secure password that meets specific criteria

Struggling to craft a regex for Angular Validators pattern on a password field with specific criteria: Minimum of 2 uppercase letters Minimum of 2 digits At least 1 special character. Currently able to validate each requirement individually (1 uppercase ...

What is preventing me from retrieving a value from a member function or method within a TypeScript class instance?

I am facing an issue with the FileInfo class that implements the IFileInfo interface. This class has an instance member function ext and a function getExt(). Within my component, there is a private method named openTempFolder() which makes an HTTP call to ...

Issue with consistent search autocomplete feature in a stationary navigation bar using bootstrap technology

My issue is with the autocomplete box - I want it to have the same width as the entire search box. Something like this using Bootstrap's col-xs-11 class: https://i.sstatic.net/npzhC.png If I set the position to "relative," it looks like this (all st ...

Tips for avoiding a ligature occurrence in a specific location

I am a fan of ligatures in general, as they improve readability. I want to implement them across all my HTML pages. However, there is this one word Hanftierheft (which is German and a compound word made up of Hanf, Tier, and Heft). I specifically do not w ...

What is the best way to customize the style using a CSS class?

Is it possible to alter a specific style with a CSS class using jQuery or JavaScript? For example, if the HTML looks like this: <tab> <a class="anchor">a</a> </tab> And the CSS looks like this: a {border:1px} .anchor {color: ...

Using TypeScript to Import Modules without Default Exports (CommonJS)

Can a module that is defined without a default export be imported using import module from 'module'; and then compiled to commonjs? An answer on Stack Overflow suggests that it might be possible with the use of the --allowSyntheticDefaultImports ...

I am having trouble with my custom-button class not successfully overriding the btn background color property. Can anyone provide insight

Utilizing the bootstrap5 variant-button mixin, I aim to create a custom-colored button. While I have successfully altered the default hover effect color, I am encountering difficulty in setting the background color of the button itself. Upon inspecting the ...

Having trouble with routerLink in your custom library while using Angular 4?

In my Angular 4 project, I have developed a custom sidebar library and integrated it into the main project. My current issue is that I want to provide the option for users to "open in new tab/window" from the browser's context menu without having the ...

Expand by focusing solely on recognized attributes?

I am working on creating an interface that can accept a mapped type, allowing for both runtime logic and compile-time typing to be utilized. Here is an example of what I'm aiming for: type SomeType = { a: string b: { a: string, b: string } } magi ...

Adjust the size of H1, H2... tags based on their own specifications, rather than the surrounding element

I have run into a bit of a conundrum with my code and cannot seem to find the right solution. Here is what I currently have: <div id="bloquetexto4" class="bloquetexto"> <H2><b>TITULO</b></H2> <p>Texto bla bla bla.</p ...

Having trouble getting Owl Carousel to function properly within an AngularJS partial view?

I just started working on a single page application using AngularJs. Here is a snippet from my Index.html: <!DOCTYPE html> <html data-ng-app="myApp"> <head> <meta charset="utf-8> <meta name="viewport" content="width=devi ...

What method can be employed to eliminate choice selection lacking any value?

Currently, I am encountering difficulties in my attempt to remove or hide the first option value from a ransack code. Would you be able to assist me in addressing this concern? Here is the HTML CODE that I am working with: <select id="q_c_0_a_0_name" ...

Enhancing Security and Privacy of User Information with JWT Tokens and NgRx Integration in Angular Application

I'm facing a security concern with my Angular application. Currently, I store user details like isAdmin, isLoggedIn, email, and more in local storage. However, I'm worried about the risks of unauthorized updates to this data, especially since my ...

Is it necessary to list all potential strings for accessibilityRole?

When working with accessibilityRole in React Native, I am wondering if there is a way to import all the possible strings instead of typing them out manually. createAccessibilityRole(parent: Element): string { if(isLink) return 'link' return ...

Determine the height of a DIV element and its contents using JQuery

In this div, there are various elements present: <div class="menuItem designMenu" id="dMenu"> <ul class="menuList menu"> <li class="menuHeader">Design</li> <li class="projectHeader">Mother</li> <li clas ...

Transform the initial HTML table row into a header row for every table by utilizing XSLT

My XML file contains HTML content that I need to manipulate. Previously, I used <xsl:copy-of select="customFields/customField[@name='mainContent']/html"/> to bring the content to the correct location. Now, I have a new requirement to conver ...