1

I added a plotly component to my project following this guide. When the user clicks on the bar chart, I need to get the data corresponding to the bar that the user clicked on. The structure is just like in the guide I followed and everything works great, I just do not know how to add a click event to the bar chart. The bar chart looks like this enter image description here When the user clicks the chart, I need to get the associated vehicle make, like "HUMMER" for example.

2 Answers 2

1

After calling Plotly.newPlot, you can add a click event handler and access the clicked data like this

(document.getElementById('myPlotlyDiv') as any).on('plotly_click', function(data){
    // The label of the horizontal bar chart
    console.log(data.points[0].y);
    // The value for the clicked bar
    console.log(data.points[0].x);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Updated answer to ignore the typescript error Property 'on' does not exist on type "'myPlotlyDiv'", which I found at this SO question
0

The guide uses any type. However, your ESLint setup might give you some errors later on:

@typescript-eslint/no-unsafe-member-access: Unsafe member access .on on an `any` value.
@typescript-eslint/no-unsafe-call: Unsafe call of an `any` typed value.

Our days Plotly.js is definitely typed. So, you need to install as a developer dependence some types for plotly.js (e.g. npm i -D @types/plotly.js-dist-min) and use them:

import { PlotlyHTMLElement } from 'plotly.js-dist-min';
const myPlot = document.getElementById('myPlotlyDiv') as PlotlyHTMLElement;
myPlot.on('plotly_click', function(data){
    // The label of the horizontal bar chart
    console.log(data.points[0].y);
    // The value for the clicked bar
    console.log(data.points[0].x);
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.