0
votes

I have some DataFrame to be plotted on plotly in bar chart.

Here is a dataframe example:

Here is an example of dataframe

I am trying to display on graph 2 direct data labels, but can not do it anyway. I want to show count and share separated by comma (e.g. "3.3M, 0.88"). Can anyone help me?

Below is my code:


    import plotly.express as px
    fig = px.bar(
        df, x="range", y="count", hover_data=["share"], color="range", text="count", height=500, width=950,
        color_discrete_sequence = px.colors.sequential.Plasma_r
                )
    fig.update_layout(xaxis_type="category")
    fig.update_traces(texttemplate='%{text:.2s,  }', textposition='outside')
    pio.write_html(fig, 'cell_id.html')
    fig.show()

Here is an example of graph

Thank you beforehand!

1

1 Answers

3
votes

I had the same problem and solved it like follows (I took your data as example):

import pandas as pd
import plotly.express as px
x = [1, 2, 3, 4, 5]
y = [3300000, 290000, 88000, 40000, 57000]
df = pd.DataFrame(dict(range=['1-10', '11-20', '21-30', '31-40', '41 or above'],
                       count=[3322933, 287372, 87938, 40061, 56767], share=[0.88, 0.08, >0.02, 0.01, 0.01]))

fig = px.bar(df, x='range', y='count', hover_data=['share'], color='range',
             text=('{}, {:.2f}'.format(df['count'][0], df['share'][0]),
                   '{}, {:.2f}'.format(df['count'][1], df['share'][1]),
                   '{}, {:.2f}'.format(df['count'][2], df['share'][2]),
                   '{}, {:.2f}'.format(df['count'][3], df['share'][3]),
                   '{}, {:.2f}'.format(df['count'][4], df['share'][4])),
             height=500, width=950, color_discrete_sequence = 
px.colors.sequential.Plasma_r)

fig.update_layout(xaxis_type="category")
fig.update_traces( textposition='outside')
fig.show()

which results in the following plot: enter image description here

So you have to add the direct labels as a list to the parameter px.bar(text=list()) and create an individual entry for every bar.

by changing the entries for example like this

text=(`{}people, {:.2f}%'.format(df['count'][0], df['share'][0]*100)`, ...)

3322933people, 88%

you can add more detail information to the direct labels.

I do not know whether there is a more elegant way to code this but this did it for me.

I hope this helps.