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

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

Using Vue.js to sift through and refine data

I have retrieved data from an API and am displaying it here using VueJS. The user information is stored inside the users[] array, with two types of plans: basic_plan and standard_plan. Currently, all users are being shown. Now I want to apply filters simi ...

Modify the css based on the user's input

<html lang="en"> <head> <link rel="stylesheet" href="style.css" /> <li id="visa"> <section class="credit-card visa gr-visa"> <div class="logo">visa</div> <form> <h2>Payment ...

Making a switch from one image to another - JavaScript

I need a solution to swap out an image that is used in multiple locations on a webpage. Consider this sample HTML page: <html> <head> </head> <body> <img id="1" src="example.com/img/1889.png"> <d ...

Having some trouble getting @angular/cli to install properly on my Ubuntu system

After numerous attempts to install @angular/cli on Ubuntu terminal, I kept encountering the following error: **npm ERR! 404 Not Found: @angular/cli@latest**. Even though I had installed nodejs with nvm and set NVM_BIN path to /root/.nvm/versions/node/v9. ...

The Ajax Auto Complete function encounters an issue when attempting to assign a value to the TextBox

I have a Textbox that utilizes an Ajax Autocomplete function. The function is functioning correctly and retrieves values from the database, populating them in the TextBox as well. However, there is a button on the page that triggers a query, fetching som ...

Slide containing Ionic list views

In my Ionic app, I am using ion-slide-box with 3 slides. Each slide contains an ion-list (table view) with varying numbers of items. The issue is that when scrolling through the shorter list items, it shows empty content due to the taller sibling list taki ...

Is there a way for me to automatically update a webpage every 5 minutes, beginning at 8:01 a.m., and subsequently at 8:06 a.m., and so forth?

<html> <head>Harshal</head> <script> var limit="5:0" var doctitle = document.title var parselimit=limit.split(":") parselimit=parselimit[0]*60+parselimit[1]*1 function beginrefresh(){ if (parselimit==1) window.location.reload ...

Navigating through the Table using AngularJS

I was able to successfully loop through a table using AngularJS to retrieve values from a specified scope named {{rec}} as shown below. HTML <div id="AngularContainer" data-ng-app="myApp" data-ng-controller="myCtrl"> < ...

What's the reason behind the malfunction of this code on Chrome?

After recently installing Mobiscroll, I have been using the date scroller feature with the following code to manage the textbox. <script type="text/javascript"> $(function() { // create a datepicker with default settings $("#begi ...

Initiating and handling a POST request

In my node.js server, I have a simple setup like this: var express = require('express'); var app = express(); app.post('/savearticles', function (req, res) { res.send(req.body); }); Additionally, the javascript code is not very c ...

Issues with Angular toggle sorting functionality not functioning as expected

$scope.searchObject = { from: 0, hydrate: false, size: 12, sort: 'timestamp:desc' }; $scope.sort = function(a) { var ascend = a + ':' + 'asc'; var descend = a + ':' + 'desc'; if ($scope.searc ...

Is it possible to apply styles to javascript elements without relying on img class? Additionally, how can I incorporate an onclick button while maintaining a fully functional navigation bar?

My current project involves creating an interactive collage where users can click around and have pictures pop up at the clicked location. The functionality works as intended, but now I'm facing issues with the navigation bar not being clickable. Addi ...

Sending data from multiple HTML table rows at once to a Django model

After a user selects items from a list, they can submit the selected items to be saved in a table. The table is dynamically rendered using JavaScript and the data comes from a Map with keys as primary keys and values as descriptions and prices. function d ...

When TypeScript generator/yield is utilized in conjunction with Express, the retrieval of data would not

Trying to incorporate an ES6 generator into Express JS using TypeScript has been a bit of a challenge. After implementing the code snippet below, I noticed that the response does not get sent back as expected. I'm left wondering what could be missing: ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...

Managing dependencies and automating setup processes can be tricky when incorporating Typescript into a

Query: How can I easily set up Typescript with Symfony without making extensive changes to Symphony's configuration files? Here are the key requirements for the solution: Typescript MVC Pattern should be set up in a private typescript directory: ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

How can permissions for video and audio be configured in Next.js?

When the button is clicked, I want to set permissions. This is how I'd like the scenario to play out: first, the method works initially and allows permission when the button is pressed. Here is my code: <button onClick={requestPermission} classN ...

Utilizing Express-Partials in conjunction with a single layout to incorporate multiple partials

Recently, as I migrated to Node.js and ExpressJS 3.0, I noticed that partials were no longer supported. However, I stumbled upon express-partials which provided a similar feature. Upon exploring the example on their GitHub page, I came across this snippet ...