Creating a dynamic label in Echart with multiple values: A step-by-step guide

How can I customize the legend in an Echarts doughnut chart to display additional content like shown in the image below?

Current Legend:

[

Desired Legend:

https://i.stack.imgur.com/ur0ri.png

Thank you,
Eric

Answer №1

When working with a pie chart, I made a customization to display the value after the name. Here is the snippet of code that achieved this:

 legend: {
  show: props.legend ? true : false,
  orient: 'horizontal',
  x: 'left',
  y: 'bottom',
  formatter: props.legendValue ? function (name) {
    let itemValue = data.filter(item => item.name === name)
    return `${name}: ${itemValue[0].value}`
} : "{name}",
  data: props.legend
}

Answer №2

Success!

  useEffect(() => {
    initializeChart()
    window.addEventListener('resize', () => myChart.current.resize())

    axios.get('api/xxx/xxx').then(res => {
      myChart.current.setOption({
        legend: {
          formatter: function (name) {
            const _data = res.data.groups
            const _value = _data.filter(item => item.name === name)[0].value
            return `${name}  -  ${_value}`
          }
        },
        series: [{
          data: res.data.groups
        }]
      })
    })

    return () => window.removeEventListener('resize', () => myChart.current.resize())
  })

Answer №3

if you're looking for increased space, consider using the series.center option, for more information

The center position of a Pie chart is defined by two values, where the first represents the horizontal position and the second represents the vertical position.

Percentage values are supported. When set as a percentage, the value is relative to the container width for the first item and the height for the second item.

Take a look at this demonstration:

let echartsObj = echarts.init(document.querySelector('#canvas'));
 
option = {
    color:['#429eda', '#8490ca', '#e97f74', '#f8d368', '#93cb76'],
    legend: {
        orient: 'vertical',
        x: 'right',
        y: 'center',
        data:['America','Canada','Japan','Mexico','India']
    },
    series: [
        {
 
            type:'pie',
            radius: ['50%', '70%'],
            startAngle: 170,
            center: ['30%', '50%'],
            label: {
                normal: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    show: true,
                    textStyle: {
                        fontSize: '30',
                        fontWeight: 'bold'
                    }
                }
            },
            labelLine: {
                normal: {
                    show: false
                }
            },
            data:[
                {value:835, name:'America'},
                {value:310, name:'Canada'},
                {value:314, name:'Japan'},
                {value:135, name:'Mexico'},
                {value:948, name:'India'}
            ]
        }
    ]
};


    echartsObj.setOption(option)
<html>
      <header>
        <script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts-en.min.js"></script>
      </header>
      <body>
        <div id="canvas" style="width: 100%; height: 300px">
        </div>
      </body>
    </html>

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

After completing a sequence, it does not reset

I'm working on creating a versatile "slideshow" feature that can be used for various elements. Currently, I am testing it on a div that contains paragraph text taken from my HTML document and represented as container1, container2, and container3. The ...

What is the correct way to assign a property to a function's scope?

Lately, I've been delving into Typescript Decorators to address a specific issue in my application. Using a JS bridge to communicate TS code between Android and iOS, we currently define functions as follows: index.js import foo from './bar' ...

Angular CDKScrollable not triggering events

I'm having trouble making the angular CdkScrollable work when creating my own div: <div class="main-section" id="mainsection" #mainsection CdkScrollable> <div class="content" style="height: 300px; backgr ...

What are the essential Angular 2 observables for me to utilize?

I have created a form input for conducting searches. Upon user input into the search bar, I want to trigger calls to two separate APIs simultaneously. Here is my current attempt: myInput: new FormControl(); listOne: Observable<string[]>; listTwo: Ob ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

methods for pausing music through a toggle button in a React JS application

I am facing an issue with the following shortcode for playing a song on a toggle button. The problem occurs when I try to pause the music and it does not stop as expected. import { React, useState } from 'react'; import './audio.css&apos ...

What is the reason for dirname not being a module attribute? (using the __ notation)

Currently, I am learning the fundamentals of Node.js. Based on the documentation, both __dirname and __filename are part of the module scope. As anticipated, when I use them like this: console.log(__dirname) console.log(__filename) They work correctly, d ...

Deploy a web application using JavaScript and HTML to Heroku platform

I noticed that when I visit the Heroku dashboard, there is an option to create an app using Node.js, but not JavaScript. This raises a question for me - if I want to upload my locally created JavaScript/HTML5 app to Heroku, do I need to select Node.js or ...

"Encountering a 403 error while using the request method in Node.js

app.post("/",function(req,res){ // console.log(req.body.crypto); request("https://apiv2.bitcoinaverage.com/indices/global/ticker/all?crypto=BTC&fiat=USD,EUR",function(error,response,body){ console.error('error:', error ...

Utilizing Stripe for Payment Processing

I'm encountering a problem with getting Stripe charging to function properly. Despite having manually loaded Composer since it wouldn't install, I am not receiving any PHP errors and the token creation is running smoothly. There don't seem t ...

Strange glitches and slow loading problems plaguing website. (GoDaddy)

TackEmporium.com Lately, I have been revamping my website, which was originally given to me by a friend. I have been making slight adjustments to update its appearance while keeping its classic look with enhanced resolution and cleaned-up HTML5 code. Rec ...

The "Key" function from Object.keys does not yield true when compared to an identical string

Object.keys(data).forEach((key) => { bannerData[key] = data[key][0]; console.log(key); if (key == "timestamp") { labels.push(data[key]); console.log("wtf"); console.log(labels); ...

Dynamically loading pages into a div with the power of AngularJS

I am attempting to dynamically load pages into a div using a select Here is my HTML code : <div ng-app="App" ng-controller="ProjectCtrl"> <div> <select ng-model="selectedType" class="form-control" ng-change="showContent()" ng-opt ...

Is there an issue with the proper execution of keypresses/updates in the code

I'm currently stuck while trying to develop a game in Javascript. My challenge lies in detecting keypresses and constantly checking if they are being held down to move the character. Below is the code I have been using: var THREE; var keys; var updat ...

Seamless changes with graceful fades while transitioning between classes

Is it more efficient to handle this in CSS than using jQuery? I'm not entirely sure. If anyone has a solution, that would be greatly appreciated. However, I am currently facing an issue with the jQuery method I have implemented. It successfully fades ...

ES6 Class Directive for Angular 1.4

I am currently exploring the possibility of incorporating a directive from version 1.4 and adapting it to resemble a 1.5 component. By utilizing bindToController and controllerAs, I aim to integrate the controller within my directive rather than using a se ...

Navigating with Angular: Understanding ng-view and Routing

How does Angular understand which template view to request containing the 'ng-view' element? If I directly navigate within my application to http://localhost/Categories/List/accessories , a request is still sent to '/' or the index ...

What could be the significance behind these sudden pop-ups of console error messages?

var sendTitle = function() { var title = $("input[name='movie-search-title']").val(); getMovie(title) getQuotes(title) } $("input[name='movie-search-title']").keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); ...

When attempting to parse a JSON feed with jQuery and innerHTML, the data fails to display

Having trouble parsing a JSON feed using jQuery and innerHTML, but for some reason it's not working as expected. No errors are being displayed in the console and the feed itself is functioning properly. Not quite sure why this issue is occurring. < ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...