Determine the mean values to showcase at the center of a D3 donut graph

Check out this plunkr where I'm utilizing angularjs and d3.js.

In the plunkr, I've created several donut charts. I'm interested in learning how to display the average data in the center of the arc instead of the percentage. Additionally, I'm curious about how to show labels on the arcs.

svg.append("text")
        .attr("dy", ".35em")
        .style("text-anchor", "middle")
        .attr("class", "inside")
        .text(function(d) { 
            return '56%'; 
        });

Answer №1

At the moment, the percentage displayed is hardcoded in the code. To replace this hardcoded percentage with the average of the data, you can substitute the 56% with the actual average.

You can achieve this by leveraging the array of data used for calculating each donut chart, which is conveniently accessible as data (initially named scope.data). Here's how you can show the average:

svg.append("text")
        .attr("dy", ".35em")
        .style("text-anchor", "middle")
        .attr("class", "inside")
        .text(function(d) { 
            return data.reduce(function(a, b) { return a + b; }) / data.length;
        });

Furthermore, as mentioned by Henry in the comments, a simpler approach would be to use d3.mean instead of the reduce function. Thus, you can replace the previous block with:

return d3.mean(data);

You can view the outcome on this Plunker.

Most browsers that support d3 should also support the ECMA5 reduce method showcased here. Yet, if you intend to utilize this with a d3 shim like r2d3 for IE8 compatibility, consider incorporating an Array.prototype.reduce polyfill, such as the one available from Mozilla.

Regarding the inquiry about labels, it's best to address it as a separate question. StackOverflow encourages one question per post. Once we conclude this discussion, feel free to post the label-related question, and I'll gladly assist.

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

Encountering obstacles with asynchronous requests while attempting to retrieve an Excel file using ajax

I am coding JavaScript for a SharePoint project, focusing on creating a function to retrieve data from an Excel document in a library. While I have successfully implemented the basic functionality, I am facing an issue with large file sizes causing the dat ...

Filter the specific output in a generator function

I have a code snippet that I need help with. function* iterateRecord() { const db = yield MongoClient.connect(''); const collection = db.collection(''); const query = {} const cursor = collection.find(query); ...

Having issues with the functionality of the Material UI checkbox component

Having issues with getting the basic checked/unchecked function to work in my react component using material UI checkbox components. Despite checking everything, it's still not functioning as expected. Can someone please assist? Here's the code s ...

Encountering difficulty in creating a Nuxt website using @googlemaps/js-api-loader

While using the @googlemaps/js-api-loader in my Nuxt 3 website, I encountered an issue. Everything worked perfectly during local development. However, when I attempted to build the project with nuxt generate (whether locally or on Vercel), I received the f ...

Sorting the Czech alphabet with the help of Tablesorter

Utilizing the tablesorter characterEquivalents extension as outlined in this documentation. I have created a similar extension for Czech characters, but the sorting is not functioning correctly for certain characters - like \u017d $.extend( $.tables ...

JSON nested error: Cannot read property 'length' of undefined

Having some trouble working with a nested array within a JSON in D3JS, specifically encountering a "property length undefined" error at the line: .attr("d", function(d) { return line(d.points); }). Below is the JSON data structure: [ { "aspectRatio" ...

Improving the Sum of Pairs solution on Codewars

Seeking assistance in optimizing a solution for a problem that has already been identified. However, the existing code is not efficient when dealing with large arrays - view the problem on codeWars : Sum of Pairs Below is the current code snippet: var s ...

Sending an event to a component that has been rendered in Vue

I'm currently in the process of developing a custom rendered component that will execute a function when clicked on: // Creating a standard Vue component with a render function Vue.component('greeting', { methods: { sayHello(){ ...

Apply a CSS class to the initial item in each carousel present on a webpage

I am utilizing Bootstrap 4's carousel to showcase dynamic content. The challenge lies in marking the first item of the carousel with the CSS class ".active". While it is typically added directly in the HTML, it becomes complicated when dealing with dy ...

How can I extract the id of a clicked item and pass it to a different page with Jquery?

Facing an issue where the attribute value of a clicked href tag is not retained after browser redirection. Initially, when clicking on the href tag, the value is displayed correctly. However, upon being redirected to the peoplegallery_album, the id becomes ...

Error: The function props.addToCart is not accessible

While attempting to trigger my action on the client's click of the "addToCart" button to add a new product to the cart, I encountered the error message: "TypeError: props.addToCart is not a function." I am relatively new to Redux and have grasped the ...

Uncovering the unique properties of custom Items in MUI v5 - RichTreeView: A Step-by-Step Guide

Can custom item properties received asynchronously with MUI - RichTreeView be exposed inside a custom treeItem? For instance, how can the customProperty1 and customProperty2 be accessed within the CustomTreeItem? The console.log to props only shows defaul ...

jquery disable document manipulation function

I need to make some updates to a simple function that involves the current textarea. $(document).on("keydown", updated_textarea_var, function (e) { // do stuff }); To achieve this, I tried disabling the previous function and running a new one w ...

div added on the fly not showing up

I'm attempting to dynamically add a div to a webpage using Chrome. Despite following several instructional guides, the code does not seem to be working as expected. I have added style attributes to make it more visible, but the element is not showing ...

Implementing conditional rendering using custom division return functions with onClick attribute on a submit button in React: A step-by-step guide

import React from "react"; class Input extends React.Component { constructor() { super(); this.state = { phone: "", weight: "", height: "", gender: "", smoke: "", lazy: "", bmi: "", pain: "", ...

The Distinction Between "Q" and "q" in AngularJS and RequireJS

Currently, my project involves developing a single page application using AngularJS, Breeze, and RequireJS. While trying to configure AMD with requirejs to integrate Angular and Breeze, I ran into an issue related to Breeze's dependency on "q". Intere ...

Accessing an external webpage within a React.js application while maintaining visibility of the navbar

Seeking assistance on how to open an external link within a React app below the navbar when navigating to "/WebSite". Currently using react router for page navigation. Here's the code snippet: const App = () => { return( <BrowserRouter&g ...

Transform JavaScript object into desired structure

let obj = { "rec": [{ "id": "25837", "contentId": "25838" }, { "id": "25839", "contentId": "25838" }, { "id": "25838" }, { "id": "25 ...

Error: Cannot iterate over Redux props map as it is not a function

I've encountered an issue while trying to render out a Redux state by mapping through an array of objects. Despite receiving the props successfully, I keep getting an error stating that 'map is not a function'. It seems like the mapping func ...

Updating a nested property within an array of objects in MongoDB

Storing grades for an online education application using MongoDB. Here is a sample classRoom document stored in my mongoDB database. StudentGradeObjs are kept in an array within a GradeObject. GradeObjs are stored in an array of GradeObjects inside a class ...