Black Lives Matter. Please consider donating to Black Girls Code today.

Calculate bar length for conditional annotation

I’ve created some bar charts using custom hover text and bar annotations. The main problem I’m running into is that in some cases the length of the bar is not long enough to include the annotation. In these circumstances, I’d like to suppress the annotation and the value will be available on the hover event. How can I figure out if the length of the bar is too short for the annotation?

Sample code

bars = [Bar(y = data[‘count’].values,
x = data[‘value’].values,
text = ["{0:.2f}%".format(x) for x in data[‘percent’].values],

NOTE: For y the calculation was trying to shift the annotation down slightly so it wasn’t on the edge of the bar. I’m not sure this the best way to go about it.

annotations = [dict( y=yi - yi*.08,
text="{0: ,}".format(yi),
showarrow = False,
) for xi, yi in zip(data[‘value’].values,

layout = Layout(title=‘Title’,
height = 450,
width = 800,

fig = Figure(data= bars, layout=layout)
iplot(fig, config={‘displayModeBar’: False})