Display chart labels are constantly visible in Vue Chart JS

In my Vue.js JavaScript application, I am working on setting up a chart where I want the labels and chart information to be visible at all times without requiring mouse hover.

Check out this image of the chart.

This is the code snippet for my chart:

<template>
  <Pie :data="ameacas.chartData" :options="ameacas.chartOptions" style="width: 300px; height: 300px;" />
</template>

<script lang="ts">
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'
import { Pie } from 'vue-chartjs'

ChartJS.register(ArcElement, Tooltip, Legend)

export default {
  name: 'TdPie',
  components: {
    Pie
  },
  props: {
    threats: {
      type: Array,
      required: true
    }
  },
  computed: {
    ameacas: function () {
      return {
        chartData: {
          labels: ['High', 'Medium', 'Low'],
          datasets: [
            {
              backgroundColor: ['#CC092F', '#DD3820', '#FCBA03'],
              data: [this.getHighThreat, this.getMediumThreat, this.getLowThreat]
            }
          ]
        },
        chartOptions: {
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    getHighThreat: function () {
      return this.threats
        .filter(threat => threat.severity && threat.severity.toLowerCase() == 'high')
        .length;
    },
    getMediumThreat: function () {
      return this.threats
        .filter(threat => threat.severity && threat.severity.toLowerCase() == 'medium')
        .length;
    },
    getLowThreat: function () {
      return this.threats
        .filter(threat => threat.severity && threat.severity.toLowerCase() == 'low')
        .length;
    }
  }
}
</script>

I have already explored solutions like the one shared in this source and other resources within the community.

Answer №1

After setting up the "chartjs-plugin-datalabels", my code looked like this:

<template>
  <Pie :data="ameacas.chartData" :options="ameacas.chartOptions" style="width: 300px; height: 300px;" />
</template>

<script lang="ts">
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'
import { Pie } from 'vue-chartjs'
import ChartDataLabels from 'chartjs-plugin-datalabels';

ChartJS.register(ArcElement, Tooltip, Legend)
ChartJS.register(ChartDataLabels);

export default {
  name: 'TdPie',
  components: {
    Pie
  },
  props: {
    threats: {
      type: Array,
      required: true
    }
  },
  computed: {
    ameacas: function () {
      return {
        chartData: {
          labels: ['High', 'Medium', 'Low'],
          datasets: [
            {
              backgroundColor: ['#CC092F', '#DD3820', '#FCBA03'],
              data: [this.getHighThreat, this.getMediumThreat, this.getLowThreat]
            }
          ]
        },
        chartOptions: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            datalabels: {
              backgroundColor: function (context) {
                return context.dataset.backgroundColor;
              },
              borderColor: 'white',
              borderRadius: 25,
              borderWidth: 2,
              color: 'white',
              padding: 6,
              formatter: Math.round
            }
          }
        }
      }
    },
    getHighThreat: function () {
      return this.threats
        .filter(threat => threat.severity && threat.severity.toLowerCase() == 'high')
        .length;
    },
    getMediumThreat: function () {
      return this.threats
        .filter(threat => threat.severity && threat.severity.toLowerCase() == 'medium')
        .length;
    },
    getLowThreat: function () {
      return this.threats
        .filter(threat => threat.severity && threat.severity.toLowerCase() == 'low')
        .length;
    }
  }
}
</script>

This is what the outcome looked like:

View the updated chart image here

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

Setting the Vuetify drawer menu to be permanent on computer devices and non-permanent on mobile devices can be done by using conditional logic in your code

Can anyone assist me in making my drawer menu permanently displayed depending on the user's device? I was considering using the Vuetify grid system to determine whether I'm in LG, MD, or SM, but I'm not sure how to implement it. This is the ...

What is the best way to use AJAX to send a downloadable file in WordPress?

Currently working on developing a WordPress plugin and could use some assistance ...

Tips for retrieving data from multiple text boxes in a loop in React js and transmitting it to an API

I am in the process of developing a quiz application where I aim to create multiple question input fields based on the administrator's inputs. For example, if the admin provides 10 questions for the quiz, I will then generate a form within a loop fo ...

Guide on how to navigate users to a new page using react-router-dom v6 within a class-based component

I am facing an issue where I need to redirect the user to '/dashboard' after logging in, but I do not want to use history.push() from react-router-dom v5.2.0 as I have react-router-dom v6 installed. Is there another alternative to achieve this re ...

Initiate data extraction immediately upon the DOM being fully loaded using NightmareJS

Currently, I am utilizing nightmarejs and facing a challenge that I am struggling to resolve. After using the goto(URL) command, I then proceed to use the evaluate() command to execute specific operations on the webpage. However, I have noticed that while ...

Angular Controller encounters issue with event handler functionality ceasing

One of my Angular controllers has the following line. The event handler works when the initial page loads, but it stops working when navigating to a different item with the same controller and template. document.getElementById('item-details-v ...

Custom div element obstructs information window on map due to lack of auto panning feature

I created a unique div that is absolutely positioned on a Google Map. You can view the image below to see it. My issue is that the info window is being covered by this custom div element, as demonstrated in the picture. https://i.stack.imgur.com/1TgyQ.jpg ...

What is the method to permanently install and enforce the latest version using npm?

We are implementing a private npm module for exclusive use within our organization. Given that the module is managed internally, we have confidence in version updates and changes. Is there a way to seamlessly install this module across multiple projects s ...

Inquiries for Web-Based Applications

As I contemplate coding my very first webapp, I must admit that my skills are somewhere between beginner and intermediate in html, css, js, jquery, node, sql, and mongodb. However, the challenge lies in not knowing how to bring my vision to life. My ulti ...

Update the ajax request from jquery to axios and configure the xhrFields

Can someone help me convert my jQuery request to axios? $.ajax({ type: "GET", url: "http://6232423.212342343.100.89:9000/api/v2/content/categories/", xhrFields: { withCredentials: true }, }); I attempted to do it like this: axios ...

What is the source of this error message "Exceeding maximum characters in string literal"?

Hey everyone! Sorry for the bother, but I'm a bit stumped on this issue. Within my view, I have the following code snippet: <fieldset> <dl> <dt> <label for="FormTypes">Form Type:</label> ...

Unable to trigger AJAX Complete Handler

Upon completing extensive backend work on my web application, I discovered that the GetMeasure Request was taking up to 10 seconds to finalize. To prevent confusion for potential users, I decided to implement an overlay so that they would not be left stari ...

Using the Google Chrome console, execute a command on each page within a specified website

While browsing a website, I noticed a bug that required me to manually run a JavaScript function each time I navigated to a different page in order for the site to work smoothly. Is there a way to automate this process upon page load? I am using Google C ...

Is there a way to retrieve the hand-drawn lines at no cost in the form of a list, with each line represented as a collection of coordinates

I am currently contemplating the idea of utilizing fabric.js for an online handwriting recognition system. In order to make this system work, I need to transmit the sketched lines as a collection of lines, where each line consists of several points. If a ...

What steps do I need to take to share my Node JS application on my local area network (

I have a Node.js application running on my Ubuntu machine successfully, as I can access it through localhost:8080. However, other machines on the network are unable to reach it. CODE: const portNumber = 8080 let app = express() app.use(express.static(__d ...

Establishing global date restrictions for the DatePicker component in Angular 8 using TypeScript across the entire application

I am currently learning Angular 8 and I am looking to globally set the minimum and maximum dates for a datepicker in my application. I would like to accomplish this by using format-datepicker.ts. Any suggestions on how I can achieve this? Min date: Jan 1, ...

Click the 'expand' button for additional details on every row in the table

I am facing a challenge with my HTML table where I have a lot of information to add for each row. However, displaying everything at once makes the page look cluttered. Therefore, I am looking to add a "view more" button in another column for each row. Des ...

Creating a visually striking layout with Bootstrap card columns masonry effect by seamlessly adjusting card heights to prevent any

When using the bootstrap card columns masonry and a user clicks on a button inside a card, the height of the card changes dynamically by adding a card-footer. However, in certain situations, the cards change position causing a jumpy effect. To see this i ...

The v-img component is unable to find the resource within the assets directory

Having some trouble getting a static image to display properly using the v-img Vuetify component. The image is located at src/assets/images/logo.png. <v-img src="@/assets/images/rima_logo.png"></v-img> When attempting to load t ...

What content appears post-iframe?

After researching for a while, I've only come across information about text displayed after a broken iframe on this topic. However, what I actually want to do is display text below an iframe set at 90% height, like so: https://i.sstatic.net/KHXI3.png ...