绘图对象:显示悬停信息不起作用

时间:2020-08-21 15:10:26

标签: python hover plotly plotly-dash

如何将“值”列中的悬停信息添加到该图中?

import plotly-graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(x = df.category,
                         y = df.type,
                         mode='markers',
                         marker={"color": df.value,
                                 "colorscale": 'Sunsetdark',
                                 "size": df["size"],
                                 "showscale": True}
                        ),
              )

我的数据框如下:

  category          value       type          size
8        B        95890.0          A     19.171122
35       G        95890.0          B     22.312869
67       V        4113.75          C     20.188301
          .
          .
          .

我尝试将参数hoverinfo = df.value传递给go.Scatter(),但这不起作用。它可以使用plotly express,但是我想使用plotly graph对象。错误提示(无效元素是我df的前10个):

ValueError: 
    Invalid element(s) received for the 'hoverinfo' property of scatter
        Invalid elements include: [95890.0, 69910.0, 4113.75, 40450.0, 77530.0, 67470.0, 97660.03, 644340.03, 79488.89, 45591.7399999998]

    The 'hoverinfo' property is a flaglist and may be specified
    as a string containing:
      - Any combination of ['x', 'y', 'z', 'text', 'name'] joined with '+' characters
        (e.g. 'x+y')
        OR exactly one of ['all', 'none', 'skip'] (e.g. 'skip')
      - A list or array of the above

1 个答案:

答案 0 :(得分:1)

您可以将df.value设置为text,然后设置hoverinfo='text'。请注意,由于您设置了mode='markers',所以绘图本身不会显示任何文本。下面根据您的代码提供了一个示例。

import plotly.graph_objects as go
import pandas as pd

df = pd.DataFrame({'category': ['B', 'G', 'V'],
                   'value': [95890.0, 95890.0 , 4113.75],
                   'type': ['A', 'B', 'C'],
                   'size': [19.171122, 22.312869, 20.188301]})

fig = go.Figure()

fig.add_trace(go.Scatter(x=df.category,
                         y=df.type,
                         text=df.value,
                         hoverinfo='text',
                         mode='markers',
                         marker={'color': df.value,
                                 'colorscale': 'Sunsetdark',
                                 'size': df.size,
                                 'showscale': True}))

fig.show()