7

How to add a horizontal line to a hvplot ? Holoviews has .HLine and .VLine but not sure how to access it via pandas.hvplot or hvplot

here is a sample dataframe and plotting script.

import pandas as pd
import hvplot.pandas

df = pd.DataFrame({'A':[100], 'B':[20]})
df = df.reset_index()

print(df)
#   index   A       B
#0  0       100     20

# create plot
plot = df.hvplot.bar(y=['A', 'B'], x='index', 
              rot=0, subplots=False, stacked=True)

plot


enter image description here

Sander van den Oord
  • 10,986
  • 5
  • 51
  • 96
muon
  • 12,821
  • 11
  • 69
  • 88

1 Answers1

10

I would just overlay a holoviews hv.HLine() to your plot like so:

import holoviews as hv

your_hvplot * hv.HLine(60)

Using the * symbol in the code is an easy of putting the HLine on top of your other plot.
This is called an Overlay.


If you also need a label with your HLine, this SO question contains an example for that:
How do I get a full-height vertical line with a legend label in holoviews + bokeh?


Your sample code with the horizontal line would look like this then:

# import libraries
import pandas as pd
import hvplot.pandas
import holoviews as hv

# sample data
df = pd.DataFrame({'A':[100], 'B':[20]})

# create plot
plot = df.hvplot.bar(
    y=['A', 'B'], 
    stacked=True, 
    xaxis='', 
    title='Adding horizontal line hv.HLine() to plot with * overlay',
)

# create separate hline 
# for demonstration purposes I added some styling options
hline = hv.HLine(60)
hline.opts(
    color='red', 
    line_dash='dashed', 
    line_width=2.0,
)

# add hline to plot using * which overlays the hline on the plot
plot * hline

Final result:
adding hv.hline to hvplot

Sander van den Oord
  • 10,986
  • 5
  • 51
  • 96
  • thanks for showing how to avoid using 'index', that was ugly hack. – muon Nov 09 '19 at 14:26
  • yeah in this case, if you don't specify the 'x' argument, hvplot() will automatically take the index of your dataframe as the 'x' argument. But sometimes i also find myself using .reset_index() in cases where it doesn't work :) – Sander van den Oord Nov 11 '19 at 09:33