5

I would like to modify the hovertemplate of a plotly histogram. So far, couldn't find a way to: Round the values given Remove the name of the histograms (here: '2012', '2013') Add a name to indicate what the values represent

Desired hovertext:

Bin-range: -1.24, 3.31

or

Even better alternative (range with hyphen):

Bin-range: -1.24 - 3.31

Any ideas?

import plotly.figure_factory as ff
import numpy as np
import pandas as pd

df = pd.DataFrame({'2012': np.random.randn(200),
                   '2013': np.random.randn(200)+1})

fig = ff.create_distplot([df[c] for c in df.columns], 
                         df.columns, bin_size=.25, show_rug=False)
fig.show()
vestland
  • 55,229
  • 37
  • 187
  • 305
Dana_Miles
  • 399
  • 3
  • 17
  • 1
    `create_displot` is deprecated. https://plotly.github.io/plotly.py-docs/generated/plotly.figure_factory.create_distplot.html and does not support hovertext like other plotly functions. – M-- Jun 18 '20 at 19:38

1 Answers1

5

The answer:

Adding the following snippet to your setup will produce the plot below:

fig.update_traces(hovertemplate ='<i>Bin-range</i>:' + '%{x}' + '<extra></extra>',
                  selector=dict(type="histogram"))

The part selector=dict(type="histogram") is there to only update the histogram traces and leave the lines alone. The '<extra></extra>' part is as cool as it is cryptic, and simply removes 2012 and 2013 from the hoverlabels.

enter image description here

I hope this comes close to what you want to achieve. I'll have to take a closer look at the rounding part though. But all in all I think the plot looks pretty good as it is

Some details and comments:

To my knowledge, and contrary to the statements on github on plotly.figure_factory.create_distplot, ff.create_distplot is in fact not headed towards deprecation. It's just not being updated anymore. Further, it appears that ff.create_distplot still is the best alternative for creating hisograms with a normal distribution or kde estimation added to it. So it's not going anywhere in the foreseeable future.

Complete code:

import plotly.figure_factory as ff
import numpy as np
import pandas as pd

np.random.seed(123)
df = pd.DataFrame({'2012': np.random.randn(200),
                   '2013': np.random.randn(200)+1})

fig = ff.create_distplot([df[c] for c in df.columns], 
                         df.columns, bin_size=.25, show_rug=False)

fig.update_traces(hovertemplate ='<i>Bin-range</i>:' + '%{x}' + '<extra></extra>',
                  selector=dict(type="histogram"))

#fig.update_layout(hoverinfo = 'x+y+text')

fig.show()
vestland
  • 55,229
  • 37
  • 187
  • 305