Reputation: 890
below is the code in the document of plotly.js dealing with click events
var myPlot = document.getElementById('myDiv'),
d3 = Plotly.d3,
N = 16,
x = d3.range(N),
y = d3.range(N).map( d3.random.normal() ),
data = [ { x:x, y:y, type:'scatter',
mode:'markers', marker:{size:16} } ],
layout = {
hovermode:'closest',
title:'Click on Points'
};
Plotly.newPlot('myDiv', data, layout);
myPlot.on('plotly_click', function(data){
var pts = '';
for(var i=0; i < data.points.length; i++){
pts = 'x = '+data.points[i].x +'\ny = '+
data.points[i].y.toPrecision(4) + '\n\n';
}
alert('Closest point clicked:\n\n'+pts);
});
via plotly_click
event, I can access the data through the point values x
and y
. but I want to get the other fields than these. Assume I change the above data in a suitable way for plotly.js
as
var N = 5,
x = d3.range(N),
y = d3.range(N).map( d3.random.normal() ),
text = d3.range(N).map( function() {return "hello";} ),
data = [ {x: x, y: y, text: text, type:"scatter", mode: "markers"} ];
in this case, is there a way to access text
attribute in plotly_click
event? basically I want to open new tab with url containing additional information (like text
field).
Additionally, I wander how to make data with hidden fields (other than text
) so that I use text
for tooltips when hover, and other field for the click event. Thanks in advance.
Upvotes: 2
Views: 2829
Reputation: 31659
You can access the data associated with your click event via d
from function(d)
.
The index of the clicked point can be retrieved via d.points[0].pointNumber
.
d.points[0].fullData
and d.points[0].data
contain your text as an array.
d.points[0].data
contains additional attributes (e.g. freetext
in the snippet below).
var myPlot = document.getElementById('myDiv');
var x = [0, 1, 2];
var y = [0, 1, 0];
var text = ['one', 'two', 'three'];
var freetext = ['One Is a Lonely Number', 'two is better than one', 'three is a lucky number'];
var data = [{x: x,
y: y,
text: text,
freetext: freetext,
type: 'scatter',
mode: 'markers',
marker: {size: 64}}];
Plotly.newPlot('myDiv', data);
myPlot.on('plotly_click', function (d) {
window.alert('Here is the text associated with your point:\n' + d.points[0].data.text[d.points[0].pointNumber] + '\n\nbut you can also get any other info as well:\n' + d.points[0].data.freetext[d.points[0].pointNumber]);
});
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id='myDiv'></div>
Upvotes: 2