【问题标题】:Matplotlib: -- how to show all digits on ticks? [duplicate]Matplotlib: -- 如何在刻度上显示所有数字? [复制]
【发布时间】:2013-01-21 15:39:24
【问题描述】:

可能重复:
How to remove relative shift in matplotlib axis

我正在针对日期绘制五位数字(210.10、210.25、211.35 等),我希望 y 轴刻度显示所有数字('214.20' 而不是 '0.20 + 2.14e2')并且无法弄清楚这一点。我尝试将 ticklabel 格式设置为普通格式,但它似乎没有效果。

plt.ticklabel_format(style='plain', axis='y')

关于我明显遗漏的任何提示?

【问题讨论】:

标签: python matplotlib


【解决方案1】:

轴号是根据给定的Formatter 定义的。不幸的是(AFAIK),matplotlib 没有公开一种方法来控制阈值从数字变为较小的数字 + 偏移量。蛮力方法是设置所有 xtick 字符串:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(100, 100.1, 100)
y = np.arange(100)

fig = plt.figure()
plt.plot(x, y)
plt.show()  # original problem

# setting the xticks to have 3 decimal places
xx, locs = plt.xticks()
ll = ['%.3f' % a for a in xx]
plt.xticks(xx, ll)
plt.show()

这实际上与使用字符串设置 FixedFormatter 相同:

from matplotlib.ticker import FixedFormatter
plt.gca().xaxis.set_major_formatter(FixedFormatter(ll))

但是,这种方法的问题是标签是固定的。如果要调整绘图的大小/平移,则必须重新开始。更灵活的方法是使用 FuncFormatter:

def form3(x, pos):
    """ This function returns a string with 3 decimal places, given the input x"""
    return '%.3f' % x

from matplotlib.ticker import FuncFormatter
formatter = FuncFormatter(form3)
gca().xaxis.set_major_formatter(FuncFormatter(formatter))

现在您可以移动绘图并且仍然保持相同的精度。但有时这并不理想。人们并不总是想要一个固定的精度。想要保留默认的 Formatter 行为,只需将阈值增加到它开始添加偏移量的时间。没有公开的机制,所以我最终要做的是更改源代码。这很简单,只需在ticker.py 的一行中更改一个字符。如果你查看那个 github 版本,它在第 497 行:

if np.absolute(ave_oom - range_oom) >= 3:  # four sig-figs

我一般改成:

if np.absolute(ave_oom - range_oom) >= 5:  # four sig-figs

并发现它对我的使用效果很好。在你的 matplotlib 安装中更改那个文件,然后记得在它生效之前重启 python。

【讨论】:

  • 一组出色的答案!非常感谢!
  • 这应该是最好的答案了,我真的不喜欢直接操作斧头。
【解决方案2】:

您也可以只关闭偏移量:(How to remove relative shift in matplotlib axis 的几乎完全相同的副本)

import matlplotlib is plt

plt.plot([1000, 1001, 1002], [1, 2, 3])
plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)
plt.draw()

这会获取当前的 axes,获取 x 轴 axis 对象,然后是主要格式化对象,并将 useOffset 设置为 false (doc)。

【讨论】:

  • 关闭偏移的问题是,当你有大量的数字时,它们会相互重叠。这就是为什么我更喜欢有一个更大的阈值来使用偏移量。
  • @tiago 您应该向matplotlib 提交功能请求,以通过rcParam 设置该阈值。
  • 我知道。但是我懒得买很多matplotlib版本了……
猜你喜欢
  • 2021-11-17
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多