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

kit*_*su3 6 python matplotlib

可能重复:
如何删除matplotlib轴中的相对位移

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

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

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

tia*_*ago 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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

# 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

from matplotlib.ticker import FixedFormatter
plt.gca().xaxis.set_major_formatter(FixedFormatter(ll))
Run Code Online (Sandbox Code Playgroud)

但是,这种方法的问题是标签是固定的.如果你想调整/平移图,你必须重新开始.一种更灵活的方法是使用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))
Run Code Online (Sandbox Code Playgroud)

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

if np.absolute(ave_oom - range_oom) >= 3:  # four sig-figs
Run Code Online (Sandbox Code Playgroud)

我通常将其更改为:

if np.absolute(ave_oom - range_oom) >= 5:  # four sig-figs
Run Code Online (Sandbox Code Playgroud)

并发现它适用于我的用途.在matplotlib安装中更改该文件,然后记住在生效之前重新启动python.


tac*_*ell 7

您也可以关闭偏移量:(几乎完全删除如何删除matplotlib轴中的相对偏移)

import matlplotlib is plt

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

这将axes获取当前信息,获取x轴axis对象,然后获取主格式化程序对象并设置useOffset为false(doc).