简体   繁体   中英

Plotly: How to modify hovertemplate of a histogram?

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()

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.

在此处输入图像描述

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM