I tried to create an interactive bar chart with r plotly, where the height of bar is adjusting to a different value when hovering over it.
I have the following example dataframe:
df <- data.frame(para = c("Eve", "Cain", "Seth", "Enos", "Noam"),
valA = c(1,11,12,20,17),
valB =c(2,9,13,15,12))
And the following code creating the bar chart.
fig <- plot_ly(df, x= ~para, y=~valA, type="bar", customdata= ~valB)
The inital height of each bar is definedt by valA. When hovering for example over the bar for "Eve", it should change the height according to valB. and a horizontal line should appear on the height of the valA to allow comparison of both data.
I wasn't able to find an example providing an easy solution.
I found this article about adding event handlers.
So figured out, that I have to use the onRender-Funtion similar to the following.
But since I am not familiar with javascript, I get stuck.
onRender(
fig, "
function(el) {
el.on('plotly_hover', function(data) {
var pn = data.points[i].pointNumber;
for(var i=0; i < data.points.length; i++){
y = data.points[i].y;
};
y[pn] = ~varB;
var update = {'bar':{y: y}};
Plotly.restyle('myDiv', update);
});
}
")
Also it would be nice, if the bar of interest is changing the color upon hover.
I guess an plotly_unhover-Function is also missing.
I would apreciate it, if somebody could help or has an hint, how I could get near a solution.