How to add data labels to bar plot?

I want to add data labels to the bars of my bar plot, as seen here:

image
(chart and python code accessible here

How do I do it? Right now what I have is:

plotly()
y = rand(5)
x = string.([1,2,3,4,5])
using Plots
bar = plot(x, y, st = :bar, txt = x)

which returns:

Note that if I change st = :bar to st = :scatter, it works as expected:

plotly()
y = rand(5)
x = string.([1,2,3,4,5])
using Plots
scatter = plot(x, y, st = :scatter, txt = x)


(well, I’d like the labels to not overlap with the markers but I guess that is easy to change)

3 Likes

I’m looking at a fix for this, but a workaround is to add

plot!(y .+ 0.1, st=:scatter,marker_shape=:none,primary=false,series_annotations=x)
1 Like

The following syntax seems to work fine with both plotly() and gr(), using annotate with automatic bottom alignment.

using Printf, Plots
x = [1,2,3,4,7]
y = rand(5)
str = [@sprintf("%.2f", yi) for yi in y]
Plots.bar(x,y, title="Annotated bar plot",legend=false)
annotate!(x,y, str, :bottom)

Annotated_bar_plot

PS: included also a trick shown here to control the annotations’ font size, via tuples. But then the vertical positioning of the labels needs to be refined manually

using Printf, Plots
x = [1,2,3,4,7]
y = rand(5)
str = [(@sprintf("%.2f", yi),10) for yi in y]  # tuple with fontsize=10 (by: @pdeffebach)
(ymin,ymax) = extrema(y)
dy = 0.05*(ymax-ymin)
Plots.bar(x,y, title="Annotated bar plot",legend=false)
annotate!(x,y.+dy, str, ylim = (0,ymax+2dy))

Annotated_bar_plot_with_font_size

7 Likes

Took me a while to figure out why that works. Cool!

For posterity: Now it works natively as your initial example.

It does work, but changing the fontsize does not seem to work like the other attributes. Any information on that and chaking the x/y location of the annotations?