绘制graph_objects将df列添加到hovertemplate

时间:2020-07-09 23:17:43

标签: python plotly

我通常尝试绘制recreate this图,并努力将一列添加到绘图散点图的悬浮模板中。这是一个工作示例:

import pandas as pd
import chart_studio.plotly as py
import plotly.graph_objects as go

dfs = pd.read_html('https://coronavirus.jhu.edu/data/mortality', header=0)
df = dfs[0]
percent = df['Case-Fatality'] # This is my closest guess, but isn't working
fig = go.Figure(data=go.Scatter(x=df['Confirmed'],
                               y = df['Deaths'],
                               mode='markers',
                               hovertext=df['Country'],
                               hoverlabel=dict(namelength=0),
                               hovertemplate = '%{hovertext}<br>Confirmed: %{x}<br>Fatalities: %{y}<br>%{percent}',
                               
                               ))
fig.show()

我希望将列Cast-Fatality显示在{percent}

我也尝试过为Scatter()插入text = [df['Case-Fatality']],呼叫行,并将{percent}切换为{text},如this example所示,但这没有不会像希望的那样从数据框中拉出。

this example之后,我尝试将其重新配置为px,但它会引发错误dictionary changed size during iteration,我认为使用go可能比{{1}更简单},但我是新手。

预先感谢您对如何向悬停栏添加列的任何见识。

3 个答案:

答案 0 :(得分:2)

您共享的链接已损坏。您是否正在寻找类似的东西?

import pandas as pd
import plotly.express as px

px.scatter(df,
           x="Confirmed",
           y="Deaths",
           hover_name="Country",
           hover_data={"Case-Fatality":True})

然后,如果您需要使用粗体或更改hover_template,则可以按照此answer

的最后一步进行操作

答案 1 :(得分:1)

当问题要求使用 >>> pd.concat([df]*20) \ .assign(S_No=np.arange(len(df)*20) // 3+1) \ .reset_index(drop=True) 解决时,这里有两个有效-

方法 (i)

在您希望变量值所在的位置添加 graph_objects 并传递另一个名为 %{text} 的变量,该变量是 text 调用中所需值的列表。像这样-

go.Scatter()

这是完整的代码-

percent = df['Case-Fatality']
hovertemplate = '%{hovertext}<br>Confirmed: %{x}<br>Fatalities: %{y}<br>%{text}',text = percent

方法 (ii)

此解决方案要求您在将 import pandas as pd import plotly.graph_objects as go dfs = pd.read_html('https://coronavirus.jhu.edu/data/mortality', header=0) df = dfs[0] percent = df['Case-Fatality'] # This is my closest guess, but isn't working fig = go.Figure(data=go.Scatter(x=df['Confirmed'], y = df['Deaths'], mode='markers', hovertext=df['Country'], hoverlabel=dict(namelength=0), hovertemplate = '%{hovertext}<br>Confirmed: %{x}<br>Fatalities: %{y}<br>%{text}', text = percent)) fig.show() 传递给 x unified 时看到悬停标签。然后您需要做的就是传递具有相同 x 轴和所需 y 轴值的不可见轨迹。传递 hovermode 使其不可见。这是完整的代码-

mode='none'

答案 2 :(得分:0)

从另一个SO question/answer中汲取灵感,我发现这可以按需工作,并允许向悬停数据添加多个列:

import pandas as pd
import plotly.express as px

fig = px.scatter(df,
           x="Confirmed",
           y="Deaths",
           hover_name="Country",
           hover_data=[df['Case-Fatality'], df['Deaths/100K pop.']])
fig.show()