密谋:如何修改直方图的悬浮模板?

时间:2020-06-18 11:22:17

标签: python plotly plotly-python

我想修改绘图直方图的悬停模板。到目前为止,找不到以下方法: 四舍五入给定的值 删除直方图的名称(此处为“ 2012”,“ 2013”​​) 添加名称以指示值代表什么

所需的悬浮文本:

Bin-range: -1.24, 3.31

更好的选择(带连字符):

Bin-range: -1.24 - 3.31

有什么想法吗?

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

1 个答案:

答案 0 :(得分:3)

答案:

在您的设置中添加以下代码段将产生以下图:

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

selector=dict(type="histogram")部分仅用于更新直方图迹线,而不会留下线条。 '<extra></extra>'部分就像神秘的部分一样酷,只需从悬浮标签中删除20122013

enter image description here

我希望这接近您想要实现的目标。不过,我将不得不仔细研究舍入部分。但总的来说,我认为情节看起来很不错

一些细节和评论:

据我所知,与plotly.figure_factory.create_distplot上github上的声明相反,ff.create_distplot实际上并未走向过时。只是不再更新了。此外,似乎ff.create_distplot仍然是创建添加了正态分布或kde估计的直方图的最佳选择。因此,在可预见的将来它不会走到任何地方。

完整代码:

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