Python Matplotlib:将轴设置为相对于一个值的增量

Python Matplotlib: Set axis as increments with respect to one value

有时,当绘图放大到足够大时,轴会发生变化,因此会显示类似这样的内容

这意味着 x 值在本例中为 1.565 + 刻度中显示的值。

有没有办法以这种格式设置轴刻度?一旦到了那里,我该如何设置偏移量(在本例中为 1.565)并格式化刻度?

一个。手动放置偏移

我认为最简单的解决方案是绘制 x-offset,而不是 x 本身。然后只需在轴下方添加一个偏移量的文本字段。

import numpy as np
import matplotlib.pyplot as plt

x = np.array([-0.02+np.pi/2, +0.02+np.pi/2])
y = [1,1]

plt.plot(x - np.pi/2, y)
plt.text(1, -0.07, "$+\pi / 2$", ha="right", va="top",
         transform=plt.gca().transAxes)

plt.show()

乙。使用固定格式化程序

或者您可以使用 FixedFormatter 并手动设置其偏移标签。

import numpy as np
import matplotlib.pyplot as plt

x = np.array([-0.02+np.pi/2, +0.02+np.pi/2])
y = [1,1]

plt.plot(x, y)

xticks = np.array([-0.02, -0.01, 0, 0.01, 0.02])

plt.gca().set(xticks = xticks + np.pi/2, 
              xticklabels = xticks)
plt.gca().xaxis.get_major_formatter().set_offset_string("$+\pi / 2$")

plt.show()

这样做的缺点是刻度位置是固定的,因此缩放时会丢失漂亮的标签。

C。使用具有固定偏移量的自定义定位器和格式化程序

这是可能的,但非常复杂。该解决方案看起来类似于 ,但也需要使用定位器。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker

class OffsetLocator(matplotlib.ticker.AutoLocator):
    def __init__(self, offset=0):
        self.fixed_offset = offset
        matplotlib.ticker.AutoLocator.__init__(self)
    def tick_values(self, vmin, vmax):
        v = np.array([vmin,vmax])-self.fixed_offset
        ticks = matplotlib.ticker.AutoLocator.tick_values(self, *v)
        return ticks + self.fixed_offset

class OffsetFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, offset=0, offsettext = None, mathText=True):
        self.fixed_offset = offset
        self.offset_text = offsettext
        matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,
                                                   useMathText=mathText)
    def _set_orderOfMagnitude(self, nothing):
        self.orderOfMagnitude = 0
    def _compute_offset(self):
        return self.fixed_offset
    def get_offset(self):
        return self.offset_text or matplotlib.ticker.ScalarFormatter.get_offset(self)
   

x = np.array([-0.02+np.pi/2, +0.02+np.pi/2])
y = [1,1]

plt.plot(x, y)

plt.gca().xaxis.set_major_locator(OffsetLocator(np.pi/2))
plt.gca().xaxis.set_major_formatter(OffsetFormatter(np.pi/2, offsettext="$+\pi / 2$"))

plt.show()

结果看起来与上面的类似,但与使用某些偏移量的所有其他情况一样表现得完全自然。人们可能只有在调整图形大小、缩放和平移等时才会观察到差异。