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],
hoverinfo=‘text’,
marker={‘color’:[’#67a9cf’,’#1c9099’,’#016c59’]}
)]

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,
x=xi,
text="{0: ,}".format(yi),
font={‘color’:‘white’},
showarrow = False,
) for xi, yi in zip(data[‘value’].values,
data[‘count’].values,
)
]

layout = Layout(title=‘Title’,
yaxis={‘title’:‘Count’},
height = 450,
width = 800,
annotations=annotations
)

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