Reputation: 9773
I have a bar chart that shows the number of customers who waited a certain number of minutes. I would like a percentage in each category on hovering over the bar but can't work out how to do that.
Here is what I have so far.
var data = [{x: ['0-10', '11-20', '21-30', '31-45', '46-60', '61-120', '>120'],
y: [100, 55, 33, 28, 12, 11, 1],
name: 'Wait times',
type: 'bar',
hoverinfo: 'y'}]
var layout = {title: "Waiting Times",
xaxis: {title: 'Minutes'},
yaxis: {title: 'Number of customers'}}
Plotly.newPlot('mydiv', data, layout)
At the moment when I hover over the bar I get the value of the bar shown at the top of the bar. The behaviour I would like would be for the value of the bar to be shown with the percentage formatted to 1 decimal point after it in parentheses - e.g. 100 (41.7%) for the first data point.
I have tried various combinations of hoverinfo and hovermode settings but am having trouble understanding the documentation. Obviously I need an array of the percentages like this [41.66666666666667, 22.916666666666664, 13.750000000000002, 11.666666666666666, 5.0, 4.583333333333333, 0.4166666666666667]
but I don't know where to put this or how to format it.
Upvotes: 2
Views: 4758
Reputation: 1
You can customize hover text with customdata and a hovertemplate. Here is the how you do it:
var y = [100, 55, 33, 28, 12, 11, 1];
var data = [{
x: ['0-10', '11-20', '21-30', '31-45', '46-60', '61-120', '>120'],
y: y,
customdata:y.map((c)=>{return c=c/y.reduce((a, b) => a + b)*100}), //divide each element in array by the sum then multiply 100
hovertemplate: ' %{y}<br>%{customdata:.1f}%<extra></extra>',
name: 'Wait times',
type: 'bar'
}];
var layout = {
title: "Waiting Times",
xaxis: { title: 'Minutes' },
yaxis: { title: 'Number of customers' }
};
Plotly.newPlot('mydiv', data, layout);
Upvotes: 0
Reputation: 9773
OK, I sorted this out myself in the end.
var data = [{x: ['0-10', '11-20', '21-30', '31-45', '46-60', '61-120', '>120'],
y: [100, 55, 33, 28, 12, 11, 1],
name: 'Wait times',
type: 'bar',
hoverinfo: 'y+text',
hovertext: ['41.7%', '22.9%', '13.8%', '11.7%', '5.0%', '4.6%', '4.2%']}]
var layout = {title: "Waiting Times",
xaxis: {title: 'Minutes'},
yaxis: {title: 'Number of customers'}}
Plotly.newPlot('mydiv', data, layout)
This gives the value in the hoverinfo with the percentage value beneath it which is good enough. I could create a hovertext array with the value and the percentage in parentheses after it and just change hoverinfo to 'text' for the exact effect I wanted.
Upvotes: 3