Matplotlib: - 如何显示刻度线上的所有数字?

时间:2013-01-21 15:39:24

标签: python matplotlib

  

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

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

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

有关明显我遗失的任何暗示?

2 个答案:

答案 0 :(得分:14)

轴编号是根据给定的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

enter image description here

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

enter image description here

这实际上与使用字符串设置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。

答案 1 :(得分:7)

您也可以关闭偏移:(几乎完全是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)。