How to properly setup a plot function (stemplot example)?

I use the following function a lot:

def stem_plot(data, curve=False, baseline=True, basevalue=None, marker=True, kdims=["x","y"], **args):
    if basevalue is None:  basevalue = 0
    data = np.array(data).reshape(len(data))
    x = list( range(1,len(data)+1))
    y = np.full( len(data), basevalue)
    e = data
    vlines = [ np.array( [[x[i], y[i]], [x[i], e[i]]]) for i in range(len(x)) ]


    hs = hv.Path( vlines, kdims, **args ).opts( show_legend=True, muted_alpha=0.)
    if baseline: hs = hs * hv.HLine(basevalue).opts(line_width=0.4)
    if marker:   hs = hs * hv.Scatter((x,e), *kdims, **args).opts(size=4, muted_alpha=0.)
    if curve:    hs = hs * hv.Curve((x,e), *kdims, **args).opts(line_width=0.8, muted_alpha=0.)

    return hs

e.g.,

noisy = [ 2.06  0.8   0.91 -1.37 -0.2   1.03  2.5  -0.24  0.4   0.53  0.74 -0.58
  0.63  0.56  0.29 -0.08 -0.27  0.87 -1.51  0.66]
filtered = [ 4.59  0.82  1.31 -3.81 -1.8   1.06  4.95 -2.63  0.1   0.74  0.73 -2.96
  0.64  0.82  0.03 -0.35 -0.58  1.65 -4.82  0.66]
pn.Row(stem_plot( noisy ).opts("Path", width=400)* stem_plot( filtered ))

bokeh_plot

One of the annoyances is that applying opts() to the resulting output requires
specifying some component of the plot, such as hv.Path.

I am looking for suggestions on how best to implement this type of plot!

I think you might be looking for hv.Spikes?

@huang11, you could indeed implement stem_plot() using hv.Spikes.
I chose hv.Path instead. The question I am trying to ask is how best to implement
a function that uses a number of hv.Elements with its own options, etc.

The function I currently use does what I want, but could use any number of improvements!

Here’s how a ViolinPlot is created inside HoloViews

Maybe you can add an implementation somewhere here holoviews/holoviews/plotting/bokeh/chart.py at main · holoviz/holoviews · GitHub

I would think of it as a kind of hv.Curve with a no interpolation option :slight_smile:

1 Like