Search code examples
pythonhvplot

Formatting hover text when plotting with hvplot


I am trying to use hvplot.line to plot 2 y variables in a line chart. My goal is to format the hover text to some format I want (say 1 decimal). I used the standard method to format them in bokeh's hovertool and try to pass it with ".opts(tools=)". But the formatting does not reflect in the plot. I specified the format should '0.0',but the hover text still shows 3 decimal. What did I do wrong?

My code looks like something below:

import pandas as pd
import numpy as np
import hvplot.pandas
hvplot.extension('bokeh')
from numpy import random
from bokeh.models import HoverTool
df=pd.DataFrame({'length':np.linspace(0,4000,6),
 'slope':np.linspace(1.7,2.4,6),
 'Direction':np.linspace(1.2,-0.5,6),
 'clearance':random.rand(6),
 'weight':random.rand(6)},)
hover=HoverTool(tooltips=[('clearance','@clearance{0.0}'),('weight','@weight{0.0}')])
df.hvplot.line(x='length',y=['slope','Direction'],invert=True,hover_cols=['clearance','weight']).opts(tools=[hover])

But if I reduce the number of y variable to just 1. It works fine. Replace the last line of code to be:

df.hvplot.line(x='length',y=['Direction'],invert=True,hover_cols=['clearance','weight']).opts(tools=[hover])

Solution

  • You can pass the tools to the plot call as a keyword argument.

    Change your code

    # df.hvplot.line(x='length',y=['slope','Direction'], hover_cols=['clearance','weight'], invert=True).opts(tools=[hover])
    df.hvplot.line(x='length',y=['slope','Direction'], hover_cols=['clearance','weight'], tools=[hover], invert=True)
    

    and your hovertool with your formatter is applied.

    Minimal Example

    import hvplot.pandas
    import numpy as np
    import pandas as pd
    from bokeh.models import HoverTool
    hvplot.extension('bokeh')
    
    df=pd.DataFrame({
        'length':np.linspace(0,4000,6),
        'slope':np.linspace(1.7,2.4,6),
        'Direction':np.linspace(1.2,-0.5,6),
        'clearance':np.random.rand(6),
        'weight':np.random.rand(6)}
    )
    hover=HoverTool(tooltips=[('clearance','@clearance{0.0}'),('weight','@weight{0.0}')])
    df.hvplot.line(
        x='length',
        y=['slope','Direction'],
        hover_cols=['clearance','weight'],
        tools=[hover],
        invert=True
    )
    

    Output

    working hovertool