Search code examples
pythonholoviewshvplot

Label to holoviews HLine


I have a bar plot with two static HLine, and would like to add a label to them (or a legend) so that they are defined on the plot. I tried something like:

eq = (
    sr2.hvplot(
        kind="bar", 
        groupby ="rl", 
        dynamic = False,) 
    * hv.HLine(0.35, name="IA1").opts(color='red')
    * hv.HLine(0.2, label="IA2").opts(color='green')
)

but no label comes with the chart.


Solution

  • This answer to a similar question explains that it is not easy, and you need a workaround:
    How do I get a full-height vertical line with a legend label in holoviews + bokeh?

    You can also use parts of this solution:
    https://discourse.holoviz.org/t/horizontal-spikes/117

    Maybe the easiest is just to not use hv.HLine() when you would like a legend with your horizontal line, but create a manual line yourself with hv.Curve() instead:

    # import libraries
    import pandas as pd
    import seaborn as sns
    import holoviews as hv
    import hvplot.pandas
    hv.extension('bokeh')
    
    # create sample dataset
    df = sns.load_dataset('anscombe')
    
    # create some horizontal lines manually defining start and end point
    manual_horizontal_line = hv.Curve([[0, 10], [15, 10]], label='my_own_line')
    another_horizontal_line = hv.Curve([[0, 5], [15, 5]], label='another_line')
    
    # create scatterplot
    scatter_plot = df.hvplot.scatter(x='x', y='y', groupby='dataset', dynamic=False)
    
    # overlay manual horizontal lines on scatterplot
    scatter_plot * manual_horizontal_line * another_horizontal_line
    

    Resulting plot:

    add manual horizontal lines with legend to scatterplot