Enhance your Vue app with filtered categories using Vue-google-chart

What is the process for creating a filter category in a bar chart using the vue-google-charts wrapper in Vue.js?

I have successfully created a stacked bar chart and now I am looking to add a filter by label inside the legend.

Here is my vue application:

https://codesandbox.io/embed/vue-dashboard-chart-6lvx4?fontsize=14&hidenavigation=1&theme=dark

Can someone guide me on how to achieve this using the Vue-google-charts wrapper?

Thank you and best regards, Dede

Answer №1

To easily filter chart data, you can utilize the chartEvents feature:

Vue.component("gchart", VueGoogleCharts.GChart);
new Vue({
  el: '#demo',
  data() {
    return {
      chartData: [
        ['Month', 'New', 'Verified', 'Regitered ID', 'On Playing', 'Finished', 'Active', 'Inactive'],
        ['January', 7, 4, 18, 15, 9, 10, 0],
        ['February', 16, 22, 23, 30, 16, 9, 8],
        ['March', 10, 2, 20, 13, 14, 21, 18]
      ],
      chartOptions: {
        chart: {
          title: "Player Performance"
        },
        legend: { position: 'top', maxLines: 3 },
        bar: { groupWidth: '75%' },
        isStacked: true,
      },
      chartEvents: {
        'click': (e) => {
          const numberPattern = /\d+/g;
          const idx = Number(e.targetID.match(numberPattern)[0])
          this.isFiltered ? this.allData() : this.filterChart(idx)
        }
      },
      newData: [],
      isFiltered: false
    };
  },
  methods: {
    filterChart(idx) {
      this.allData()
      for(let i = 0; i < this.newData.length; i++) {
        this.newData[i] = [this.newData[i][0], this.newData[i][idx + 1]]
      }
      this.isFiltered = true
    },
    allData() {
      this.newData = [...this.chartData]
      this.isFiltered = false
    },
  },
  mounted(){
    this.allData()
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e383b2b6329212129222b632d262f3c3a3d0e7e607d607c">[email protected]</a>/dist/vue-google-charts.browser.js"></script>
<div id="demo">
  <div id="app">
    <GChart type="ColumnChart" :data="newData" :options="chartOptions" :events="chartEvents" />
  </div>
</div>

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

Struggling to design a responsive layout as the div on the right keeps overlapping the div on the left

I recently built a React component that consists of two columns. In the left column, there's a calendar while the right column contains some text along with an input and select field. However, I noticed that when I resize the window, the elements on ...

Validating decimals in a text field with either JavaScript or jQuery

I need to implement text field validation on the keyup event. The text field should only accept money type decimals such as: (12.23) (.23) (0.26) (5.09) (6.00) If any incorrect value is entered, it should revert back to the previous value and remove the ...

Obtain GPS coordinates (latitude/longitude) from a Google map by dropping a marker on the

Is there a straightforward script that can load a Google Map and, when clicked, display a marker that saves the latitude and longitude values to a variable? Does anyone know if there is an existing PHP solution for this functionality? Appreciate any help ...

Sharing JSON data with public/javascripts/X.js in Node/Express: A beginner's guide

Currently facing a challenge with my Express project. Take a look at https://github.com/MoreeZ/help1 and examine ./public/javascripts/budget.js. My goal is to swap the incomeData object to read data from ./incomedata.json I attempted passing it through th ...

Establishing a restricted channel exclusive to a specific role for joining

I want to create a special channel where only members from the partyInvitees collection (Collection<Snowflake, GuildMember>) can join. const permission = Discord.Permissions.FLAGS; message.guild.createRole({ name: message.author.username + "&apos ...

What is the best way to utilize the existing MUI state in order to calculate and show column totals?

I am currently in the process of developing an MUI web application to keep track of some personal data. Within this application, I have incorporated the MUI datagrid pro component to efficiently display the data with its robust filtering capabilities. In ...

Is there a way to detect and handle errors triggered by a callback function?

My component has the following code snippet: this.loginService.login(this.user, () => { this.router.navigateByUrl('/'); }); Additionally, my service contains this method: login(credentials, callback) { co ...

javascript Arabic speech synthesis

Attempting to utilize SpeechSynthesisUtterance for Arabic language Successfully functioning with English content $(document).ready(function() { var u1 = new SpeechSynthesisUtterance('Hello world!'); u1.lang = 'en-US'; u1.pitch ...

Solution for fixing the error: MongooseError [OverwriteModelError]: It is not possible to overwrite the `User` model after it has been compiled in

I am new to working with the MERN stack and currently attempting to create an exercise tracker app following a tutorial on YouTube. However, I am encountering the Mongoose: OverwriteModelError when running the server and cannot seem to identify where I am ...

Multiple buttons in a single field

I am attempting to replace a Dropdown list with a series of buttons that will streamline the choices previously displayed by the dropdown list. Specifically, we are using graphic png files for the types of buttons. We experimented with checkboxing and ra ...

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

The AJAX request encountered an error while trying to send a POST request to the http://localhost/upload/undefined endpoint. The

I've been scouring the internet and testing for hours, but I'm still unable to identify the source of the error. I could really use some assistance here. I meticulously followed a tutorial on multiple file uploads with drag & drop functionali ...

Looking to alter the appearance of a div within an iframe by matching it with the title of the parent window using javascript?

I am currently working on a parent page titled Criatweb, which contains an iframe page. My goal is to modify the display of a specific div within the iframe page only when its title matches Criatweb. I attempted to implement the following script within t ...

Exploring the functionality of useRoute within a composable in Vue

I am working on a file store/service.js and I am trying to incorporate a router. This is what I have attempted so far: import { useRoute } from 'vue-router'; const router = useRoute(); function exceptionHandler(error) { if (error.response.sta ...

Mobile browser experiences video freezing when src is set through useState, yet it starts playing when triggered by a button click or when the video is set to M

Hey awesome folks at the StackOverflow Community, I'm currently encountering a perplexing issue with a video element in my web application. The video is supposed to play automatically on both desktop and mobile browsers. However, I've run into a ...

Finding elements in an array based on a specific string contained within a property

I am currently working on filtering JSON data to specifically search for job roles that begin with a particular string. The structure of the JSON is as follows : "periods": [ { "periodName": "Week1", "teamName": "Tango", ...

Error: Scheme is not a valid function call

Currently, I am attempting to implement user registration functionality in a Node.js application using MongoDB. However, I encountered this error: var UtenteSchema = Scheme({ TypeError: Scheme is not a function Below is my model utente.js: cons ...

Ways to avoid Parents Click Event from triggering during a Child's (Grandchild's) click event

My parent div has a unique feature where clicking on it reveals one of the child divs, and clicking again toggles the visibility of the child div. Inside this child div, there is a switch toggle that functions as a hidden checkbox. The issue I'm facin ...

Tips for handling promise coverage within functions during unit testing with Jest

How can I ensure coverage for the resolve and reject functions of a promise within a function while conducting unit tests using Jest? You can refer to the code snippet below. Service.js export const userLogin = data => { return AjaxService.post( ...

Utilizing Chart.js with Vue for dynamic time axis plots from JSON data through computed properties

Trying to generate a chart with a time axis in Vue using Chart.js has been a challenge. Initially, everything worked perfectly when the data was set directly in the Data object as shown below: chartData: { datasets: [ { backgroundC ...