Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...