Reputation: 338
I'm trying to add custom text inside of a plotly pie chart.
I want the largest share to be labeled Rank 1, second largest Rank 2, and so on...
Is there any way to do this using the texttemplate
or some other method?
import plotly.graph_objects as go
labels = list('ABCD')
values = [25,45,13,78]
fig = go.Figure(data=[go.Pie(labels=labels, values=values,
texttemplate=("Rank %i" % 1))])
fig.show()
Upvotes: 0
Views: 3797
Reputation: 10010
You need this function:
def get_ranks(lst, begin_with_one=False):
srtd = sorted(lst, reverse=True)
res = [srtd.index(x) for x in lst]
return [x + 1 for x in res] if begin_with_one else res
import plotly.graph_objects as go
import numpy as np
labels = list('ABCD')
values = [25,45,13,78]
fig = go.Figure(data=[go.Pie(labels=labels, values=values,
texttemplate=[f"Rank {x}" for x in get_ranks(values, begin_with_one=True)])])
fig.show()
Use as often as possible the f-strings in Python3 - they are super convenient!
Since this works only with unique list elements, I created a better index assessor:
def map_to_index(lst1, lst2):
"""Return lst1 as indexes of lst2"""
dct = {}
for i, x in enumerate(lst2):
dct[x] = dct.get(x, []) + [i]
indexes = []
for x in lst1:
indexes.append(dct[x][0])
if len(dct[x]) > 0:
dct[x] = dct[x][1:]
return indexes
And an improved get_ranks()
:
def get_ranks(lst, begin_with_one=False):
srtd = sorted(lst, reverse=True)
res = map_to_index(lst, srtd)
return [x + 1 for x in res] if begin_with_one else res
Then it works also with:
import plotly.graph_objects as go
import numpy as np
labels = list('ABCDEF')
values = [25,45,13,78,45,78] # with elements of same value
fig = go.Figure(data=[go.Pie(labels=labels, values=values,
texttemplate=[f"Rank {x}" for x in get_ranks(values, begin_with_one=True)])])
fig.show()
Upvotes: 0
Reputation: 71
Passing an array to texttemplate helps
import plotly.graph_objects as go
labels = list('ABCD')
values = [25,45,13,78]
fig = go.Figure(data=[go.Pie(labels=labels, values=values,
texttemplate=([4,2,3,'Rank 1']))])
fig.show()
Upvotes: 1