4

Using the hvplot tutorial we are trying to generate a bar plot with values as labels on the bars itself.
The bar plot is generated using the following code

import dask.dataframe as dd
import hvplot.pandas
df = dd.read_parquet('data/earthquakes.parq').persist()  
df.magType.value_counts().compute().to_frame().hvplot.bar()

enter image description here

How can we add the value of the bars on the bar itself?

Sander van den Oord
  • 10,986
  • 5
  • 51
  • 96
skibee
  • 1,279
  • 1
  • 17
  • 37

1 Answers1

2

Use holoviews hv.Labels() to add value labels to your data.

You create the labels separately and use the * symbol to overlay your labels on your plot.

Here's a working example:

# import libraries
import numpy as np
import pandas as pd

import holoviews as hv
import hvplot.pandas

# create some sample data
df = pd.DataFrame({
    'col1': ['bar1', 'bar2', 'bar3'],
    'col2': np.random.rand(3)
})

# create your plot
plot = df.hvplot(kind='bar', x='col1', y='col2', ylim=(0, 1.2))

# create your labels separately
# kdims specifies the x and y position of your value label
# vdims specifies the column to use for the value text of your label
labels = hv.Labels(data=df, kdims=['col1', 'col2'], vdims='col2')

# use the * symbol to overlay your labels on your plot
plot * labels


Final result:
enter image description here

Sander van den Oord
  • 10,986
  • 5
  • 51
  • 96
  • 2
    We tried to use the `yoffset` as shown in [Labels guide](http://holoviews.org/reference/elements/matplotlib/Labels.html) but then graph disappears - what are we doing worng? ` labels = hv.Labels(data=df, kdims=['col1', 'col2'], vdims='col2').opts(hv.opts.Labels(yoffset=0.05))` – skibee Nov 18 '19 at 07:32
  • i ran into the same problem, maybe you can ask about your issue here: https://gitter.im/pyviz/pyviz These are the developers and they are quite responsive to problems, maybe they know a solution to this. – Sander van den Oord Nov 18 '19 at 08:55
  • There is an [open issue #3892 on github](https://github.com/holoviz/holoviews/issues/3892) – skibee Nov 18 '19 at 09:36
  • If you switch the holoviews backend to plotly using hv.extension('plotly') then yoffset is working. So within holoviews it is working for plotly, but not for the bokeh backend. – Sander van den Oord Nov 18 '19 at 10:43
  • Thx for the update, unfortunately I don't have plotly in my environment – skibee Nov 18 '19 at 13:18