plotly / plotly/plotly.js

bar chart: textposition='auto' not working for 0 values

Open
#6,474 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug P3
Dominant language
JavaScript
Stars
18.3k
Forks
2k
Avg merge
2d 12h
Merged PRs (30d)
28

Description

Screenshot 2022-09-23 at 17 54 08

From the textposition argument documentation for bar traces:

"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.

For small values this is working nicely: Instead of inside, the text gets positioned outside.

But: For 0 values, the text disappears completely instead of being moved outside.

import pandas as pd
import plotly.express as px

df = pd.DataFrame({
    "Country": [f"Country {n}" for n in range(6)],
    "Some Metric": [8,5,5,.5,0.0001,0]
})

fig = px.bar(
    df, 
    x='Some Metric',
    y='Country', 
    text='Country',
    orientation='h')
fig.update_yaxes(visible=False, showticklabels=False)

# change here between "auto" (default), "inside", "outisde"
fig.update_traces(textposition="auto")

fig.show()

Setting 0 values to a small value is a dirty fix that may also lead to the text disappearing when the graph is resized. At the same time, such a fix endangers data integrity.

The alternative would be setting the textposition for every observation separately. I think that should be avoided and covered by setting texposition="auto".

Fix that everybody can implement in their code currently:

fig.update_traces(textposition=['outside' if val==0 else 'auto' for val in df['Some Metric']])

Tested with plotly 5.10.0.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the horizontal bar-chart example with textposition="auto" and a zero value, then trace the bar-trace text-positioning path used by Plotly.js. Confirm the existing behavior for small values and define done as keeping the label visible outside the bar when its value is zero, with coverage in the relevant bar-trace tests if available.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
data-visualization
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
66/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.