【发布时间】:2021-10-19 00:18:51
【问题描述】:
我有 2 个 dfs;第一个具有制作热图的值,第二个 df 具有我想在悬停时使用的元数据。
我已经尝试了很多事情,这几乎可以正常工作,除了有一些我不明白的行为:
import plotly.express as px
import pandas as pd
import difflib
df1 = pd.DataFrame([[22,33],[23,31]], columns=['A','B'])
df2 = pd.DataFrame([['top_left','top_right'],['bottom_left','bottom_right']], columns=['A','B'])
print(df1)
print(df2)
fig = px.imshow(df1,
color_continuous_scale=px.colors.diverging.RdYlGn,
title='QC')
def ff(sample, pos, tmp):
d=tmp.to_dict()
s2 = list(d.keys())[0]
print(sample, pos, s2, s2 == sample, s2 == 'A', sample == 'A', type(sample), type(s2), list(difflib.ndiff([sample], [s2])))
return sample, pos #1, tmp.loc[pos, sample]
fig.update_traces(hovertemplate="Sample: %{x} <br> Position: %{y} <br> Score: %{z}" +\
f" <br> Depths: {ff('%{x}', '%{y}', df2)}")
fig.show()
给予
A B
0 22 33
1 23 31
A B
0 top_left top_right
1 bottom_left bottom_right
%{x} %{y} A False True False <class 'str'> <class 'str'> ['- %{x}', '+ A']
所以 s2 != sample 因为它仍然是 %{x} (不是 'A')。这可以解释为什么这不起作用#1,tmp.loc [pos,sample]。我不知道如何解决这个问题。任何帮助表示赞赏!
要明确一点 - 如果我将鼠标悬停在热图的左上角 (A0) 上,我想要得到的是“top_left”。
【问题讨论】:
-
似乎首先构建了模板字符串,即调用了
ff(…),解析了f-字符串插值等,然后仅将字符串用作模板(使用%{x}和%{y}已替换)。 -
是的。知道如何进行这项工作吗?
-
我无法测试任何东西,因为我在这里没有 plotly,但你可以看看将额外的数据框列传递为
custom_data,例如stackoverflow.com/questions/59057881/… -
嗯,我今天确实读过,但现在我更深入地了解它更有意义。泰
-
这也有一个带有自定义数据和热图的示例:chart-studio.plotly.com/~empet/15366/…
标签: pandas hover plotly heatmap plotly-python