CryptTP
CryptTP

Reputation: 11

Embedding individual label into plotly express histogram

I'd like to embedded individual label(s) into each bar of the plotly express histogram.

As an example:

import plotly.express as px
import pandas as pd
    
df = pd.DataFrame({'name':['label1', 'label2','label3', 'label4', 'label1'],
                   'val1':[1,2,1,2,1]})

px.histogram(df, x='val1', nbins=3)

enter image description here

Is it possible to have ['label1', 'label3'], ['label2', 'label4'] appear in the 1st and 2nd columns of the histogram plot, respectively?

Upvotes: 1

Views: 624

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31226

  • work out data in pandas as well
  • add additional information onto figure as annotations
import plotly.express as px
import pandas as pd
    
df = pd.DataFrame({'name':['label1', 'label2','label3', 'label4', 'label1'],
                   'val1':[1,2,1,2,1]})

fig = px.histogram(df, x='val1', nbins=3)

# work out bins in pandas...
df2 = (
    df.groupby(pd.cut(df["val1"], bins=3))
    .agg(
        count=("name", "size"),
        labels=("name", lambda s: ",".join(s.drop_duplicates().tolist())),
    )
    .assign(
        l=lambda d: [i.left for i in d.index.values],
        r=lambda d: [i.right for i in d.index.values],
        x=lambda d: [(i.left+i.right)/2 for i in d.index.values],
        count=lambda d: d["count"].astype(float)
    )
).fillna("")

# add text to histogram
for r in df2.iterrows():
    fig.add_annotation(text=r[1]["labels"], x=(r[1]["l"]+r[1]["r"])/2, y=r[1]["count"]+.2, showarrow=False)

fig

enter image description here

Upvotes: 1

Related Questions