How do I set precision to 1 decimal point when generating simple pie charts using plot.ly python lib?
Here's a sample code:
import plotly.plotly as py
import plotly.graph_objs as go
question = {
'A': 3,
'B': 7,
'C': 6,
'D': 11,
'E': 6
}
trace = go.Pie(labels=list(question.keys()), values=list(question.values()))
py.image.save_as([trace], filename='output.png')
That creates the following chart:
As you can see on the image, value for "A" is computed as 9.09%, thus if we sum up all the chart percentage we're left with 99,99%.
Is there a param for the plot.ly api to make them round up the "A" value to 9.1%, so that each chart percentage value would use 1 decimal point precision (and sum to 100%)?
Pie charts can be used to show percentages of a whole, and represents percentages at a set point in time. Unlike bar graphs and line graphs, pie charts do not show changes over time. The following pages describe the different parts of a pie chart.
How do you get percentages on a pie chart in Python? To add percentages to each of the constitutents of the pie chart, we add in the line, autopct='%1.1f%%', to the plt. pie() function. This formats the percentage to the tenth place.
We can get a larger chart by setting the value of that direction to be 1. In addition, we can get some more vibrant colors by setting col=rainbow(6). Finally, there is no need to just use the single letter names for the sectors of the pie.
Like this?
import plotly.express as px
import pandas as pd
df = pd.DataFrame(data=[['A',3],['B',7], ['C',6], ['D',11], ['E',6]], columns=['letter','value'])
fig = px.pie(df, names='letter', values='value')
fig.update_traces(texttemplate='%{percent:.1%f}')
fig.show()
This produces:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With