python 1/x 绘图比例格式,刻度位置

python 1/x plot scale formatting, tick position

我用 Python 绘制了一些数据,并尝试用 FuncFormatter 更改刻度。现在我想将分段更改为整数。我还希望以相同的形式出现较小的滴答声,在我的情况下,它将是 1/x 分段。我希望扩大规模。这些图片将帮助您想象我的问题。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
x = np.array([805.92055,978.82006,564.88627,813.70311,605.73361,263.27184,169.40317])
y = np.array([10,9,8,7,6,3,2])
fig, ax = plt.subplots(figsize =(3.6,2.5))
plt.plot(1/x,y,linestyle ='None',marker='1')
a=0.001
b=0.005
plt.xlim(a,b)
def my_formatter_fun(x, p):
    return "%.0f" % (1/x)         
ax.get_xaxis().set_major_formatter(tick.FuncFormatter(my_formatter_fun))

我怎样才能改变分段以便得到这样的东西?我以为可以在 my_formatter_fun 中添加我的愿望,但我不知道如何做。我怎样才能在 1/x 分布中添加次要标记?我试过 plt.minorticks_on() 但这不起作用,因为它们处于线性位置。

可以使用 matplotlib.ticker.Locator 控制刻度的位置。对于 1/x 刻度,您需要定义自己的自定义定位器:

class ReciprocalLocator(tick.Locator):
    def __init__(self, numticks = 5):
        self.numticks = numticks
    def __call__(self):
        vmin, vmax = self.axis.get_view_interval()
        ticklocs = np.reciprocal(np.linspace(1/vmax, 1/vmin, self.numticks))
        return self.raise_if_exceeds(ticklocs)

您可以通过调用

在您的情节中使用它
ax.get_xaxis().set_major_locator(ReciprocalLocator(numticks=4))
ax.get_xaxis().set_minor_locator(ReciprocalLocator(numticks=20))

这需要更多调整才能将位置移动到漂亮的数字。如需灵感,请查看 matplotlib.ticker.MaxNLocator.

的源代码