ChemaChiles
ChemaChiles

Reputation: 75

How to specify the x coordinate on a grouped bar chart on plotly?

I made a bar chart with python plotly, and I want to put a marker on a particular bar, example non-smoking females. Does anyone know how to specify this?

I took an example from the plotly documentation, if I try to put the marker it just takes the center of the main category.

import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="sex", y="total_bill",
             color='smoker', barmode='group',
             height=400)

#trying to set the marker
fig.add_trace(
    go.Scatter(x=["Female"],
               y=[1100]
              ))
fig.show()

enter image description here

Upvotes: 3

Views: 717

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31166

import plotly.express as px
import plotly.graph_objects as go
import numpy as np

df = px.data.tips()
fig = px.histogram(
    df, x="sex", y="total_bill", color="smoker", barmode="group", height=400
)

# trying to set the marker
fig.add_trace(
    go.Scatter(
        x=[0.15],
        y=[1100],
        customdata=[["No", "Female"]],
        xaxis="x2",
        hovertemplate="smoker=%{customdata[0]}<br>sex=%{customdata[1]}<br>sum of total_bill=%{y}<extra></extra>",
    )
)
fig.update_layout(xaxis2={"overlaying": "x", "range": [0, 1], "showticklabels": False})

fig

enter image description here

Upvotes: 2

Related Questions