6

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.

SosaAlmighty
  • 257
  • 2
  • 3
  • 10

3 Answers3

12

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])

nbro
  • 13,796
  • 25
  • 99
  • 185
Bogdan Veliscu
  • 591
  • 5
  • 11
5
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

wwnde
  • 22,093
  • 5
  • 13
  • 27
  • Hi I've edited my question by adding my code so that you can better understand what is my problem, thank you in advance! – SosaAlmighty Apr 21 '20 at 08:54
1

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

JohanC
  • 59,187
  • 8
  • 19
  • 45