Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors?

I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges.

The data I have is { a: 50, b: 50, c: 50} and the corresponding colors are ['green','yellow','red']. In this scenario, the chart splits evenly and the colors are displayed correctly (starting with green and ending with red). Please refer to the attached image for clarity.

Correct Chart

However, when I input values as { a: 50, b: 30, c: 70}, the colors appear in a different order. It seems that the highest value (70) is being prioritized first as shown below.

Incorrect Chart

Sample Code:

 private theData = { a: 50, b: 30, c: 70};
 private svg:any;    
 private svgWidth = 200;
 private svgHeight = 125;  
 private colorRanges:any;
 private pie:any;
     
this.svg = d3
              .select('div#pie')
              .append('svg')
              .attr('width',this.svgWidth)
              .attr('height',this.svgHeight)
              .attr('id','pie-svg') 
              .append('g')
              .attr('class','ps')
              .attr(
                'transform',                
                'translate('+this.svgWidth/2+',115)');
      
  this.colorRanges = d3.scaleOrdinal().range(['green','yellow','red']); 

 this.pie = d3
.pie()
.startAngle(-90 * (Math.PI / 180))
.endAngle(90* (Math.PI / 180))
.value((d: any) => d[1]);

this.svg.selectAll('rect')  
.data(this.pie(Object.entries(this.theData)))
.join('path')
.attr('d',
d3.arc().innerRadius(75).outerRadius(35))
.attr('fill', (d:any) => this.colorRanges(d.data[0]))
.attr('stroke','none')
.style('stroke-width','1px')
.style('opacity',1);

Answer №1

To customize the arrangement of slices in a pie chart, you can define how they should be ordered:

d3.pie()
    .startAngle(-90 * (Math.PI / 180))
    .endAngle(90 * (Math.PI / 180))
    .value(d => d[1])
    .sort((a, b) => d3.ascending(a[0], b[0]))

In this example, the slice for "a" is placed first, followed by "b", and then "c".

Additionally, it's advisable to set a domain for your color scale instead of relying on the order from Object.entries():

d3.scaleOrdinal()
    .domain(['a', 'b', 'c'])
    .range(['green','yellow','red'])

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

Utilizing state in React for CRUD operations is a fundamental practice

Currently, I am developing a React application using altjs as my Flux implementation. I have encountered an issue where when attempting to create or delete an item from the front end, regardless of the parameter passed to the function, the entire state is ...

Exploring the realm of Typescript custom decorators: The significance behind context

I'm currently working on a custom decorator that will execute decorated functions based on RxJS events. Everything seems to be going well so far, but I'm facing an issue when the function is executed: the context of the this object is lost. I&a ...

Ways to troubleshoot NPM installation issues related to gyp ERR

I have tried most of the suggestions found online, but I am still encountering an error when trying to install opencv and serialport. My current setup includes Visual Studio 2019 with C++ Desktop environment and Python 3.7. npm ERR! command C:\Windows ...

Tips for specifying the type when utilizing the spread operator to pass props

type TypeData = { data: { id: string; class: string; name: string; country: string; ew_get_url: string; ew_post_url: string; rocket_id: string; pages: { landing: { h1: string; h2: string; } ...

TypeScript raises an issue with a Vue component property that has been defined using vue-property-decorator

I have a Vue component with a property defined using a decorator: import { Component, Vue } from "vue-property-decorator" @Component({ props: { myId: String, }, }) class TestProp extends Vue { myFuncti ...

Select all elements using jQuery that have an id attribute and belong to a specific class

I am attempting to select all items with an ID attribute that starts with a specified string while also having a particular class. For instance, consider the following: <div id="test-id-1" class="test"></div> <div id="test-id-2" class="test ...

Issue with data not refreshing when using router push in NextJS version 13

I have implemented a delete user button on my user page (route: /users/[username]) which triggers the delete user API's route. After making this call, I use router.push('/users') to navigate back to the users list page. However, I notice tha ...

Utilizing FullCalendar for showcasing comprehensive details

I'm a big fan of the fullcalendar plugin and all its amazing features. I want to enhance it by displaying more customized information for each event when in agendaWeek or agendaMonth view. Switching between views is easy, but I need help filtering out ...

When iterating through a JavaScript object, opt for utilizing references instead of repeatedly specifying the path

for (var element in array[index1][index2][index3].property) { alert(array[index1][index2][index3].property[element].data); } Is there a more succinct way to achieve the same result by referencing the object directly like this: for (var ...

After the transition from Angular 8 to Angular 9, an issue arose with the node_modules/@zerohouse/router-tab/zerohouse-router-tab.d.ts file, as it was not declared

Error Image package.json { "name": "client", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "serveapp": "ng serve ...

How come modifying the css of one component impacts all the other components?

Issue: I am struggling to make CSS changes only affect the specific component I want, without impacting other elements on the page. My goal is to style my dropdown menu without affecting other text input fields: Background/Challenge: While I understand wh ...

Updating Cart Array in Angular 4 when Adding a New Item

I'm currently using angular 4 and I have encountered an issue in the code where adding a new product to the cart overwrites the existing item instead of appending it to the array. Here is a screenshot illustrating the problem cart.service.ts export ...

Is it possible to utilize a JavaScript framework within a Chrome extension?

Currently, I am developing a chrome extension that adds a toolbar to the DOM dynamically. In order to find, attach, and manipulate elements, I have been using CSS selectors in JavaScript. However, this approach has proven to be fragile as any changes made ...

The Angular Material Table Collapse feature offers dynamic collapsing similar to jQuery Datatable

Is there a way to improve the appearance of my Angular Material Table, especially on mobile? https://i.stack.imgur.com/sZXPP.png The current display of my Angular Material Table is not aesthetically pleasing when viewed on mobile devices. https://i.stack ...

Mastering the art of looping through JSON values using AngularJS ng-repeat

Is there a way to use ng-repeat in order to iterate and access the name values: test01, test02, and test03 from my JSON data? Any guidance on how to achieve this using ng-repeat would be greatly appreciated. Thanks in advance! Check out this Fiddle link. ...

The error message "ReferenceError: window is not defined in Angular Universal" indicates

Currently, I'm utilizing Angular 10 and undergoing the process of incorporating SSR into my project. Upon executing the npm run serve:ssr, I encounter the following error: ReferenceError: window is not defined After conducting a search online, the r ...

Importing D3 data from CSV files using the "%" symbol

I am trying to import a CSV file with the following data: Month, Ratio January, 0.19% February, 0.19% March, 0.19% April, 0.18% The current code snippet I'm using is as follows: d3.csv("month_ct.csv", function(d) { return { month: d ...

What steps do I need to take to include React in my background.js script for a chrome

I'm currently facing an issue with my React code that I need to include in my background.js file. However, I encountered the following error message: SyntaxError: Cannot use import statement outside a module The specific import causing this error is: ...

Issues persist with AngularJS integration using Modernizr

Incorporating AngularJS and Modernizr, I aim to identify media queries and trigger a function whenever the window or viewport is resized. My goal is to control element visibility based on whether the user is on a desktop or mobile device - certain elements ...

Material-UI: The call stack has exceeded the maximum range, causing an Uncaught RangeError

I am currently utilizing the Dialog and Select components offered by Material-UI in conjunction with React. Here is a quick example: import React from 'react'; import { Dialog, MenuItem, Select } from '@material-ui/core'; class Examp ...