Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

Plotly (python) : How to add more then one text label in a bar chart

In the code below, i have a dataframe with 4 columns ('data', 'valor', 'nome', and 'total'). The variable 'text' sets the column 'nome' as a label. Now i need to do the same with the column 'total', i need to set the column 'total' as a label too. But i can't figure out how.

  def bar_detalhado(dframe):
                    import plotly.express as px
                    import plotly

                    df = dframe
                    fig = px.bar(df, x="data", y="valor", text="nome",
                                 color='tipo', barmode='group',
                                 height=400)
                    fig.show()

Something like ... :

def bar_detalhado(dframe):
                        import plotly.express as px
                        import plotly
    
                        df = dframe
                        fig = px.bar(df, x="data", y="valor", text="nome", text2="total",
                                     color='tipo', barmode='group',
                                     height=400)
                        fig.show()
question from:https://stackoverflow.com/questions/65861823/plotly-python-how-to-add-more-then-one-text-label-in-a-bar-chart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The docs indicate you can't specify more than one column, but you can pass a list of strings.

Here's a self-contained little example that uses df.itertuples in a list comprehension to create a string of text for each bar.

import plotly.express as px
import pandas as pd

df = pd.DataFrame(dict(data=[1, 2, 3], valor=[5, 6, 7], nome=[8, 9, 10]))
df['total'] = df.sum(axis=1)
df


def bar_detalhado(dframe):
    fig = px.bar(
        dframe, 
        x="data", 
        y="valor", 
        text=[f"n={row[2]}  v={row[1]}  t={row[3]}" for row in df.itertuples()],
    )
    fig.show()

bar_detalhado(df)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...