Python plotly scatter_geo 修改悬停数据

Python plotly scatter_geo modify hover data

我想修改悬停数据并留在那里,例如只有 bins 数据。 我编写了以下代码,但 hover_data 参数不起作用。修改haver数据的方法是什么?

import plotly.express as px
import plotly.graph_objs as go
import pandas as pd

rows=[['501-600','15','122.58333','45.36667'],
      ['till 500','4','12.5','27.5'],
      ['more 1001','41','-115.53333','38.08'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)
df = df.astype({"data": int})

fig=px.scatter_geo(df,lon='longitude', lat='latitude',
                      color='bins',
                      opacity=0.5,
                      size='data',
                      projection="natural earth", hover_data=(['bins']))

fig.add_trace(go.Scattergeo(lon=df["longitude"],
              lat=df["latitude"],
              text=df["data"],
              textposition="middle center",
              mode='text',
              showlegend=False))
fig.show()

对于scatter_geo的hover_data参数,您可以如下提及。

import plotly.express as px
import plotly.graph_objs as go
import pandas as pd

rows=[['501-600','15','122.58333','45.36667'],
      ['till 500','4','12.5','27.5'],
      ['more 1001','41','-115.53333','38.08'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)
df = df.astype({"data": int})

fig=px.scatter_geo(df,lon='longitude', lat='latitude',
                      color='bins',
                      opacity=0.5,
                      size='data',
                      projection="natural earth", hover_data={'longitude':False,'latitude':False,'data':False})

fig.add_trace(go.Scattergeo(lon=df["longitude"],
              lat=df["latitude"],
              text=df["data"],
              textposition="middle center",
              mode='text',
              showlegend=False))


fig.show()

在 hover_data 中将列名称设置为 False 将从 hover_data 中删除该列名称。 希望这能回答您的问题。

使用悬停模板: hover template 在这种情况下可能效果很好:

fig=px.scatter_geo(df,lon='longitude', lat='latitude',
                      #color='bins',
                      opacity=0.5,
                      size='data',
                      projection="natural earth")

fig.update_traces(customdata=df.bins)
fig.update_traces(hovertemplate='Bins: %{customdata}<extra></extra>')

有关在悬停模板中使用 customdata 的信息,请参阅 here and here

customdata – Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, “scatter” traces also appends customdata items in the markers DOM elements

更新:在px.scatter_geo中使用color选项将对结果图的数据进行分组,使得customdata不再与强调绘图数据。这通常是我放弃 plotly express 而使用 plotly go 的地方。

使用接受的答案,我发现了以下错误(类似于@Asha Ramprasad 的评论):

RuntimeError: dictionary changed size during iteration

还有以下内容:

Python 3.7.6 (default, Jan  8 2020, 13:42:34) 
>>> import plotly
>>> plotly.__version__
'4.4.1'

我通过传递我想要的数据框列列表而不是字典来消除错误:

hover_data = [df["whatever I want displayed"],df["other thing to display"]]

这种阴谋的行为对我来说似乎是一个错误。请注意,这不允许删除列,只能添加。