Python绘图仪散布\地理修改悬停数据

2024-04-19 11:32:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想修改悬停数据并将其保留,例如,只保留bins数据。 我编写了以下代码,但是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=(['bins']))

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

Tags: 数据importgodfdataasfigplotly
3条回答

使用接受的答案,我发现以下错误(类似于@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"]]

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

使用悬停模板:Ahover 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,请参见herehere

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的要点

对于scatter\u geo的hover\u 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_数据中将列名设置为False将从hover_数据中删除该列名。 希望这能回答你的问题

相关问题 更多 >