Display images on a single dataset using Chart.js

How can I create a doughnut chart with 2 datasets where only one of them displays images? I managed to render both datasets and add images using chartjs-plugin-labels, but it applies the images to both datasets. Is there a way to specify which dataset should have the images?

https://i.sstatic.net/9FZYN.png

var config = {
  type: 'doughnut',
  data: {
    datasets: [
     /* Outer doughnut data starts*/
    {
      data: [
        10,
        20,
        30
      ],
      backgroundColor: [
        "rgb(255, 0, 0)", // red
        "rgb(0, 255, 0)", // green
        "rgb(0, 0, 255)", //blue
      ],
      label: 'Doughnut 1'
    },
    /* Outer doughnut data ends*/
    /* Inner doughnut data starts*/
    {
      data: [
        45,
        25,
        11
      ],
      backgroundColor: [
        "rgb(255, 0, 0)", // red
        "rgb(0, 255, 0)", // green
        "rgb(0, 0, 255)", //blue
      ],
      label: 'Doughnut 2'
    }
    /* Inner doughnut data ends*/
    ],
    labels: [
      "Info 1",
      "Info 2",
      "Info 3"
    ]
  },
  options: {
    responsive: true,
    legend: {
      position: 'top',
    },
    plugins: {
      labels: {
        render: 'image',
        images: [
          null, 
          null, 
          {
            src: 'https://i.sstatic.net/9EMtU.png',
            width: 20,
            height: 20
          }
        ]
      }
    },
    title: {
      display: true,
      text: 'Chart.js Doughnut Chart'
    },
    animation: {
      animateScale: true,
      animateRotate: true
    },
    tooltips: {
      callbacks: {
        label: function(item, data) {
        console.log(data.labels, item);
            return data.datasets[item.datasetIndex].label+ ": "+ data.labels[item.index]+ ": "+ data.datasets[item.datasetIndex].data[item.index];
        }
    }
}
  }
};
window.onload = function() {
  var ctx = document.getElementById("myChart")
    .getContext("2d");
  window.myDoughnut = new Chart(ctx, config);
};
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script>
  <script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
</head>

<body>
  <canvas id="myChart"></canvas>
</body>

</html>

Answer №1

According to the official documentation, you have the option to customize labels by using the following code snippet:

labels: {
  render: function (args) {
    // { label: 'Label', value: 123, percentage: 50, index: 0, dataset: {...} }
    // index - datasetIndex
    if (args.index == 1) {
       return { src: 'url', width: 25, height: 25 };
    }

    return undefined;
  },
},

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

Integrate, Delay, Experimentalize, and Attach components

This inquiry might lean more towards a general browser/javascript discussion rather than a focused prototype question, but I believe this community possesses a deep understanding of javascript and browsers. With that said, here is my query: If the followi ...

Exploring the world of unit testing in a store - any tips on getting it to work

I am currently working on a store.js file import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export const mutations = { increment: state => state.count++, Changeloading(state, status) { state.loading = status }, Cha ...

Converting a Perl hash into a JavaScript hash: A comprehensive guide

I am currently using the template toolkit framework and working with a Perl hash data type in my tt file. My goal is to convert this Perl hash data type into a JavaScript hash data type. Code: template: [% PERL %] use JSON qw(encode_json) ...

Change the content inside a div depending on the value of a button

I am currently exploring how to change the content of a div based on button values, utilizing angular2+. Below is my implementation in HTML and js export class TestComponent implements OnInit { title:string = "provas"; constructor() { } popula ...

Skipping certain key-value pairs during the conversion from JSON to Excel Worksheet using the XLSX library in JavaScript

I have a set of objects in JSON format within my JavaScript code and I am looking to transform this data into an Excel worksheet. Within the JSON structure, there are certain key-value pairs that I do not wish to include in the Excel output. For instance, ...

What is the method for incorporating choices into a schema field in Mongoose?

If my Schema is like this: var fooSchema = new Schema({ foo: String }); and I'm looking to implement select: false for foo, how can I achieve this without altering the initial structure? var fooSchema = new Schema({ foo: { type: String, select: ...

CSS and Javascript functioning correctly within internal server, but encountering issues when accessed externally

I am in the process of creating a website for a friend. The goal is to have a flashy animated style website that functions well on IOS and allows him to make changes easily. To achieve this, I am utilizing JQuery, my own javascript, and multiple css files. ...

The blinking cursor in Google Docs is known as "kix-cursor-caret."

Although I adore Google Docs, I can't help but find the blinking cursor a bit too distracting for my liking. It seems that the latest version of Google Docs fails to comply with the operating system's setting for displaying a solid, non-blinking ...

How can I ensure security measures are in place to avoid XSS attacks on user-generated HTML content?

Currently, I am in the process of developing a web application that will allow users to upload entire web pages onto my platform. My initial thought was to utilize HTML Purifier from http://htmlpurifier.org/, but I am hesitant because this tool alters the ...

Avoid opening the page when attempting to log in with jquery, ajax, and php

I am facing an issue with my code. I have a file named "index.html" which contains a login form. Another file called "dash.js" retrieves the username and password from the login form and redirects to "connectdb.php" to check the login credentials with the ...

Unable to display MongoDB collection in React application

I've been working on showcasing my projects using React and Meteor. I have two collections, Resolutions and Projects. The issue I'm facing is that while I can successfully display the Resolution collection on the frontend, I'm struggling to ...

Having Trouble with Click Function: Loading Pages into Div using Jquery/Ajax

Struggling to load content from other pages into a specific div by clicking on a URL link? Despite having previously executed the code successfully, it seems to redirect to the linked page instead of loading in the desired div. Even with an alarm set up as ...

The error message "gaq is not defined in opencart 2.0" indicates

While attempting to monitor transactions in OpenCart, I encountered the following error message: Uncaught ReferenceError: _gaq is not defined(anonymous function) This is the method I am using for tracking in my catalog/view/theme/default/template/commo ...

Is there a way to smoothly navigate back to the top within a Modal component while using React?

Here is the code snippet for scrolling back to the top of the page. const ScrollToTop = () => { const [showTopButton, setShowTopButton] = useState(false); useEffect(() => { window.addEventListener("scroll", () => { if ( ...

Utilize Javascript to refine JSON data strings

Currently, I am tackling a small project and facing a minor JS issue. The JSON string that I have looks like this: var jsObj = { "templates": { "form0": { "ID": "MyAlertNew", "isVisible": "true", ...

Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step: const args_arr = []; const options_arr = []; let options = ''; let text = ""; for (let i = 0; ...

Limiting Firebase queries with startAt and endAt

I need to retrieve the first 100 results from my Firebase data, followed by the next 100, and so on. Despite trying multiple methods, I have not been successful. Method 1 ref.child('products').orderByChild('domain').startAt(0).endAt(1 ...

"Ensuring that every" within handlebars js

I have been exploring handlebars.js (hbs) and although I haven't mastered it yet, I am curious to know if there is an equivalent to the following code: {{#if all source}} If not, how can I create a similar functionality using handlebars.js? ...

Troubleshooting the failure of the fetch function in my React application

Currently, I am delving into full-stack development with a focus on Js, React, and Express coupled with a Postgres database. The server is configured to run on localhost:5003, and the backend app.js file contains the following code: const express = require ...

Press the 'enter' button to post your tweet with Greasemonkey

I am working on a Greasemonkey script that will automatically submit a tweet when the user presses the 'enter' key. The script works perfectly on a basic HTML page with some help from tips I found on this website. However, when I attempt to use t ...