python - 如何在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
解决方案
这是对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()
推荐阅读
- python - 如何将熊猫数据帧逐行写入CSV文件,一次一行?
- python - 如何在 Ubuntu 18.04 中将 pip3 更新到其最新版本?
- css - 每个引导导航栏链接可以单独间隔吗
- xamarin - 更新到 Visual Studio 2017 版本 15.8 预览版后,“无法解析引用:`System.Memory`”或“找不到`System.Memory`”
- javascript - 溢出问题:悬停时隐藏/可见切换。Gif 可在帖子中找到
- git-clean - 我可以找回被 git 清理过的东西吗?
- javascript - indexOf 用于角度打字稿
- django - Django DateTimeField 显示为字符串
- typescript - 如何使用@PnP/SP 从列表中查询列表项和附件?
- html - 提交到数据库时,单选按钮仅选择离子中的第一个值