8

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
  • 309
  • 2
  • 4
  • 11

3 Answers3

17

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
  • 15,395
  • 32
  • 113
  • 196
Bogdan Veliscu
  • 641
  • 6
  • 11
7
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
  • 26,119
  • 6
  • 18
  • 32
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
  • 71,591
  • 8
  • 33
  • 66