简体   繁体   中英

Plotly Graph Objects: Hover information does not work

How can I add hover information from the column "value" to this figure?

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}
                        ),
              )

My dataframe looks like this:

  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
          .
          .
          .

I tried to pass the argument hoverinfo = df.value to go.Scatter() but that does not work. It would work with plotly express but I want to use the plotly graph object. The error says (the invalid elements are the first 10 of my df):

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

You could pass df.value as text , and then set hoverinfo='text' . Note that, since you set mode='markers' , no text will be displayed on the plot itself.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM