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

Error in Next.js: Trying to destructure an undefined object in useContext

While attempting to change the state of my cursor in a Next.js app using useContext, I encountered the following error: TypeError: Cannot destructure 'Object(...)(...)' as it is undefined. The goal is to update the state to isActive: true when h ...

Customizing React-Data-Grid styles using Material-UI in a React application

Imagine a scenario where we have a file containing themes: themes.js: import {createMuiTheme} from "@material-ui/core/styles"; export const myTheme = createMuiTheme({ palette: { text: { color: "#545F66", }, }, }); In ...

Hacking through external script injections into the browser

Curious about how certain software or programs are able to inject html,css,js into a web browser without the need for installing any extensions. Every time I open Chrome or Firefox, I'm bombarded with ads on popular sites like Google homepage, Faceboo ...

Executing two AJAX requests simultaneously with Django, AJAX, and jQuery in a single event

I believe I'm on the right track to getting this to work, but I could really use some assistance with the JQuery aspect. It seems that everything functions as expected after the second click onwards, but there is an issue with the functionality on the ...

Guide on parsing a JavaScript file and converting the default export module to JSON with Node.js

What I'm trying to accomplish in my Node.js project is reading a sample.js file with ES Module syntax and extracting the default export from it. sample.js import foo from "foo"; const bar = [ { name: "Homer", }, { n ...

The tooltip chart is not displaying all of its data

I create a dynamic tooltip with a custom chart inside of it. tooltip: { borderRadius: 15, borderWidth: 0, shadow: false, enabled: true, backgroundColor: 'none', useHTML: true, shared: true, formatter: function() { ...

Issue with nested views in Angular UI-Router not displaying properly

The issue I'm facing is that the template <h1>HELLO</h1> is not loading into the nested ui-view in analysis.client.view.html. However, the ui-view in the analysis.client.view.html file is being loaded successfully. I've tried naming t ...

Dynamic Binding of ng-model to DOM Element in AngularJS

I am facing a challenge with my web page where I need to dynamically attach ng-model attributes to some HTML elements that I don't have the ability to edit. What I want to achieve is to have AngularJS re-bind these attributes to the scope. You can fin ...

Learn how to create a stunning effect by combining two half images and revealing a full image upon hover with a smooth animation

I am struggling with implementing a specific feature using jQuery. I have designed a page hero with two sections (red and black): My goal is to have the black section expand over the red section when hovering, creating a full black box. I want the same ef ...

When the open button is clicked, the Div will toggle between open and closed states

Recently, some of my questions have not been well-received, which makes me feel a bit disheartened. It's important to remember to be kind when providing feedback. I've noticed that some people downvote without offering constructive criticism, whi ...

The issue with MaterialUI Select's set value is that it consistently falls outside the expected

I'm currently working on a MaterialUI Select component where I am dynamically handling the value parameter. However, I'm facing an issue where even though I set a valid value from the available options, it always shows as out of range. SelectInp ...

Why isn't the onChange function triggering in the input type text when the input is not manually typed in?

I am currently facing an issue with two text fields in my HTML form. Here is how they are set up: HTML : <input type="text" id="input1" onchange="doSomething();" disabled/> <input type="text" id="input2"/> JavaScript : function doSomething( ...

What are the reasons for the failure of parsing this specific Twitter JSON file using Angular $http, and how can I troubleshoot and resolve the issue

After finding a JSON example on the following website (located at the bottom): , I decided to save it to a file on my local system and attempt to retrieve it using Angular's $http service as shown below: To begin, I created a service: Services.Twitt ...

Update the style class of an <img> element using AJAX

My success with AJAX enables PHP execution upon image click. However, I seek a real-time visual representation without page reload. Thus, I aim to alter <img> tag classes on click. Presently, my image tag resembles something like <img title="< ...

Incorporating timed hover effects in React applications

Take a look at the codesandbox example I'm currently working on implementing a modal that appears after a delay when hovering over a specific div. However, I've encountered some challenges. For instance, if the timeout is set to 1000ms and you h ...

What is the mechanism behind property binding in Angular 2? Can you explain what is happening in this specific scenario?

Being a novice in the realm of Angular 2, I find myself grappling with doubts related to property binding. While this particular example seems to work fine, I can't help but wonder about what exactly goes on behind the scenes. Within my component vi ...

Develop a personalized conditional rendering directive in Vue.js

I am exploring how to create a custom Vue conditional directive. While I could simply use a global method and call it within a v-if, I prefer the idea of having a dedicated directive for clarity in my code. My objective is to apply this directive to an el ...

Why does Vuetify/Javascript keep throwing a ReferenceError stating that the variable is undefined?

I'm currently developing in Vuetify and I want to incorporate a javascript client for Prometheus to fetch data for my application. You can find the page Here. Despite following their example, I keep encountering a ReferenceError: Prometheus is not def ...

What could be causing the issue with my dynamic sitemap.xml file not functioning properly?

I have encountered an issue with creating a dynamic sitemap in my Next.js app. Despite following the instructions in the Next.js documentation and placing a sitemap.js file inside my app directory, I am seeing a 404 error when trying to access http://local ...

What is the process for obtaining the final element in an array of objects when a particular character is present in the value of a key?

Given the following array: arrOfOranges = [{ "kerp": "thisThing", "time": "@ rocks 3"}, { "kerp": "otherThing", "green": "blah"}, { "kerp": "thisThing", "time": "(countriesToTheStart ^"}, { "kerp": "anotherThing", "yellow": "row row"}, { "kerp": "anotherTh ...