简体   繁体   中英

Python Plotly xaxis hover text disappears when hoverinfo is set in a trace

I am plotting multiple (2) lines from a timeseries with plotly (v 2.7) in Jupyter notebook. I would like that, on hover, the axis label to appear, and a formatted text for one of the lines.

First, I had

data = []

name = 'houses'
data.append(
    go.Scatter(
        x=df.index,
        y=df[name],
        name=name,
    )
)

name = 'vazamento'
scale = 50
data.append(
    go.Scatter(
        x=df.index,
        y=df[name]*scale,
        name='leaks' + ' (ratio {0}:1)'.format(scale),
    )
)

fig = go.Figure(data=data)
iplot(fig)

which gave me 在此处输入图片说明

Now, trying to show text on hover:

name = 'vazamento'
scale = 50
data.append(
    go.Scatter(
        x=df.index,
        y=df[name]*scale,
        name='leaks' + ' (ratio {0}:1)'.format(scale),
        # Added the two lines below
        text=df[name].apply(lambda x: "{0:.0f}".format(x)+" - ")+str('leaks'),
        hoverinfo='text',
    )
)

which results in the chart below, making the x axis info on hover disappear. 在此处输入图片说明

I have tried editing the xaxis in the chart layout attribute, but had no success.

How can I keep showing the X axis info on hover, just like it appears in the first chart?

I have found the solution by trial and error after quite some time, I want to document it here.

When any trace in the data list contains the hoverinfo attribute, the x axis info on hover disappears. X info will be shown only in the traces containing x in hoverinfo . So, by default, in the other traces. That's why the second chart in the question started displaying the date (x axis info) on the houses trace, even if the edited trace was leaks .

So, in order to achieve my goal, I had to add hoverinfo='x+SOMETHING' to every trace in the plot:

data = []

name = 'houses'
data.append(
    go.Scatter(
        x=df.index,
        y=df[name],
        name=name,
        # Added this line
        hoverinfo='x+y',
    )
)

name = 'vazamento'
scale = 50
data.append(
    go.Scatter(
        x=df.index,
        y=df[name]*scale,
        name='leaks' + ' (ratio {0}:1)'.format(scale),
        # Added the 2 lines below
        text=df[name].apply(lambda x: "{0:.0f}".format(x)+" - ")+str('leaks'),
        hoverinfo='x+text',
    )
)

fig = go.Figure(data=data)
iplot(fig)

which results in this chart:

在此处输入图片说明

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