1

How to convert number to compact format for better visualization in graphs?

Numbers are coming from a series.

This is my annotation code:

for x, y in zip(t2.index,t2):
    label="{:.0f}".format(y)
    plt.annotate(label, # this is the text
                 (x,y), # this is the point to label
                 textcoords="offset points", # how to position the text
                 xytext=(0,10), # distance from text to points (x,y)
                 ha='center')

enter image description here

Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
  • 1
    I'm not very familiar with `matplotlib`, but i'm guessing you could use scientific notation or things like `10M`? – Ayush Garg Apr 24 '21 at 04:35

1 Answers1

0

As commented, you could use either scientific notation:

label = f'{y:.1e}' # 13236334 -> 1.3e+07

Or human format:

label = human_format(y) # 13236334 -> 13.2M

Where human_format() is something like this:

# from https://stackoverflow.com/a/49955617/13138364
def human_format(num, round_to=1):
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num = round(num / 1000.0, round_to)
        abbr = ['', 'K', 'M', 'G', 'T', 'P'][magnitude]
    return f'{num:.{round_to}f}{abbr}'
tdy
  • 36,675
  • 19
  • 86
  • 83