Connect the plotly library to interact with the data in a Vue.js application through

I'm currently working on a project that involves using vue.js and the plot.ly JavaScript graph library. I am trying to figure out how to bind "pts" to the data's "TestSentences" in Vue. Below is my code snippet, thanks to everyone who has provided input. My objective is to develop an interactive dashboard that allows me to modify the data by clicking anywhere on the chart.

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<div id="app">
    <div id="grafik"></div>
</div>

<!-- Vue-->
<script>
    var app = new Vue({
        el: '#app',
        data: {
            TestSentences: "",
        },
        methods: {
            grafikCiz() {
                var trace1 = {
                    x: [1, 2, 3],
                    y: ["book", "pencil", "bag"],
                    mode: 'markers',
                    marker: {
                        color: ['#6886c5', '#f40552', '#1b1b2f'],
                        size: [10, 20, 30]
                    }
                };

                var data = [trace1];
                var layout = {
                    height: 400,
                    width: 400,
                };

                Plotly.newPlot('grafik', data, layout);
            },
        },
        mounted: function () {
            this.grafikCiz();
        },
    });
</script>
<!-- Vue -->

<script>
    var my_graph = document.getElementById('grafik');
    my_graph.on('plotly_click', function (data) {

        for (var i = 0; i < data.points.length; i++) {
            pts = 'x = ' + data.points[i].x + '\ny = ' + data.points[i].y + '\n\n';
        };

        alert('Closest point clicked:\n\n' + pts);

    });
</script>

Answer №1

Utilize the Plotly wrapper designed for Vue.js found at https://github.com/David-Desmaisons/vue-plotly

To enhance functionality, consider adding a reference to the component

<vue-plotly v-show="display" :data="graphData" :layout="calculatedLayoutSizes" id="3dPlot"
        :display-mode-bar="false" ref="crazyPlotly"></vue-plotly>

Then utilize this reference within your mount point or a similar method

this.$refs.crazyPlotly.$on('click', d => {
                                         console.log(d);
                                         });

The object "d" contains values like x and y datapoints, index, etc.

Reference: https://github.com/statnett/vue-plotly/issues/23

Answer №2

As mentioned by Alagappan A, utilizing https://github.com/David-Desmaisons/vue-plotly can simplify the process of working with plotly in javascript. In my experience, all it took was:

<vue-plotly :data="data" :layout="layout" @click="temp"> </vue-plotly>

This code can then be directly used within a method like this:

methods: {
  temp (value) {
    console.log(value)
  }
}
 

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

Optical Character Recognition (OCR) tool

Does anyone have recommendations for a JavaScript OCR API that can easily be accessed via JavaScript? I'm searching for an API similar to this: upload an image along with the desired result type (e.g. numbers, objects, text, mixed, etc) and receive t ...

Embedding a label's text directly as HTML code in an ASP.NET page

I attempted this CABC</td><td valign="top"><span class="progressBar pb3">document.getElementById('<%#Label8.ClientID%>').innerHTML</span></td></tr> I am trying to incorporate a jQuery script for a sales ...

Output of ngResource compilation

Is there a way to retrieve a single result from my array $scope.trailers? I am encountering an issue where accessing the first index using $scope.trailers[0] returns undefined. The API call is made using ngResource. function getTrailers(pageNo){ ...

Automatically updating quantity with the power of jQuery

I have created a spreadsheet where users can input their expenses and the total will update automatically. Initially, I have set some default numbers in my HTML which are editable for users to modify as needed. However, I am facing an issue with my JQuer ...

Jquery: Pressing Enter will cause the input field to lose

Take a look at this fiddle I created: http://jsfiddle.net/7wp9rs2s/. This is the progress I have made on my project so far. In the fiddle above, you can double click on one of the 4 items and a textbox will appear for editing. Instead of clicking out of t ...

Verify if data already exists in an HTML table column using JavaScript

As a beginner in web programming, I am currently trying to dynamically add data to a table. But before inserting the data into the table, my requirement is to first verify if the data already exists in a specific column, such as the name column. function ...

Encountered an unanticipated symbol at column 2 while using the Angular Google Recaptcha

I have integrated the Angular Google Recaptcha directive into my application from https://github.com/VividCortex/angular-recaptcha. However, upon running my application, I encountered an error stating that I am using my public key instead of my private key ...

What's the best way to capture an element screenshot using JavaScript?

I'm working on developing a unique gradient selection application. One of the exciting features I would like to incorporate is the ability for users to save their chosen gradients as digital images (.jpg format) directly onto their computers. When the ...

What is the most effective method for integrating JWT for API requests in Nuxt.js?

I am in the process of developing a frontend using nuxt.js and my primary data is obtained from an API. To handle Authorization, I have implemented JSON Web Tokens (JWT) and now I'm looking for the most effective method to inject the JWT into the Requ ...

The request's body in the PUT method is void

I seem to be having an issue with my PUT request. While all my other requests are functioning properly, the req.body appears to remain empty, causing this error message to occur: errmsg: "'$set' is empty. You must specify a field like so: ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

When a visitor accesses a webpage, enable port listening with Node.js and Express

Struggling to navigate the world of node.js, express, and port listening. My code is functioning properly, but only if I manually enter 'node index.js' in terminal to listen on port 3000... After hours of searching for a solution, my head is spi ...

Trigger video to play or pause with every click event

Looking to dynamically change the HTML5 video tag with each click of an li tag. Here is the current structure: <div class="flexslider"> <ul class="slides"> <li> <video> <source type="video/mp4" src="http://t ...

Adjust the width of a div within a nested iframe using jQuery without the need for an identifying ID on the iframe itself

Below is the code sample I'm working with: <iframe> <div id="inner_div"> Here's some text! </div> </iframe> I am aware that by adding an id to the iframe, I could follow the instructions provided here to access t ...

Vue 3 Composable console error: Unable to access properties of undefined (specifically 'isError') due to TypeError

I recently developed a Vue 3 / TypeScript Composable for uploading images to Firebase storage. The code snippet below illustrates the structure of the ImageUpload interface: interface ImageUpload { uploadTask?: UploadTask; downloadURL?: string; progr ...

Displaying queries using ajax in Rails

Can someone assist me in dealing with a particular issue? I am using ajax to refresh queries from the database dynamically each time there is a change in a search form. The main objective is to load N number of records based on the parameters selected in ...

Error when navigating to a dynamic parameter path using Angular Router

I'm trying to redirect a user to a path with a unique UUID when they go to the root URL (localhost:4200). However, I encountered the following error: ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'document/4fdb ...

Making changes to a JSON file using JavaScript

Hello everyone, I am a beginner in Javascript and have successfully created a system that allows me to search and filter users in my data.json file. However, I am now looking to develop an application that can add users to the data.json file. Any advice or ...

What is the best way to find all the corners along a path?

I am working with an SVG path and I need to find all the extremum points (corners) on this path. How can I achieve this? I attempted to retrieve all points using the following code: let totalLength = path.getTotalLength(); for (var i = 0; i < totalL ...

I'm having trouble with my Express server routes not being accessed. The browser is displaying an error message saying 'No Data Received ERR_EMPTY_RESPONSE

I've encountered an issue with my express server while setting up an email service. Despite troubleshooting and simplifying the code to a basic 'hello world' example, the problem persists. No routes are functioning properly – requests made ...