Unable to specify d3 axis to exclusively display whole numbers

After reviewing a few answers on this, I found that they are not solving my issue.

  1. how-to-limit-d3-svg-axis-to-integer-labels
  2. d3-tick-marks-on-integers-only

My problem centers around an array of years:

years: Array<number> = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017];
let minXAxis = Math.min(...this.years);
let maxXAxis = Math.max(...this.years);

this.xScale = d3.scaleLinear().range([this.margins.left, this.width - this.margins.right]).domain([minXAxis, maxXAxis]);

this.xAxis = svg.append("g")
  .attr("class", "axis axis-x")
  .attr("transform", `translate(0, ${this.height - this.margins.bottom})`)
  .call(d3.axisBottom(this.xScale));

However, with this approach, I encounter the following result.

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

Upon adding .tickFormat(d3.format("d")) as shown below:

this.xAxis = svg.append("g")
  .attr("class", "axis axis-x")
  .attr("transform", `translate(0, ${this.height - this.margins.bottom})`)
  // set to only display ticks for digits
  .call(d3.axisBottom(this.xScale).tickFormat(d3.format("d")));

I end up with the following outcome:

https://i.sstatic.net/9ydYG.png

Although the decimal is removed, the x-axis still displays repeated values such as 2011, 2011, ...

Is there a solution to ensure that the x-axis only shows: 2010, 2011, 2012, ...?

Answer №1

Don't be fooled by appearances - the values on that axis may seem identical, but in reality, there are no duplicates, just truncated decimals.

Your mistake lies in the choice of scale for this task. Consider using a time scale or, if treating the years as qualitative variables, opt for an ordinal scale like d3.scalePoint.

Remember, a year is not a standard number; while 2012 is clear, what does 2012.2412223 represent? A linear scale reduces years to mere numbers, lacking their true essence.

To resolve this, replace the linear scale with a time scale or an ordinal scale.

However, if you insist on using a linear scale and treating years as numbers (despite their nature), utilize tickValues to ensure only values in the years array are displayed on the axis:

d3.axisBottom(this.xScale)
    .tickValues(years)

Check out this demonstration:

var years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017];
var svg = d3.select("svg");
var scale = d3.scaleLinear()
  .domain(d3.extent(years))
  .range([20, 480]);
var axis = d3.axisBottom(scale)
  .tickValues(years)
  .tickFormat(d3.format("d"));
var gX = svg.append("g")
  .attr("transform", "translate(0,50)");
axis(gX);
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="100"></svg>

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

Am I effectively implementing async await in TypeScript?

I'm not quite sure if I'm using the async/await functionality correctly in my TypeScript and Protractor code. Looking at the code snippet below, the spec uses await to call the page object, which itself is an async/await function. The page object ...

Utilizing Redux with React class components: A comprehensive guide

I have been attempting to integrate Redux with React Class using TypeScript, following the guidelines provided in this tutorial. However, I am encountering numerous compilation errors and feeling overwhelmed as to where to begin troubleshooting. It is cl ...

Unable to add personalized repository

Looking to implement a request-scoped cache for my repositories, inspired by Hibernate's first-level-cache. I have some ideas on how to achieve this and integrate it with typeorm-transactional-cls-hooked. For now, I've created a basic provider s ...

Construct an outdated angular project from scratch

I'm facing an issue with an old Angular project that I'm trying to build. After pulling down the code, running npm install @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9f9095bccdd2cbd2c8">[email p ...

Developing an asynchronous function to retrieve data from an external API utilizing Await/Async strategy

Currently, there is a method under development that retrieves a value from the API. What steps are needed to properly integrate Async/Await functionality into this process? fetchAccountById(){ let accountName; this.accountService.fetchDa ...

Using Node.js: Only bring in the necessary function, don't execute the entire file

Today, I stumbled upon an interesting observation and I'm curious about the peculiar behavior of node in this scenario. I have two files structured as follows: src/api/index-api.ts src/worker/index-worker.ts Both of these files contain a simple con ...

Having trouble getting tsserver-plugins to function properly in either Atom or VSC

My team and I are on a mission to enhance our Angular 2 templates with code completion, similar to what is showcased in this gif. To achieve this goal, we require: tsserver-plugins coupled with tslint-language-service and @angular/language-service We ...

Retrieving routing information from directives within angular2

const APP_ROUTES: RouterConfig = [ { path: 'app/home', component: HomeComponent, data: { name: 'Home' } } ] Assuming the route configuration is set as displayed above, how can one ...

Issue with border radius in MUI 5 affecting table body and footer elements

Currently, I am diving into a new project utilizing React version 18.2 and MUI 5.10.3 library. My main task involves designing a table with specific styles within one of the components. The table header should not display any border lines. The table body ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

The limitations of Typescript when using redux connect

Recently, I utilized TypeScript for React to declare a class with constraints and now I'm looking to implement the connect method. Here is the code snippet: import * as React from 'react'; import { connect } from 'react-redux'; im ...

Learn how to set up browser targeting using differential loading in Angular 10, specifically for es2016 or newer versions

Seeking advice on JS target output for compiled Angular when utilizing differential loading. By default, Angular compiles TypeScript down to ES5 and ES2015, with browsers using either depending on their capabilities. In order to stay current, I've b ...

Having trouble with Ionic 4 navigation not triggering after a single click, requiring multiple clicks to navigate

I have a long list of items, around 40 in total, that load a page describing each item with photos, URLs, and other content. However, I find that I need to click two to three times before reaching this page. I suspect that the excessive use of HTML compone ...

What is the reason behind the never return value in this typescript template?

As demonstrated in this example using TypeScript: Access TypeScript Playground type FirstOrSecond<condition, T1, T2> = condition extends never ? T1 : T2 type foo = never extends never ? () => 'hi' : (arg1: never) => 'hi' ...

The enigma of TypeScript

Whenever I try to declare or initialize data members in a class, the following methods never seem to work: var view: string[]; var view: string[] = []; let view: string[]; let view: string[] = []; Even though the TypeScript documentation states that it s ...

How can we ensure file uploads are validated when using class-validator?

Recently, I've been utilizing the wonderful class-validator package to validate data. One specific validation task I'm working on is validating a file upload, ensuring that the file is not empty and ideally confirming that it is an image file. H ...

I am struggling to figure out why NativeWind props are not being recognized in my tsx file

Can someone help me understand why I can call className in jsx files but not tsx files? The error message displayed is: No overload matches this call. Overload 1 of 2, '(props: ViewProps): View', gave the following error. Type '{ children: ...

Executing installed packages using npm: A step-by-step guide

Recently, I have encountered a confusing issue in my coding journey. In Python, I got used to installing packages and using them right away without any hiccups. For example, with SpotDL, everything worked seamlessly. However, things took a different turn w ...

When attempting to access the id-data, an error is thrown indicating that the property 'username' of null cannot be read

Is there a way to transfer a user's data to their profile? I have successfully retrieved the complete user information from the API and displayed it on the user's page. However, I encounter an error when attempting to display the same data on the ...

Can we leverage Angular service styles in scss?

I am working on a change-color.service.ts file that contains the following code snippet: public defaultStyles = { firstDesignBackgroundColor: '#a31329', firstDesignFontColor: '#ffffff', secondDesignBackgroundColor: '#d1 ...