Add two texts to each bar chart in plotly

Viewed 3079

I am working on plotly (python) to plot a horizontal bar chart like the below figure.

import plotly.express as px


fig = px.bar(
         x=prices,
        y=['Average $' + str(round(avg_price, 2)), 'Lowest $' + 
str(round(min_price, 2)), 'Last $' + str(round(last_price, 2)), 
'Proposed $' + str(round(proposed_price, 2))],
         color=['Last', 'Average', 'Lowest',  'Proposed'],
         text=delta,
         orientation='h',
         height=400,
        )
fig.add_vline(x=spend[-1], line_width=2, line_dash="dash", 
line_color="red")
fig.add_vline(x=max(spend), line_width=2, line_dash="dash", 
line_color="green")
fig.update_traces( textposition='outside')


fig.update_layout(
        title="Saving/Loss diagram",
        xaxis_title="",
        yaxis_title="",
        legend_title="Vendor names",
        width=1000,
        )
fig.show()

enter image description here

In this figure I display text only outside of each bar chart. But now I am going to display another text inside each bar chart. How can I do that in plotly (python)?

1 Answers

If you want to add a text inside the bars with plotly.express, you could use fig.update_traces with two parameters texttemplate and textposition

You could try this code:

import plotly.express as px

data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
fig.update_traces(texttemplate = data_canada.year.unique(),textposition = "inside")
fig.show()

enter image description here

There is an option to do all this with plotly.graph_objects.

But here, you should add text that appears inside the bars and textposition adjust the text.

import plotly.graph_objects as go

data_canada = px.data.gapminder().query("country == 'Canada'")

fig = go.Figure(data=[go.Bar(
            x=data_canada.year, y=data_canada["pop"],
            text=data_canada.year.unique(),
            textposition='inside'
        )])

fig.show()

enter image description here

Update based on the comments:

You can change the position of each text for each bar but the possible positions are four positions: "inside" | "outside" | "auto" | "none" as documented on the main page of plotly here, search for textposition attribute.

To do this you can do it as follows:

import plotly.express as px
x = ['Aaron', 'Bob', 'Chris','Tom','Anna']
y = [5, 10, 6, 11, 8]

texts = ["first","second","third","fourth","fifth"]
positions = ['inside','outside','auto','outside','inside']
fig = px.bar(x=x, y=y)
fig.update_traces(texttemplate = texts, textposition = positions)
fig.show()

enter image description here

Related