Quick help with barchart text formatting

Hi all, I love this product and love the community. Glad to have stumbled across Dash when I did.

I’ve done my due diligence and can’t find anything on the internet for the particular problem that I’m having. I’ve got a simple bar chart created through plotly.express.bar (it’s part of a multipage Dash app that I am creating). One of the arguments that you can give that method is ‘text’, which takes a column of data (in this case the count that each bar represents) and displays it at the top of the bar. Anyone who’s tried to do the same thing in matplotlib knows how much of a timesaver that “text” argument is.

Anyway, everything works great, except that sometimes when the bars are short, the counts get rendered horizontally instead of vertically. What’s baffling is that sometimes the number will appear outside of the bar vertically (on top of it) which would be a great solution if it was consistent.

Screen Shot 2020-12-02 at 6.17.37 PM

Any suggestions here to get the number to always render vertically?

Hi americanthinker,
I think you can manage it using textposition = “outside”

This is the explanation from this link: https://plotly.com/python/reference/bar/#bar-textposition

textposition
Code: fig.update_traces(textposition=<VALUE>, selector=dict(type='bar'))
Type: enumerated or array of enumerateds , one of ( "inside" | "outside" | "auto" | "none" )
Default: "none"

Specifies the location of the text. “inside” positions text inside, next to the bar end (rotated and scaled if needed). “outside” positions text outside, next to the bar end (scaled if needed), unless there is another bar stacked on this one, then the text gets pushed inside. “auto” tries to position text inside the bar, but if the bar is too small and no bar is stacked on this one the text is moved outside.

Hi @Eduardo,

Thanks for pointing out that parameter, which I had overlooked. I made the change that you suggested and it did work, in terms of popping all of the numbers on top of the bar, but then it created another problem when the bars are at the top of the graph, you can no longer see the number.

I did a simple hack to fix that issue and just set the range_y parameter to always be a max of 1.3 x the biggest value, thus ensuring there is always room for the number to show no matter what the underlying values are.

I think the “auto” option might be a bug, because it should automatically pop the number out if it sense that it won’t fit in the box or not appear in the graph.

But either way, I’m closing out this issue, thanks for the support!

Hi americanthinker
:+1:
I had the same problem with a waterfall chart, aparently is a bug that they are trying to solve,
chriddyp gave me a solution that is specifically to the waterfall but may be other similar for your chart.
See this:

1 Like