Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Direct labels and hover info to be different in plotly

I have a stacked bar chart. On the segments in the bar chart I want to add the numbers (y values) and on hover I want some different information to be shown (not name or x or y values).

Is it possible? From what I can see hoverinfo let's you only duplicate the values in text or add the name.

import plotly
from plotly.graph_objs import Layout, Bar

hoverinformation = ["test", "test2", "test3", "test4"] # this info I would like it on hover
data = []
for index, item in enumerate(range(1,5)): 
    data.append(
        Bar(
            x="da",
            y=[item],
            name="Some name", # needs to be different than the hover info
            text=item,
            hoverinfo="text",
            textposition="auto"
        )
    )

layout = Layout(
    barmode='stack',
)

plotly.offline.plot({
    "data": data,
    "layout": layout
})

This is a simple stack bar and the value on hover would be either in a pandas dataframe or in a variable hoverinformation

Preferably a solution that doesn't involve the creation of 2 plots one on top of the other...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes you can do this by using the hovertext element. Docs

import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)


hoverinformation = ["test", "test2", "test3", "test4"] # this info I would like it on hover
data = []
for index, item in enumerate(range(1,5)): 
    data.append(
        go.Bar(
            x="da",
            y=[item],
            hovertext=hoverinformation[index], # needs to be different than the hover info
            text=[item],
            hoverinfo="text",
            name="example {}".format(index),  # <- different than text
            textposition="auto",

        )
    )

layout = go.Layout(
    barmode='stack',
)

iplot({
    "data": data,
    "layout": layout
})

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...