Plotly 中的 Python_DF 排序和自定义数据

标签 python pandas hover plotly scatter-plot

我在下面的代码中遇到悬停时反射数据错误的问题。查看带有每个 block 注释的代码。

我在下面的代码中遇到悬停时反射数据错误的问题。查看带有每个 block 注释的代码。

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

rows=[['501-600','15','122.58333','45.36667','Name1'],
      ['till 500','4','12.5','27.5','Name2'],
      ['more 601','41','-115.53333','38.08','Name3'],
      ['till 500', '26', '65.5', '29.5','Name4'],
      ['501-600','35','12.58333','55.36667','Name5'],
      ['more 601','9','55.53333','-38.08','Name6'],
      ]

colmns=['bins','data','longitude','latitude','names']
#Df creation
df=pd.DataFrame(data=rows, columns=colmns)
#Ordering for labels in legend
order = ['till 500', '501-600', 'more 601']
df = df.set_index('bins')
df_ordered = df.T[order].T.reset_index()
df_ordered = df_ordered.astype({"data": int})
#Plotting viz
fig=px.scatter_geo(df_ordered,lon='longitude', lat='latitude',color='bins',
                   color_discrete_sequence=px.colors.qualitative.Set1,
                   hover_name="names",
                   size='data',opacity=0.7,text='data',
                   projection="equirectangular",size_max=35,
                   )
#Adding custom data for hovers
fig.update_traces(customdata=df_ordered)
fig.update_traces(hovertemplate="<b>Name: %{customdata[4]} </b><br><br>Bin: %{customdata[0]}<br>"
                                "Data: %{customdata[1]:.2f}<extra></extra>")
#Adding marker labels
fig.add_trace(go.Scattergeo(lon=df_ordered["longitude"],
              lat=df_ordered["latitude"],
              text=df_ordered["names"],
              textposition="middle left",
              mode='text',
              textfont=dict(size=12,color="black"),
              showlegend=False,
              texttemplate="       %{text}",
              hoverinfo='skip',
              ))
fig.show()

所以最后我猜想这个问题是由订购引起的,也许我需要在自定义数据行中重新制作,但不明白如何修复它。将不胜感激您帮助修复它。

Marker size, it's color and oposition is correct, but data in hover no.

最佳答案

在这种情况下,我很难使用自定义悬停模板(您最终可以看到这个 doc ),但我认为我可以实现您正在寻找的输出,而无需添加额外的跟踪。

fig=px.scatter_geo(df_ordered,
                   lon='longitude',
                   lat='latitude',
                   color='bins',
                   color_discrete_sequence=px.colors.qualitative.Set1,
                   hover_name="names",
                   size='data',
                   opacity=0.7,
                   text='names',
                   projection="equirectangular",
                   size_max=35,
                   # by default every column go to hover
                   # you can eventually use formatting here
                   hover_data={"longitude": False,
                               "latitude": False,
                               "names": False,
                               "data": ":.2f"},
                   # if you don't want to change column names
                   # you can just change them here
                   labels={"bins": "Bin",
                           "data": "Data"}
                   )

fig.update_traces(mode="markers+text",
                  textposition="middle left",
                  textfont=dict(size=12,
                                color="black")
                  showlegend=False,
                 )

# Here I just change the `=` for `: ` in every trace
for data in fig.data:
    data.hovertemplate = data.hovertemplate.replace("=", ": ")

fig.show()

更新我刚刚意识到labelshover_data一起使用时存在一个错误,特别是如果您使用labels code> 由于某些原因,格式 "data": ":.2f"未保留。可能的解决方法如下

fig = px.scatter_geo(df_ordered,
                     lon='longitude',
                     lat='latitude',
                     color='bins',
                     color_discrete_sequence=px.colors.qualitative.Set1,
                     hover_name="names",
                     size='data',
                     opacity=0.7,
                     text='names',
                     projection="equirectangular",
                     size_max=35,
                     # by default every column go to hover
                     # you can eventually use formatting here
                     hover_data={"longitude": False,
                                 "latitude": False,
                                 "names": False,
                                 "data": ":.2f"}
                    )

fig.update_traces(mode="markers+text",
                  textposition="middle left",
                  textfont=dict(size=12,
                                color="black"),
                  showlegend=False,
                 )

# it's pretty verbose but now the output should be
# exactly as you expect
for data in fig.data:
    template = data.hovertemplate
    template = template.replace("<b>", "<b>Name: ")\
                       .replace("bins=", "Bin: ")\
                       .replace("data=", "Data: ")
    data.hovertemplate = template

fig.show()

关于Plotly 中的 Python_DF 排序和自定义数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62152593/

相关文章:

python - 从不允许直接访问页面的网站检索 json

python - 有没有办法在 python 中读取/写入没有节头的配置文件?

python - 如何使用值满足条件的列名填充 pandas 数据框中的列?

python - 过滤作为列表的 DataFrame 行

python - 使用直方图的 Matplotlib/Pandas 错误

python - fft 除法用于快速多项式除法

Python 漂亮的 XML 打印机与 lxml

css - 叠加在等于图像固定大小的图像上

java - 在 Android Studio 中悬停/触摸时在图像上显示内容

jquery - 关闭 fancybox 后 CSS3 悬停动画失败