set y-axis in millions [duplicate]

荒凉一梦 提交于 2021-02-05 06:03:53

问题


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.


回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/61330427/set-y-axis-in-millions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!