Enhance your tooltip pie chart in echarts4r by incorporating additional variables

Currently, I am in the process of creating a doughnut chart with echarts4r. As I delve into adding a custom tooltip to enhance the user experience, I have successfully referenced examples from Stack Overflow on stacked area charts (Echarts4r : Create stacked area chart with percentage from total in tooltip) and extra variables in tooltips for echarts4r (Displaying extra variables in tooltips echarts4r). However, adapting these concepts to a pie chart is proving to be a bit challenging. My goal is to implement a pie chart that displays both the total values and their relative percentages in the tooltip.

library(tidyverse)
library(echarts4r)

My_df <- data.frame(n = c(1, 4, 10), 
                    x = c("A", "B", " C")) %>%
  mutate(percent = round(n/sum(n), 2) )

My_df %>%
  e_charts(x)  %>% 
  e_pie(n, radius = c("50%", "70%")) %>%
  e_tooltip()

Here's my progress so far:

My_df %>%
  e_charts(x)  %>% 
  e_pie(n, radius = c("50%", "70%")) %>%
  e_tooltip(formatter = htmlwidgets::JS("
                                        function(params){
                                        return('<strong>' + params.name + 
                                        '</strong><br />total: ' + params.value + 
                                        '<br />percent: ' +  params.value[1])   }  "))

While the scatterplot examples utilize bind = to include additional values, this approach doesn't seem to work smoothly with the pie chart.

Answer №1

Is it possible to utilize params.percent in this scenario?

My_df %>
  e_charts(x)  %> 
  e_pie(n, radius = c("50%", "70%")) %>%
  e_tooltip(formatter = htmlwidgets::JS("
                                        function(params){
                                        return('<strong>' + params.name + 
                                        '</strong><br />total: ' + params.value + 
                                        '<br />percent: ' +  params.percent)  +'%' }  "))

You might also simplify the code by incorporating Javascript template literals.

My_df %>
  e_charts(x)  %> 
  e_pie(n, radius = c("50%", "70%")) %>%
  e_tooltip(formatter = htmlwidgets::JS("
                                        function(params)
                                        {
                                            return `<strong>${params.name}</strong>
                                                    <br/>Total: ${params.value}
                                                    <br/>Percent: ${params.percent}%`
                                        }  "))

Answer №2

It seems that this solution is even more creative than the one provided by @WeihuangWong in Displaying extra variables in tooltips echarts4r

If you are only interested in showcasing the percentages, then following the method suggested by @norie would be the way to go. Nevertheless, my approach could come in handy if you wish to include values in the tooltip that are not pre-calculated by echarts.

  1. By implementing that technique, you can introduce a variable to your dataframe containing the series name and the additional values intended for display in the tooltip, referred to as name

  2. Substitute x with name within e_charts

  3. In e_tooltip, break down name into its components and configure your tooltip accordingly

  4. However, utilizing name causes both the name and percent value to appear as labels and in the legend. To address this, formatters need to be added for the labels and legend as well.

library(tidyverse)
library(echarts4r)

My_df <- data.frame(n = c(1, 4, 10), 
                    x = c("A", "B", " C")) %>%
  mutate(percent = round(n/sum(n), 2),
         name = paste(x, percent, sep = ","))

My_df %>%
  e_charts(name)  %>% 
  e_pie(n, radius = c("50%", "70%"), label = list(
    formatter = htmlwidgets::JS(
    "function(params){
      var vals = params.name.split(',')
      return(vals[0])}"))
  ) %>%
  e_legend(formatter = htmlwidgets::JS(
      "function(name){
      var vals = name.split(',')
      return(vals[0])}")) %>% 
  e_tooltip(formatter = htmlwidgets::JS("
                                        function(params){
                                        var vals = params.name.split(',')
                                        
                                        return('<strong>' + vals[0] + 
                                        '</strong><br />total: ' + params.value + 
                                        '<br />percent: ' +  vals[1])   }  "))

https://i.sstatic.net/w5CgY.png

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

When trying to apply styles using ng-style attribute with jQuery, Angular does not seem to

Check out this plunker showcasing the issue : http://plnkr.co/edit/1ceWH9o2WNVnUUoWE6Gm Take a look at the code : var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { console.log('yeah'); ...

Increasing numerical values within an array using JavaScript

My goal is to enhance the functionality of this visualization by being able to increase or decrease the nodes in the hidden layers. I have attempted to achieve this by adding the following code: I am facing difficulties in adjusting the number of hidden l ...

Error in typing on a prismic application utilizing a ContentRelationshipField

I am facing a type error in my Prismic Next.js application that I am struggling to resolve. While the app functions properly, I keep encountering type errors like the following: The property 'data' does not exist on the type 'ContentRelati ...

The jQuery fadeToggle function toggles the visibility of an element starting from hidden instead

I'm having an issue where text in my div only appears on the second click, instead of the first. What could be causing this problem? $('#fPaperCirclePic').on('click', function () { $('#fPaperCircleText, #isargebla, #moq10 ...

Capture the item selected from the dropdown using ng-model to retrieve the name instead of the

I need help getting the name/text/html of the selected option in a dropdown using angular.js, rather than just its value. Currently, I have this setup which retrieves the value: Here is my HTML code snippet <select class="SelectCar" ng-model="Selected ...

Guide on Validating and Updating an embedded item within a mongoDB Collection Document

How do I go about updating the values of an embedded object within a mongoDB document? The values displayed for {{service.id}} and {{service.username}} in the table template are correct. However, I am unsure of the correct way to access them within the sa ...

VSCode is experiencing issues with recognizing .env* files for markup purposes and is also failing to recognize .env.local.* files

Current Environment: Utilizing NextJs, React, and VsCode Noticing a problem with syntax highlighting in my VSCODE editor. I have installed the following extensions: ENV DotEnv As per suggestions, I updated my json configuration file as follows: " ...

`@keyup.enter event listener will only be triggered upon pressing the Enter key if the focus is on

My login button only seems to work when I press the tab button after entering my email and password. I would like it to work whenever I press the enter key while on the Login page of this VueJS application. This is the HTML template: <template> ...

The page is undergoing a refresh and the query will not be executed - Ajax and PHP working together

function submitComment(ele) { event.preventDefault(); var username = "<?php echo $current_user; ?>"; var user_id = "<?php echo $current_user_id; ?>"; var post_id = $(ele).data('id'); var comments = $(ele).parent(".comment-se ...

What steps can be taken to disable Angular's automatic trimming of fields?

Is there a global way to prevent Angular from automatically trimming input fields throughout the entire application? I know that I can avoid it for specific fields using the ngTrim directive, but it's not ideal to add this directive to every text fiel ...

Modify the indentation format in CSS/JS

When the Tab key is pressed in an HTML page and the tabbed link gets highlighted, is it feasible to customize the style of that highlight? ...

What is the best way to implement the Active list element feature in my menu bar?

The current list element is : <li class="nav__item"><a class="nav__link nav__link--active " href="#"... The standard list element is: <li class="nav__item"><a class="nav__link " href=&quo ...

Position the colored div on the left side of the page

Here is the CSS I am currently using... <style type="text/css"> .widediv{width:1366px;margin-left:auto;margin-right:auto} </style> This CSS code helps me create my webpage : <body><div class="widedivv"> <!-- Content go ...

How to locate and extract specific data from a webpage table using JavaScript and Node.js for web scraping and storing in an array of objects

Exploring the realm of web scraping by targeting a UFC betting site for data extraction. JavaScript, alongside request-promise and cheerio packages, is utilized in this endeavor. Site: The primary aim is to retrieve the fighters' names along with th ...

send JSON data to a Spring MVC endpoint

Here is the controller signature I have tried using @RequestBody: @RequestMapping(value = "/Lame", method = RequestMethod.POST) public @ResponseBody boolean getLame(@RequestParam String strToMatchA, @RequestParam String strToMatchB) {} This is the json I ...

The hamburger menu on the navigation bar only functions the first time it is clicked

I've encountered an issue with my hidden menu nav bar. The hamburger and close buttons only work once. Should I organize the events within a function and call it at the end, or perhaps use a loop for the button events? It's worth noting that I d ...

Retrieve the dimensions of an image once rendering is complete, using Angular

I'm currently working on obtaining the rendered size of an image within a component. By utilizing the (load) event, I can capture the size of the image as it appears at that particular moment (pic1), as well as its "final" size after the page has fini ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

Cancelling an ongoing AWS S3 upload with Angular 2/Javascript on button click

I'm currently working with Angular 2 and I have successfully implemented an S3 upload feature using the AWS S3 SDK in JavaScript. However, I am now facing a challenge: how can I cancel the upload if a user clicks on a button? I've attempted the ...

creating dynamic navigation tabs with scroll functionality

Utilizing Bootstrap Nav Tabs and Tab panes on my website has been a smooth process. However, I am encountering some difficulty in adding extra links that not only activate the Tab Panes but also scroll to them. The issue seems to be related to a specific l ...