首页 > 解决方案 > 如何在matplotlib plot的xlabel中打印10K、20K....1M

问题描述

嗨,我正在与 RL 合作,我想绘制 n 个时间步的奖励。假设如果我有 100 万个时间步长,我将获得相同的奖励。现在,当我绘制它时,x 标签变得更加混乱。我希望 xlabel 显示为 10K、20K 到 1M。我该怎么做?

例如我有这个代码,

import matplotlib.pyplot as plt
import torch

x = torch.rand(1000000,)
plt.plot(x)
plt.show()

因此,当您绘制此图时,在 x 轴上您将得到 0、200000、400000、600000、800000、1000000 但我想将其打印显示为 20K、40K、60K、80K、1M

标签: pythonpython-3.xmatplotlib

解决方案


这是对Jake VanderPlas 的自定义刻度的改编(他写成 π 的倍数)。

from math import log10, floor
from matplotlib import pyplot as plt

def format_func(value, tick_number=None):
    num_thousands = 0 if abs(value) < 1000 else floor (log10(abs(value))/3)
    value = round(value / 1000**num_thousands, 2)
    return f'{value:g}'+' KMGTPEZY'[num_thousands]

fig, ax = plt.subplots()
plt.plot([500, 2_000], [2_200_000, 4_000_000])
ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
ax.yaxis.set_major_formatter(plt.FuncFormatter(format_func))
plt.show()

结果


推荐阅读