简体   繁体   English

Plotly:如何修改直方图的悬停模板?

[英]Plotly: How to modify hovertemplate of a histogram?

I would like to modify the hovertemplate of a plotly histogram.我想修改 plotly 直方图的悬停模板。 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到目前为止,找不到一种方法:对给定的值进行四舍五入删除直方图的名称(这里:'2012','2013')添加一个名称以指示值代表什么

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:将以下代码段添加到您的设置中将生成下面的 plot:

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.部分selector=dict(type="histogram")仅用于更新直方图轨迹并单独保留线条。 The '<extra></extra>' part is as cool as it is cryptic, and simply removes 2012 and 2013 from the hoverlabels. '<extra></extra>'部分既酷又神秘,只是从悬停标签中删除了20122013

在此处输入图像描述

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但总而言之,我认为 plot 看起来还不错

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.据我所知,与 plotly.figure_factory.create_distplot 上github上的陈述相反, ff.create_distplot实际上并没有走向弃用。 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.此外,似乎ff.create_distplot仍然是创建添加了正态分布或 kde 估计的直方图的最佳选择。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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