How to add data labels to bar plot?

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

9 Likes