Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set y-axis in millions [duplicate]

I have a problem with this plot:

[![enter image description here][1]][1]

The y-axis is in unit but I need them to be in millions as such:

[![enter image description here][2]][2]

Do you know a method to achieve this? Thanks in advance.

like image 355
SosaAlmighty Avatar asked Apr 20 '20 19:04

SosaAlmighty


3 Answers

You can use a custom FuncFormatter like this:

from matplotlib.ticker import FuncFormatter
import matplotlib.pyplot as plt
def millions(x, pos):
    'The two args are the value and tick position'
    return '%1.1fM' % (x * 1e-6)


formatter = FuncFormatter(millions)

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)

Or you can even replace millions with the following functions to support all magnitudes:


def human_format(num, pos):
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    # add more suffixes if you need them
    return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])

like image 183
Bogdan Veliscu Avatar answered Oct 21 '22 02:10

Bogdan Veliscu


import pandas as pd
import matplotlib .pyplot as plt
import matplotlib.ticker as ticker
fig, ax=plt.subplots()
ax.plot([1, 2], [1000000, 5000000])
scale_y = 1e6
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax.yaxis.set_major_formatter(ticks_y)
ax.set_ylabel('val in millions')

enter image description here

like image 42
wwnde Avatar answered Oct 21 '22 01:10

wwnde


You could use a FuncFormatter:

from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter

def millions_formatter(x, pos):
    return f'{x / 1000000}'

fig, ax = plt.subplots()
ax.plot([1, 2], [1000000, 5000000])
ax.yaxis.set_major_formatter(FuncFormatter(millions_formatter))
ax.set_ylabel('value (in millions)')
plt.show()

resulting plot

like image 39
JohanC Avatar answered Oct 21 '22 02:10

JohanC