'Change the format of values in a Plotly pie chart (in Python)

I'd like to make a pie chart in Python with plotly that displays amounts of money. The following code shows a minimal working example:

import pandas as pd
import plotly.express as px

data = {"Name": ["Stocks", "ETF's", "Cash"], "Value": [1000, 2000, 3000]}
df = pd.DataFrame(data)
figure = px.pie(df, values='Value', names='Name',
                title='Fund Distribution')
figure.update_traces(textposition='inside', textinfo='percent+label+value')

figure.show()

Which yields the following figure: enter image description here

But, it'd like to format the values. I.e. $3,000 instead of just 3000. I found this question regarding the same problem in R but nothing in Python.

Thanks a lot.



Solution 1:[1]

You can use text attribute to format values and then add it to textinfo:

import pandas as pd
import plotly.express as px

data = {"Name": ["Stocks", "ETF's", "Cash"], "Value": [1000, 2000, 3000]}
df = pd.DataFrame(data)


figure = px.pie(df, values='Value', names='Name',
                title='Fund Distribution',)

figure.update_traces(textposition='inside', 
                     text=df['Value'].map("${:,}".format),
                     textinfo='percent+label+text')


figure.show()

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phoenix